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 | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/CreateScalarUnsafe.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\General\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 CreateScalarUnsafeSingle()
{
var test = new VectorCreate__CreateScalarUnsafeSingle();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarUnsafeSingle
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single value = TestLibrary.Generator.GetSingle();
Vector128<Single> result = Vector128.CreateScalarUnsafe(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single value = TestLibrary.Generator.GetSingle();
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.CreateScalarUnsafe), new Type[] { typeof(Single) })
.Invoke(null, new object[] { value });
ValidateResult((Vector128<Single>)(result), value);
}
private void ValidateResult(Vector128<Single> result, Single expectedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Single[] resultElements, Single expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (false /* value is uninitialized */)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128.CreateScalarUnsafe(Single): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
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\General\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 CreateScalarUnsafeSingle()
{
var test = new VectorCreate__CreateScalarUnsafeSingle();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarUnsafeSingle
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single value = TestLibrary.Generator.GetSingle();
Vector128<Single> result = Vector128.CreateScalarUnsafe(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single value = TestLibrary.Generator.GetSingle();
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.CreateScalarUnsafe), new Type[] { typeof(Single) })
.Invoke(null, new object[] { value });
ValidateResult((Vector128<Single>)(result), value);
}
private void ValidateResult(Vector128<Single> result, Single expectedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Single[] resultElements, Single expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (false /* value is uninitialized */)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128.CreateScalarUnsafe(Single): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.IO.FileSystem/tests/Base/SymbolicLinks/BaseSymbolicLinks.FileSystem.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.IO.Enumeration;
using System.Linq;
using Xunit;
namespace System.IO.Tests
{
// Contains test methods that can be used for FileInfo, DirectoryInfo, File or Directory.
public abstract class BaseSymbolicLinks_FileSystem : BaseSymbolicLinks
{
protected abstract bool IsDirectoryTest { get; }
/// <summary>Creates a new file or directory depending on the implementing class.
/// If createOpposite is true, creates a directory if the implementing class is for File or FileInfo, or
/// creates a file if the implementing class is for Directory or DirectoryInfo.</summary>
protected abstract void CreateFileOrDirectory(string path, bool createOpposite = false);
protected abstract void AssertIsCorrectTypeAndDirectoryAttribute(FileSystemInfo linkInfo);
protected abstract void AssertLinkExists(FileSystemInfo linkInfo);
/// <summary>Calls the actual public API for creating a symbolic link.</summary>
protected abstract FileSystemInfo CreateSymbolicLink(string path, string pathToTarget);
private void CreateSymbolicLink_Opposite(string path, string pathToTarget)
{
if (IsDirectoryTest)
{
File.CreateSymbolicLink(path, pathToTarget);
}
else
{
Directory.CreateSymbolicLink(path, pathToTarget);
}
}
/// <summary>Calls the actual public API for resolving the symbolic link target.</summary>
protected abstract FileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget);
[Fact]
public void CreateSymbolicLink_NullPathToTarget()
{
Assert.Throws<ArgumentNullException>(() => CreateSymbolicLink(GetRandomFilePath(), pathToTarget: null));
}
[Theory]
[InlineData("")]
[InlineData("\0")]
public void CreateSymbolicLink_InvalidPathToTarget(string pathToTarget)
{
Assert.Throws<ArgumentException>(() => CreateSymbolicLink(GetRandomFilePath(), pathToTarget));
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_TargetExists()
{
// /path/to/link -> /path/to/existingtarget
string linkPath = GetRandomLinkPath();
string existentTarget = GetRandomFileName();
string targetPath = Path.Join(Path.GetDirectoryName(linkPath), existentTarget);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_TargetExists_WithRedundantSegments()
{
// /path/to/link -> /path/to/../to/existingtarget
string linkPath = GetRandomLinkPath();
string fileName = GetRandomFileName();
string dirPath = Path.GetDirectoryName(linkPath);
string dirName = Path.GetFileName(dirPath);
string targetPath = Path.Join(dirPath, fileName);
string existentTarget = Path.Join("..", dirName, fileName);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_TargetExists()
{
// /path/to/link -> /path/to/existingtarget
string linkPath = GetRandomLinkPath();
string targetPath = GetRandomFilePath();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: targetPath,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_TargetExists_WithRedundantSegments()
{
// /path/to/link -> /path/to/../to/existingtarget
string linkPath = GetRandomLinkPath();
string fileName = GetRandomFileName();
string dirPath = Path.GetDirectoryName(linkPath);
string dirName = Path.GetFileName(dirPath);
string targetPath = Path.Join(dirPath, fileName);
string existentTarget = Path.Join(dirPath, "..", dirName, fileName);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_NonExistentTarget()
{
// /path/to/link -> /path/to/nonexistenttarget
string linkPath = GetRandomLinkPath();
string nonExistentTarget = GetRandomFileName();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: nonExistentTarget,
targetPath: null); // do not create target
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_NonExistentTarget()
{
// /path/to/link -> /path/to/nonexistenttarget
string linkPath = GetRandomLinkPath();
string nonExistentTarget = GetRandomFilePath();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: nonExistentTarget,
targetPath: null); // do not create target
}
protected void ResolveLinkTarget_Throws_NotExists_Internal<T>() where T : Exception
{
string path = GetRandomFilePath();
Assert.Throws<T>(() => ResolveLinkTarget(path, returnFinalTarget: false));
Assert.Throws<T>(() => ResolveLinkTarget(path, returnFinalTarget: true));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ResolveLinkTarget_ReturnsNull_NotALink(bool returnFinalTarget)
{
string path = GetRandomFilePath();
CreateFileOrDirectory(path);
Assert.Null(ResolveLinkTarget(path, returnFinalTarget));
}
[Theory]
[MemberData(nameof(SymbolicLink_ResolveLinkTarget_PathToTarget_Data))]
public void ResolveLinkTarget_Succeeds(string pathToTarget, bool returnFinalTarget)
{
string linkPath = GetRandomLinkPath();
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, pathToTarget);
AssertLinkExists(linkInfo);
AssertIsCorrectTypeAndDirectoryAttribute(linkInfo);
Assert.Equal(pathToTarget, linkInfo.LinkTarget);
FileSystemInfo targetInfo = ResolveLinkTarget(linkPath, returnFinalTarget);
Assert.NotNull(targetInfo);
Assert.False(targetInfo.Exists);
string expectedTargetFullName = Path.IsPathFullyQualified(pathToTarget) ?
pathToTarget : Path.GetFullPath(Path.Join(Path.GetDirectoryName(linkPath), pathToTarget));
Assert.Equal(expectedTargetFullName, targetInfo.FullName);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ResolveLinkTarget_FileSystemEntryExistsButIsNotALink(bool returnFinalTarget)
{
string path = GetRandomFilePath();
CreateFileOrDirectory(path); // entry exists as a normal file, not as a link
FileSystemInfo target = ResolveLinkTarget(path, returnFinalTarget);
Assert.Null(target);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Absolute()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: link2Path,
link2Path: link2Path,
link2Target: filePath,
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Absolute_WithRedundantSegments()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string dirPath = Path.GetDirectoryName(filePath);
string dirName = Path.GetFileName(dirPath);
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: Path.Join(dirPath, "..", dirName, link2FileName),
link2Path: link2Path,
link2Target: Path.Join(dirPath, "..", dirName, fileName),
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Relative()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: link2FileName,
link2Path: link2Path,
link2Target: fileName,
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Relative_WithRedundantSegments()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string dirPath = Path.GetDirectoryName(filePath);
string dirName = Path.GetFileName(dirPath);
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: Path.Join("..", dirName, link2FileName),
link2Path: link2Path,
link2Target: Path.Join("..", dirName, fileName),
filePath: filePath);
}
[Theory]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(20, false)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(20, true)]
public void ResolveLinkTarget_ReturnFinalTarget_ChainOfLinks_Succeeds(int length, bool relative)
{
string target = GetRandomFilePath();
CreateFileOrDirectory(target);
string tail = CreateChainOfLinks(target, length, relative);
FileSystemInfo targetInfo = ResolveLinkTarget(tail, returnFinalTarget: true);
Assert.Equal(target, targetInfo.FullName);
}
[Theory]
// 100 is way beyond the limit (63 in Windows and 40 in Unix), we just want to make sure that a nice exception is thrown when its exceeded.
// We also don't want to test for a very precise limit given that it is very inconsistent across Windows versions.
[InlineData(100, false)]
[InlineData(100, true)]
public void ResolveLinkTarget_ReturnFinalTarget_ChainOfLinks_ExceedsLimit_Throws(int length, bool relative)
{
string target = GetRandomFilePath();
CreateFileOrDirectory(target);
string tail = CreateChainOfLinks(target, length, relative);
Assert.Throws<IOException>(() => ResolveLinkTarget(tail, returnFinalTarget: true));
}
private string CreateChainOfLinks(string target, int length, bool relative)
{
string previousPath = target;
for (int i = 0; i < length; i++)
{
string currentLinkPath = GetRandomLinkPath();
CreateSymbolicLink(currentLinkPath, relative ? Path.GetFileName(previousPath) : previousPath);
previousPath = currentLinkPath;
}
return previousPath;
}
[Fact]
public void DetectSymbolicLinkCycle()
{
// link1 -> link2 -> link1 (cycle)
string link2Path = GetRandomFilePath();
string link1Path = GetRandomFilePath();
FileSystemInfo link1Info = CreateSymbolicLink(link1Path, link2Path);
FileSystemInfo link2Info = CreateSymbolicLink(link2Path, link1Path);
// Can get targets without following symlinks
FileSystemInfo link1Target = ResolveLinkTarget(link1Path, returnFinalTarget: false);
FileSystemInfo link2Target = ResolveLinkTarget(link2Path, returnFinalTarget: false);
// Cannot get target when following symlinks
Assert.Throws<IOException>(() => ResolveLinkTarget(link1Path, returnFinalTarget: true));
Assert.Throws<IOException>(() => ResolveLinkTarget(link2Path, returnFinalTarget: true));
}
[Fact]
public void DetectLinkReferenceToSelf()
{
// link -> link (reference to itself)
string linkPath = GetRandomFilePath();
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, linkPath);
// Can get target without following symlinks
FileSystemInfo linkTarget = ResolveLinkTarget(linkPath, returnFinalTarget: false);
// Cannot get target when following symlinks
Assert.Throws<IOException>(() => ResolveLinkTarget(linkPath, returnFinalTarget: true));
}
[Fact]
public void CreateSymbolicLink_CorrectTargetType_Indirect_Succeeds()
{
// link-2 (file) -> link-1 (file) -> file
// link-2 (dir) -> link-1 (dir) -> dir
string targetPath = GetRandomFilePath();
string firstLinkPath = GetRandomFilePath();
string secondLinkPath = GetRandomFilePath();
CreateFileOrDirectory(targetPath, createOpposite: false);
CreateSymbolicLink(firstLinkPath, targetPath);
FileSystemInfo secondLinkInfo = CreateSymbolicLink(secondLinkPath, firstLinkPath);
Assert.Equal(firstLinkPath, secondLinkInfo.LinkTarget);
Assert.Equal(targetPath, secondLinkInfo.ResolveLinkTarget(true).FullName);
}
private void VerifySymbolicLinkAndResolvedTarget(string linkPath, string expectedLinkTarget, string targetPath = null)
{
// linkPath -> expectedLinkTarget (created in targetPath if not null)
if (targetPath != null)
{
CreateFileOrDirectory(targetPath);
}
FileSystemInfo link = CreateSymbolicLink(linkPath, expectedLinkTarget);
if (targetPath == null)
{
// Behavior different between files and directories when target does not exist
AssertLinkExists(link);
}
else
{
Assert.True(link.Exists); // The target file or directory was created above, so we report Exists of the target for both
}
FileSystemInfo target = ResolveLinkTarget(linkPath, returnFinalTarget: false);
AssertIsCorrectTypeAndDirectoryAttribute(target);
Assert.True(Path.IsPathFullyQualified(target.FullName));
}
/// <summary>
/// Creates and Resolves a chain of links.
/// link1 -> link2 -> file
/// </summary>
private void ResolveLinkTarget_ReturnFinalTarget(string link1Path, string link1Target, string link2Path, string link2Target, string filePath)
{
Assert.True(Path.IsPathFullyQualified(link1Path));
Assert.True(Path.IsPathFullyQualified(link2Path));
Assert.True(Path.IsPathFullyQualified(filePath));
CreateFileOrDirectory(filePath);
// link2 to file
FileSystemInfo link2Info = CreateSymbolicLink(link2Path, link2Target);
Assert.True(link2Info.Exists);
Assert.True(link2Info.Attributes.HasFlag(FileAttributes.ReparsePoint));
AssertIsCorrectTypeAndDirectoryAttribute(link2Info);
AssertPathEquals_RelativeSegments(link2Target, link2Info.LinkTarget);
// link1 to link2
FileSystemInfo link1Info = CreateSymbolicLink(link1Path, link1Target);
Assert.True(link1Info.Exists);
Assert.True(link1Info.Attributes.HasFlag(FileAttributes.ReparsePoint));
AssertIsCorrectTypeAndDirectoryAttribute(link1Info);
AssertPathEquals_RelativeSegments(link1Target, link1Info.LinkTarget);
// link1: do not follow symlinks
FileSystemInfo link1TargetInfo = ResolveLinkTarget(link1Path, returnFinalTarget: false);
Assert.True(link1TargetInfo.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(link1TargetInfo);
Assert.True(link1TargetInfo.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(link2Path, link1TargetInfo.FullName);
AssertPathEquals_RelativeSegments(link2Target, link1TargetInfo.LinkTarget);
// link2: do not follow symlinks
FileSystemInfo link2TargetInfo = ResolveLinkTarget(link2Path, returnFinalTarget: false);
Assert.True(link2TargetInfo.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(link2TargetInfo);
Assert.False(link2TargetInfo.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(filePath, link2TargetInfo.FullName);
Assert.Null(link2TargetInfo.LinkTarget);
// link1: follow symlinks
FileSystemInfo finalTarget = ResolveLinkTarget(link1Path, returnFinalTarget: true);
Assert.True(finalTarget.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(finalTarget);
Assert.False(finalTarget.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(filePath, finalTarget.FullName);
void AssertPathEquals_RelativeSegments(string expected, string actual)
{
#if WINDOWS
// DeviceIoControl canonicalizes the target path i.e: removes redundant segments.
int rootLength = PathInternal.GetRootLength(expected);
if (rootLength > 0)
{
expected = PathInternal.RemoveRelativeSegments(expected, rootLength);
}
#endif
Assert.Equal(expected, actual);
}
}
// Must call inside a remote executor
protected void CreateSymbolicLink_PathToTarget_RelativeToLinkPath_Internal(bool createOpposite)
{
string tempCwd = ChangeCurrentDirectory();
// Create a dummy file or directory in cwd.
string fileOrDirectoryInCwd = GetRandomFileName();
CreateFileOrDirectory(fileOrDirectoryInCwd, createOpposite);
string oneLevelUpPath = Path.Combine(tempCwd, "one-level-up");
Directory.CreateDirectory(oneLevelUpPath);
string linkPath = Path.Combine(oneLevelUpPath, GetRandomLinkName());
// Create a link with a similar Target Path to the one of our dummy file or directory.
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, fileOrDirectoryInCwd);
FileSystemInfo targetInfo = linkInfo.ResolveLinkTarget(returnFinalTarget: false);
// Verify that Target is resolved and is relative to Link's directory and not to the cwd.
Assert.False(targetInfo.Exists);
Assert.Equal(Path.GetDirectoryName(linkInfo.FullName), Path.GetDirectoryName(targetInfo.FullName));
}
protected static string? GetAppExecLinkPath()
{
string localAppDataPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
if (localAppDataPath is null)
{
return null;
}
string windowsAppsDir = Path.Join(localAppDataPath, "Microsoft", "WindowsApps");
if (!Directory.Exists(windowsAppsDir))
{
return null;
}
var opts = new EnumerationOptions { RecurseSubdirectories = true };
return new FileSystemEnumerable<string?>(
windowsAppsDir,
(ref FileSystemEntry entry) => entry.ToFullPath(),
opts)
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
FileSystemName.MatchesWin32Expression("*.exe", entry.FileName) &&
(entry.Attributes & FileAttributes.ReparsePoint) != 0
}.FirstOrDefault();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO.Enumeration;
using System.Linq;
using Xunit;
namespace System.IO.Tests
{
// Contains test methods that can be used for FileInfo, DirectoryInfo, File or Directory.
public abstract class BaseSymbolicLinks_FileSystem : BaseSymbolicLinks
{
protected abstract bool IsDirectoryTest { get; }
/// <summary>Creates a new file or directory depending on the implementing class.
/// If createOpposite is true, creates a directory if the implementing class is for File or FileInfo, or
/// creates a file if the implementing class is for Directory or DirectoryInfo.</summary>
protected abstract void CreateFileOrDirectory(string path, bool createOpposite = false);
protected abstract void AssertIsCorrectTypeAndDirectoryAttribute(FileSystemInfo linkInfo);
protected abstract void AssertLinkExists(FileSystemInfo linkInfo);
/// <summary>Calls the actual public API for creating a symbolic link.</summary>
protected abstract FileSystemInfo CreateSymbolicLink(string path, string pathToTarget);
private void CreateSymbolicLink_Opposite(string path, string pathToTarget)
{
if (IsDirectoryTest)
{
File.CreateSymbolicLink(path, pathToTarget);
}
else
{
Directory.CreateSymbolicLink(path, pathToTarget);
}
}
/// <summary>Calls the actual public API for resolving the symbolic link target.</summary>
protected abstract FileSystemInfo ResolveLinkTarget(string linkPath, bool returnFinalTarget);
[Fact]
public void CreateSymbolicLink_NullPathToTarget()
{
Assert.Throws<ArgumentNullException>(() => CreateSymbolicLink(GetRandomFilePath(), pathToTarget: null));
}
[Theory]
[InlineData("")]
[InlineData("\0")]
public void CreateSymbolicLink_InvalidPathToTarget(string pathToTarget)
{
Assert.Throws<ArgumentException>(() => CreateSymbolicLink(GetRandomFilePath(), pathToTarget));
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_TargetExists()
{
// /path/to/link -> /path/to/existingtarget
string linkPath = GetRandomLinkPath();
string existentTarget = GetRandomFileName();
string targetPath = Path.Join(Path.GetDirectoryName(linkPath), existentTarget);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_TargetExists_WithRedundantSegments()
{
// /path/to/link -> /path/to/../to/existingtarget
string linkPath = GetRandomLinkPath();
string fileName = GetRandomFileName();
string dirPath = Path.GetDirectoryName(linkPath);
string dirName = Path.GetFileName(dirPath);
string targetPath = Path.Join(dirPath, fileName);
string existentTarget = Path.Join("..", dirName, fileName);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_TargetExists()
{
// /path/to/link -> /path/to/existingtarget
string linkPath = GetRandomLinkPath();
string targetPath = GetRandomFilePath();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: targetPath,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_TargetExists_WithRedundantSegments()
{
// /path/to/link -> /path/to/../to/existingtarget
string linkPath = GetRandomLinkPath();
string fileName = GetRandomFileName();
string dirPath = Path.GetDirectoryName(linkPath);
string dirName = Path.GetFileName(dirPath);
string targetPath = Path.Join(dirPath, fileName);
string existentTarget = Path.Join(dirPath, "..", dirName, fileName);
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: existentTarget,
targetPath: targetPath);
}
[Fact]
public void CreateSymbolicLink_RelativeTargetPath_NonExistentTarget()
{
// /path/to/link -> /path/to/nonexistenttarget
string linkPath = GetRandomLinkPath();
string nonExistentTarget = GetRandomFileName();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: nonExistentTarget,
targetPath: null); // do not create target
}
[Fact]
public void CreateSymbolicLink_AbsoluteTargetPath_NonExistentTarget()
{
// /path/to/link -> /path/to/nonexistenttarget
string linkPath = GetRandomLinkPath();
string nonExistentTarget = GetRandomFilePath();
VerifySymbolicLinkAndResolvedTarget(
linkPath: linkPath,
expectedLinkTarget: nonExistentTarget,
targetPath: null); // do not create target
}
protected void ResolveLinkTarget_Throws_NotExists_Internal<T>() where T : Exception
{
string path = GetRandomFilePath();
Assert.Throws<T>(() => ResolveLinkTarget(path, returnFinalTarget: false));
Assert.Throws<T>(() => ResolveLinkTarget(path, returnFinalTarget: true));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ResolveLinkTarget_ReturnsNull_NotALink(bool returnFinalTarget)
{
string path = GetRandomFilePath();
CreateFileOrDirectory(path);
Assert.Null(ResolveLinkTarget(path, returnFinalTarget));
}
[Theory]
[MemberData(nameof(SymbolicLink_ResolveLinkTarget_PathToTarget_Data))]
public void ResolveLinkTarget_Succeeds(string pathToTarget, bool returnFinalTarget)
{
string linkPath = GetRandomLinkPath();
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, pathToTarget);
AssertLinkExists(linkInfo);
AssertIsCorrectTypeAndDirectoryAttribute(linkInfo);
Assert.Equal(pathToTarget, linkInfo.LinkTarget);
FileSystemInfo targetInfo = ResolveLinkTarget(linkPath, returnFinalTarget);
Assert.NotNull(targetInfo);
Assert.False(targetInfo.Exists);
string expectedTargetFullName = Path.IsPathFullyQualified(pathToTarget) ?
pathToTarget : Path.GetFullPath(Path.Join(Path.GetDirectoryName(linkPath), pathToTarget));
Assert.Equal(expectedTargetFullName, targetInfo.FullName);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ResolveLinkTarget_FileSystemEntryExistsButIsNotALink(bool returnFinalTarget)
{
string path = GetRandomFilePath();
CreateFileOrDirectory(path); // entry exists as a normal file, not as a link
FileSystemInfo target = ResolveLinkTarget(path, returnFinalTarget);
Assert.Null(target);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Absolute()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: link2Path,
link2Path: link2Path,
link2Target: filePath,
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Absolute_WithRedundantSegments()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string dirPath = Path.GetDirectoryName(filePath);
string dirName = Path.GetFileName(dirPath);
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: Path.Join(dirPath, "..", dirName, link2FileName),
link2Path: link2Path,
link2Target: Path.Join(dirPath, "..", dirName, fileName),
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Relative()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: link2FileName,
link2Path: link2Path,
link2Target: fileName,
filePath: filePath);
}
[Fact]
public void ResolveLinkTarget_ReturnFinalTarget_Relative_WithRedundantSegments()
{
string link1Path = GetRandomLinkPath();
string link2Path = GetRandomLinkPath();
string filePath = GetRandomFilePath();
string dirPath = Path.GetDirectoryName(filePath);
string dirName = Path.GetFileName(dirPath);
string link2FileName = Path.GetFileName(link2Path);
string fileName = Path.GetFileName(filePath);
ResolveLinkTarget_ReturnFinalTarget(
link1Path: link1Path,
link1Target: Path.Join("..", dirName, link2FileName),
link2Path: link2Path,
link2Target: Path.Join("..", dirName, fileName),
filePath: filePath);
}
[Theory]
[InlineData(1, false)]
[InlineData(10, false)]
[InlineData(20, false)]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(20, true)]
public void ResolveLinkTarget_ReturnFinalTarget_ChainOfLinks_Succeeds(int length, bool relative)
{
string target = GetRandomFilePath();
CreateFileOrDirectory(target);
string tail = CreateChainOfLinks(target, length, relative);
FileSystemInfo targetInfo = ResolveLinkTarget(tail, returnFinalTarget: true);
Assert.Equal(target, targetInfo.FullName);
}
[Theory]
// 100 is way beyond the limit (63 in Windows and 40 in Unix), we just want to make sure that a nice exception is thrown when its exceeded.
// We also don't want to test for a very precise limit given that it is very inconsistent across Windows versions.
[InlineData(100, false)]
[InlineData(100, true)]
public void ResolveLinkTarget_ReturnFinalTarget_ChainOfLinks_ExceedsLimit_Throws(int length, bool relative)
{
string target = GetRandomFilePath();
CreateFileOrDirectory(target);
string tail = CreateChainOfLinks(target, length, relative);
Assert.Throws<IOException>(() => ResolveLinkTarget(tail, returnFinalTarget: true));
}
private string CreateChainOfLinks(string target, int length, bool relative)
{
string previousPath = target;
for (int i = 0; i < length; i++)
{
string currentLinkPath = GetRandomLinkPath();
CreateSymbolicLink(currentLinkPath, relative ? Path.GetFileName(previousPath) : previousPath);
previousPath = currentLinkPath;
}
return previousPath;
}
[Fact]
public void DetectSymbolicLinkCycle()
{
// link1 -> link2 -> link1 (cycle)
string link2Path = GetRandomFilePath();
string link1Path = GetRandomFilePath();
FileSystemInfo link1Info = CreateSymbolicLink(link1Path, link2Path);
FileSystemInfo link2Info = CreateSymbolicLink(link2Path, link1Path);
// Can get targets without following symlinks
FileSystemInfo link1Target = ResolveLinkTarget(link1Path, returnFinalTarget: false);
FileSystemInfo link2Target = ResolveLinkTarget(link2Path, returnFinalTarget: false);
// Cannot get target when following symlinks
Assert.Throws<IOException>(() => ResolveLinkTarget(link1Path, returnFinalTarget: true));
Assert.Throws<IOException>(() => ResolveLinkTarget(link2Path, returnFinalTarget: true));
}
[Fact]
public void DetectLinkReferenceToSelf()
{
// link -> link (reference to itself)
string linkPath = GetRandomFilePath();
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, linkPath);
// Can get target without following symlinks
FileSystemInfo linkTarget = ResolveLinkTarget(linkPath, returnFinalTarget: false);
// Cannot get target when following symlinks
Assert.Throws<IOException>(() => ResolveLinkTarget(linkPath, returnFinalTarget: true));
}
[Fact]
public void CreateSymbolicLink_CorrectTargetType_Indirect_Succeeds()
{
// link-2 (file) -> link-1 (file) -> file
// link-2 (dir) -> link-1 (dir) -> dir
string targetPath = GetRandomFilePath();
string firstLinkPath = GetRandomFilePath();
string secondLinkPath = GetRandomFilePath();
CreateFileOrDirectory(targetPath, createOpposite: false);
CreateSymbolicLink(firstLinkPath, targetPath);
FileSystemInfo secondLinkInfo = CreateSymbolicLink(secondLinkPath, firstLinkPath);
Assert.Equal(firstLinkPath, secondLinkInfo.LinkTarget);
Assert.Equal(targetPath, secondLinkInfo.ResolveLinkTarget(true).FullName);
}
private void VerifySymbolicLinkAndResolvedTarget(string linkPath, string expectedLinkTarget, string targetPath = null)
{
// linkPath -> expectedLinkTarget (created in targetPath if not null)
if (targetPath != null)
{
CreateFileOrDirectory(targetPath);
}
FileSystemInfo link = CreateSymbolicLink(linkPath, expectedLinkTarget);
if (targetPath == null)
{
// Behavior different between files and directories when target does not exist
AssertLinkExists(link);
}
else
{
Assert.True(link.Exists); // The target file or directory was created above, so we report Exists of the target for both
}
FileSystemInfo target = ResolveLinkTarget(linkPath, returnFinalTarget: false);
AssertIsCorrectTypeAndDirectoryAttribute(target);
Assert.True(Path.IsPathFullyQualified(target.FullName));
}
/// <summary>
/// Creates and Resolves a chain of links.
/// link1 -> link2 -> file
/// </summary>
private void ResolveLinkTarget_ReturnFinalTarget(string link1Path, string link1Target, string link2Path, string link2Target, string filePath)
{
Assert.True(Path.IsPathFullyQualified(link1Path));
Assert.True(Path.IsPathFullyQualified(link2Path));
Assert.True(Path.IsPathFullyQualified(filePath));
CreateFileOrDirectory(filePath);
// link2 to file
FileSystemInfo link2Info = CreateSymbolicLink(link2Path, link2Target);
Assert.True(link2Info.Exists);
Assert.True(link2Info.Attributes.HasFlag(FileAttributes.ReparsePoint));
AssertIsCorrectTypeAndDirectoryAttribute(link2Info);
AssertPathEquals_RelativeSegments(link2Target, link2Info.LinkTarget);
// link1 to link2
FileSystemInfo link1Info = CreateSymbolicLink(link1Path, link1Target);
Assert.True(link1Info.Exists);
Assert.True(link1Info.Attributes.HasFlag(FileAttributes.ReparsePoint));
AssertIsCorrectTypeAndDirectoryAttribute(link1Info);
AssertPathEquals_RelativeSegments(link1Target, link1Info.LinkTarget);
// link1: do not follow symlinks
FileSystemInfo link1TargetInfo = ResolveLinkTarget(link1Path, returnFinalTarget: false);
Assert.True(link1TargetInfo.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(link1TargetInfo);
Assert.True(link1TargetInfo.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(link2Path, link1TargetInfo.FullName);
AssertPathEquals_RelativeSegments(link2Target, link1TargetInfo.LinkTarget);
// link2: do not follow symlinks
FileSystemInfo link2TargetInfo = ResolveLinkTarget(link2Path, returnFinalTarget: false);
Assert.True(link2TargetInfo.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(link2TargetInfo);
Assert.False(link2TargetInfo.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(filePath, link2TargetInfo.FullName);
Assert.Null(link2TargetInfo.LinkTarget);
// link1: follow symlinks
FileSystemInfo finalTarget = ResolveLinkTarget(link1Path, returnFinalTarget: true);
Assert.True(finalTarget.Exists);
AssertIsCorrectTypeAndDirectoryAttribute(finalTarget);
Assert.False(finalTarget.Attributes.HasFlag(FileAttributes.ReparsePoint));
Assert.Equal(filePath, finalTarget.FullName);
void AssertPathEquals_RelativeSegments(string expected, string actual)
{
#if WINDOWS
// DeviceIoControl canonicalizes the target path i.e: removes redundant segments.
int rootLength = PathInternal.GetRootLength(expected);
if (rootLength > 0)
{
expected = PathInternal.RemoveRelativeSegments(expected, rootLength);
}
#endif
Assert.Equal(expected, actual);
}
}
// Must call inside a remote executor
protected void CreateSymbolicLink_PathToTarget_RelativeToLinkPath_Internal(bool createOpposite)
{
string tempCwd = ChangeCurrentDirectory();
// Create a dummy file or directory in cwd.
string fileOrDirectoryInCwd = GetRandomFileName();
CreateFileOrDirectory(fileOrDirectoryInCwd, createOpposite);
string oneLevelUpPath = Path.Combine(tempCwd, "one-level-up");
Directory.CreateDirectory(oneLevelUpPath);
string linkPath = Path.Combine(oneLevelUpPath, GetRandomLinkName());
// Create a link with a similar Target Path to the one of our dummy file or directory.
FileSystemInfo linkInfo = CreateSymbolicLink(linkPath, fileOrDirectoryInCwd);
FileSystemInfo targetInfo = linkInfo.ResolveLinkTarget(returnFinalTarget: false);
// Verify that Target is resolved and is relative to Link's directory and not to the cwd.
Assert.False(targetInfo.Exists);
Assert.Equal(Path.GetDirectoryName(linkInfo.FullName), Path.GetDirectoryName(targetInfo.FullName));
}
protected static string? GetAppExecLinkPath()
{
string localAppDataPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
if (localAppDataPath is null)
{
return null;
}
string windowsAppsDir = Path.Join(localAppDataPath, "Microsoft", "WindowsApps");
if (!Directory.Exists(windowsAppsDir))
{
return null;
}
var opts = new EnumerationOptions { RecurseSubdirectories = true };
return new FileSystemEnumerable<string?>(
windowsAppsDir,
(ref FileSystemEntry entry) => entry.ToFullPath(),
opts)
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
FileSystemName.MatchesWin32Expression("*.exe", entry.FileName) &&
(entry.Attributes & FileAttributes.ReparsePoint) != 0
}.FirstOrDefault();
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.IO.Ports/tests/SerialStream/EndWrite.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.IO.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_EndWrite : PortsTest
{
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_Null()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying EndWrite with null asyncResult");
com.Open();
VerifyEndWriteException(com.BaseStream, null, typeof(ArgumentNullException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_MultipleInOrder()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int numBytesToWrite1 = 8, numBytesToWrite2 = 16, numBytesToWrite3 = 10;
Debug.WriteLine("Verifying EndWrite with multiple calls to BeginRead");
com.Open();
IAsyncResult readAsyncResult1 = com.BaseStream.BeginWrite(new byte[numBytesToWrite1], 0, numBytesToWrite1, null, null);
IAsyncResult readAsyncResult2 = com.BaseStream.BeginWrite(new byte[numBytesToWrite2], 0, numBytesToWrite2, null, null);
IAsyncResult readAsyncResult3 = com.BaseStream.BeginWrite(new byte[numBytesToWrite3], 0, numBytesToWrite3, null, null);
com.BaseStream.EndWrite(readAsyncResult1);
com.BaseStream.EndWrite(readAsyncResult2);
com.BaseStream.EndWrite(readAsyncResult3);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_MultipleOutOfOrder()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int numBytesToWrite1 = 8, numBytesToWrite2 = 16, numBytesToWrite3 = 10;
Debug.WriteLine(
"Verifying calling EndWrite with different asyncResults out of order returned from BeginRead");
com.Open();
IAsyncResult readAsyncResult1 = com.BaseStream.BeginWrite(new byte[numBytesToWrite1], 0, numBytesToWrite1, null, null);
IAsyncResult readAsyncResult2 = com.BaseStream.BeginWrite(new byte[numBytesToWrite2], 0, numBytesToWrite2, null, null);
IAsyncResult readAsyncResult3 = com.BaseStream.BeginWrite(new byte[numBytesToWrite3], 0, numBytesToWrite3, null, null);
com.BaseStream.EndWrite(readAsyncResult2);
com.BaseStream.EndWrite(readAsyncResult3);
com.BaseStream.EndWrite(readAsyncResult1);
}
}
#endregion
#region Verification for Test Cases
private void VerifyEndWriteException(Stream serialStream, IAsyncResult asyncResult, Type expectedException)
{
if (expectedException == null)
{
serialStream.EndWrite(asyncResult);
}
else
{
Assert.Throws(expectedException, () => serialStream.EndWrite(asyncResult));
}
}
#endregion
}
}
| // 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.IO.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_EndWrite : PortsTest
{
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_Null()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying EndWrite with null asyncResult");
com.Open();
VerifyEndWriteException(com.BaseStream, null, typeof(ArgumentNullException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_MultipleInOrder()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int numBytesToWrite1 = 8, numBytesToWrite2 = 16, numBytesToWrite3 = 10;
Debug.WriteLine("Verifying EndWrite with multiple calls to BeginRead");
com.Open();
IAsyncResult readAsyncResult1 = com.BaseStream.BeginWrite(new byte[numBytesToWrite1], 0, numBytesToWrite1, null, null);
IAsyncResult readAsyncResult2 = com.BaseStream.BeginWrite(new byte[numBytesToWrite2], 0, numBytesToWrite2, null, null);
IAsyncResult readAsyncResult3 = com.BaseStream.BeginWrite(new byte[numBytesToWrite3], 0, numBytesToWrite3, null, null);
com.BaseStream.EndWrite(readAsyncResult1);
com.BaseStream.EndWrite(readAsyncResult2);
com.BaseStream.EndWrite(readAsyncResult3);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void AsyncResult_MultipleOutOfOrder()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int numBytesToWrite1 = 8, numBytesToWrite2 = 16, numBytesToWrite3 = 10;
Debug.WriteLine(
"Verifying calling EndWrite with different asyncResults out of order returned from BeginRead");
com.Open();
IAsyncResult readAsyncResult1 = com.BaseStream.BeginWrite(new byte[numBytesToWrite1], 0, numBytesToWrite1, null, null);
IAsyncResult readAsyncResult2 = com.BaseStream.BeginWrite(new byte[numBytesToWrite2], 0, numBytesToWrite2, null, null);
IAsyncResult readAsyncResult3 = com.BaseStream.BeginWrite(new byte[numBytesToWrite3], 0, numBytesToWrite3, null, null);
com.BaseStream.EndWrite(readAsyncResult2);
com.BaseStream.EndWrite(readAsyncResult3);
com.BaseStream.EndWrite(readAsyncResult1);
}
}
#endregion
#region Verification for Test Cases
private void VerifyEndWriteException(Stream serialStream, IAsyncResult asyncResult, Type expectedException)
{
if (expectedException == null)
{
serialStream.EndWrite(asyncResult);
}
else
{
Assert.Throws(expectedException, () => serialStream.EndWrite(asyncResult));
}
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Private.Xml.Linq/tests/XPath/XDocument/NavigatorComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Uncomment for more asserts (slows down tests)
// This will add additional asserts to help debugging issues
//#define ASSERT_VERBOSE
// This will trigger comparison between attributes and namespaces
// Currently XDocument is sorting attributes while other XPathNavigators aren't
//#define CHECK_ATTRIBUTE_ORDER
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using Xunit;
namespace System.Xml.XPath.XDocument.Tests.XDocument
{
public class NavigatorComparer : XPathNavigator
{
private XPathNavigator _nav1, _nav2;
private static void CompareNavigators(XPathNavigator a, XPathNavigator b)
{
#if ASSERT_VERBOSE
Assert.NotNull(a);
Assert.NotNull(b);
CompareNodeTypes(a.NodeType, b.NodeType);
if (AreComparableNodes(a.NodeType, b.NodeType))
{
CompareValues(a, b);
Assert.Equal(a.Name, b.Name);
}
#endif
}
private static bool IsWhitespaceOrText(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Whitespace || nodeType == XPathNodeType.Text || nodeType == XPathNodeType.SignificantWhitespace;
}
private static bool IsNamespaceOrAttribute(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Namespace || nodeType == XPathNodeType.Attribute;
}
private static bool AreComparableNodes(XPathNodeType a, XPathNodeType b)
{
bool areBothTextOrWhitespaces = IsWhitespaceOrText(a) && IsWhitespaceOrText(b);
bool areBothNamespacesOrAttributes = IsNamespaceOrAttribute(a) && IsNamespaceOrAttribute(b);
#if CHECK_ATTRIBUTE_ORDER
areBothNamespacesOrAttributes = false
#endif
return !areBothTextOrWhitespaces && !areBothNamespacesOrAttributes;
}
private static void CompareNodeTypes(XPathNodeType a, XPathNodeType b)
{
// XPath.XDocument interprets whitespace as XPathNodeType.Text
// while other XPath navigators do it properly
Assert.Equal(IsWhitespaceOrText(a), IsWhitespaceOrText(b));
Assert.Equal(IsNamespaceOrAttribute(a), IsNamespaceOrAttribute(b));
if (!IsWhitespaceOrText(a) && !IsNamespaceOrAttribute(a))
{
Assert.Equal(a, b);
}
}
private static void CompareValues(XPathNavigator a, XPathNavigator b)
{
// In order to account for Desktop vs CoreCLR difference in implementation of XmlDocument we need to normalize line endings to conform XML specification.
string sa = a.Value.Replace("\r\n", "\n").Replace("\r", "\n");
string sb = b.Value.Replace("\r\n", "\n").Replace("\r", "\n");
Assert.Equal(sa, sb);
}
public NavigatorComparer(XPathNavigator nav1, XPathNavigator nav2)
{
_nav1 = nav1;
_nav2 = nav2;
}
public override string ToString()
{
var r1 = _nav1.ToString();
var r2 = _nav2.ToString();
Assert.Equal(r1, r2);
return r1;
}
public override void SetValue(string value)
{
_nav1.SetValue(value);
_nav2.SetValue(value);
CompareNavigators(_nav1, _nav2);
}
public override object TypedValue
{
get
{
// No point of comparing by ref
return _nav1.TypedValue;
}
}
public override void SetTypedValue(object value)
{
_nav1.SetTypedValue(value);
_nav2.SetTypedValue(value);
CompareNavigators(_nav1, _nav2);
}
public override Type ValueType
{
get
{
var r1 = _nav1.ValueType;
var r2 = _nav2.ValueType;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool ValueAsBoolean
{
get
{
var r1 = _nav1.ValueAsBoolean;
var r2 = _nav2.ValueAsBoolean;
Assert.Equal(r1, r2);
return r1;
}
}
public override DateTime ValueAsDateTime
{
get
{
var r1 = _nav1.ValueAsDateTime;
var r2 = _nav2.ValueAsDateTime;
Assert.Equal(r1, r2);
return r1;
}
}
public override double ValueAsDouble
{
get
{
var r1 = _nav1.ValueAsDouble;
var r2 = _nav2.ValueAsDouble;
Assert.Equal(r1, r2);
return r1;
}
}
public override int ValueAsInt
{
get
{
var r1 = _nav1.ValueAsInt;
var r2 = _nav2.ValueAsInt;
Assert.Equal(r1, r2);
return r1;
}
}
public override long ValueAsLong
{
get
{
var r1 = _nav1.ValueAsLong;
var r2 = _nav2.ValueAsLong;
Assert.Equal(r1, r2);
return r1;
}
}
public override object ValueAs(Type type, IXmlNamespaceResolver resolver)
{
var r1 = _nav1.ValueAs(type, resolver);
var r2 = _nav2.ValueAs(type, resolver);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator CreateNavigator()
{
var r1 = _nav1.CreateNavigator();
var r2 = _nav2.CreateNavigator();
return new NavigatorComparer(r1, r2);
}
public override XmlNameTable NameTable
{
get
{
// comparing NameTable might be unreliable
return _nav1.NameTable;
}
}
public override string LookupNamespace(string value)
{
var r1 = _nav1.LookupNamespace(value);
var r2 = _nav2.LookupNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override string LookupPrefix(string value)
{
var r1 = _nav1.LookupPrefix(value);
var r2 = _nav2.LookupPrefix(value);
Assert.Equal(r1, r2);
return r1;
}
public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope value)
{
var r1 = _nav1.GetNamespacesInScope(value);
var r2 = _nav2.GetNamespacesInScope(value);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator Clone()
{
return new NavigatorComparer(_nav1.Clone(), _nav2.Clone());
}
public override XPathNodeType NodeType
{
get
{
var r1 = _nav1.NodeType;
var r2 = _nav2.NodeType;
CompareNodeTypes(r1, r2);
return r1;
}
}
public override string LocalName
{
get
{
var r1 = _nav1.LocalName;
var r2 = _nav2.LocalName;
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string Name
{
get
{
var r1 = _nav1.Name;
var r2 = _nav2.Name;
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string NamespaceURI
{
get
{
var r1 = _nav1.NamespaceURI;
var r2 = _nav2.NamespaceURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override string Prefix
{
get
{
var r1 = _nav1.Prefix;
var r2 = _nav2.Prefix;
Assert.Equal(r1, r2);
return r1;
}
}
public override string BaseURI
{
get
{
var r1 = _nav1.BaseURI;
var r2 = _nav2.BaseURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsEmptyElement
{
get
{
var r1 = _nav1.IsEmptyElement;
var r2 = _nav2.IsEmptyElement;
Assert.Equal(r1, r2);
return r1;
}
}
public override string XmlLang
{
get
{
var r1 = _nav1.XmlLang;
var r2 = _nav2.XmlLang;
Assert.Equal(r1, r2);
return r1;
}
}
public override XmlReader ReadSubtree()
{
// no point of comparing
return _nav1.ReadSubtree();
}
public override void WriteSubtree(XmlWriter writer)
{
throw new NotSupportedException("WriteSubtree not supported yet.");
}
public override object UnderlyingObject
{
get
{
// no point of comparing
return _nav1.UnderlyingObject;
}
}
public override bool HasAttributes
{
get
{
var r1 = _nav1.HasAttributes;
var r2 = _nav2.HasAttributes;
Assert.Equal(r1, r2);
return r1;
}
}
public override string GetAttribute(string a, string b)
{
var r1 = _nav1.GetAttribute(a, b);
var r2 = _nav2.GetAttribute(a, b);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToAttribute(string a, string b)
{
var r1 = _nav1.MoveToAttribute(a, b);
var r2 = _nav2.MoveToAttribute(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstAttribute()
{
var r1 = _nav1.MoveToFirstAttribute();
var r2 = _nav2.MoveToFirstAttribute();
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextAttribute()
{
var r1 = _nav1.MoveToNextAttribute();
var r2 = _nav2.MoveToNextAttribute();
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override string GetNamespace(string value)
{
var r1 = _nav1.GetNamespace(value);
var r2 = _nav2.GetNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToNamespace(string value)
{
var r1 = _nav1.MoveToNamespace(value);
var r2 = _nav2.MoveToNamespace(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToFirstNamespace(value);
var r2 = _nav2.MoveToFirstNamespace(value);
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToNextNamespace(value);
var r2 = _nav2.MoveToNextNamespace(value);
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNext()
{
var r1 = _nav1.MoveToNext();
var r2 = _nav2.MoveToNext();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToPrevious()
{
var r1 = _nav1.MoveToPrevious();
var r2 = _nav2.MoveToPrevious();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirst()
{
var r1 = _nav1.MoveToFirst();
var r2 = _nav2.MoveToFirst();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstChild()
{
var r1 = _nav1.MoveToFirstChild();
var r2 = _nav2.MoveToFirstChild();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToParent()
{
var r1 = _nav1.MoveToParent();
var r2 = _nav2.MoveToParent();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override void MoveToRoot()
{
_nav1.MoveToRoot();
_nav2.MoveToRoot();
CompareNavigators(_nav1, _nav2);
}
public override bool MoveTo(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp == null)
{
throw new NotSupportedException("MoveTo(XPathNavigator) not supported.");
}
var r1 = _nav1.MoveTo(comp._nav1);
var r2 = _nav2.MoveTo(comp._nav2);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToId(string value)
{
var r1 = _nav1.MoveToId(value);
var r2 = _nav2.MoveToId(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(string a, string b)
{
var r1 = _nav1.MoveToChild(a, b);
var r2 = _nav2.MoveToChild(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(XPathNodeType value)
{
var r1 = _nav1.MoveToChild(value);
var r2 = _nav2.MoveToChild(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b, XPathNavigator c)
{
throw new NotSupportedException("MoveToFollowing(string, string, XPathNavigator) not supported.");
}
public override bool MoveToFollowing(XPathNodeType value)
{
var r1 = _nav1.MoveToFollowing(value);
var r2 = _nav2.MoveToFollowing(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(XPathNodeType a, XPathNavigator b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(string a, string b)
{
var r1 = _nav1.MoveToNext(a, b);
var r2 = _nav2.MoveToNext(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(XPathNodeType value)
{
var r1 = _nav1.MoveToNext(value);
var r2 = _nav2.MoveToNext(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool HasChildren
{
get
{
var r1 = _nav1.HasChildren;
var r2 = _nav2.HasChildren;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsSamePosition(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp != null)
{
var r1 = _nav1.IsSamePosition(comp._nav1);
var r2 = _nav2.IsSamePosition(comp._nav2);
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
else
{
throw new NotSupportedException("IsSamePosition is not supported.");
}
}
public override string Value
{
get
{
#if CHECK_ATTRIBUTE_ORDER
CompareValues(_nav1, _nav2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
CompareValues(_nav1, _nav2);
}
#endif
return _nav1.Value;
}
}
public override object ValueAs(Type value)
{
var r1 = _nav1.ValueAs(value);
return r1;
}
// consider adding in the future
//public override bool IsDescendant(XPathNavigator value)
//public override XmlNodeOrder ComparePosition(XPathNavigator value)
//public override XPathExpression Compile(string value)
//public override XPathNavigator SelectSingleNode(string value)
//public override XPathNavigator SelectSingleNode(string a, IXmlNamespaceResolver b)
//public override XPathNavigator SelectSingleNode(XPathExpression value)
//public override XPathNodeIterator Select(string value);
//public override XPathNodeIterator Select(string a, IXmlNamespaceResolver b)
//public override XPathNodeIterator Select(XPathExpression value)
//public override object Evaluate(string a)
//public override object Evaluate(string, System.Xml.IXmlNamespaceResolver)
//public override object Evaluate(System.Xml.XPath.XPathExpression)
//public override object Evaluate(System.Xml.XPath.XPathExpression, System.Xml.XPath.XPathNodeIterator)
//public override bool Matches(System.Xml.XPath.XPathExpression)
//public override bool Matches(string)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(System.Xml.XPath.XPathNodeType)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(string, string)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(string, string, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(string, string, bool)
//public override bool get_CanEdit()
//public override System.Xml.XmlWriter PrependChild()
//public override System.Xml.XmlWriter AppendChild()
//public override System.Xml.XmlWriter InsertAfter()
//public override System.Xml.XmlWriter InsertBefore()
//public override System.Xml.XmlWriter CreateAttributes()
//public override System.Xml.XmlWriter ReplaceRange(System.Xml.XPath.XPathNavigator)
//public override void ReplaceSelf(string)
//public override void ReplaceSelf(System.Xml.XmlReader)
//public override void ReplaceSelf(System.Xml.XPath.XPathNavigator)
//public override string get_OuterXml()
//public override void set_OuterXml(string)
//public override string get_InnerXml()
//public override void set_InnerXml(string)
//public override void AppendChild(string)
//public override void AppendChild(System.Xml.XmlReader)
//public override void AppendChild(System.Xml.XPath.XPathNavigator)
//public override void PrependChild(string)
//public override void PrependChild(System.Xml.XmlReader)
//public override void PrependChild(System.Xml.XPath.XPathNavigator)
//public override void InsertBefore(string)
//public override void InsertBefore(System.Xml.XmlReader)
//public override void InsertBefore(System.Xml.XPath.XPathNavigator)
//public override void InsertAfter(string)
//public override void InsertAfter(System.Xml.XmlReader)
//public override void InsertAfter(System.Xml.XPath.XPathNavigator)
//public override void DeleteRange(System.Xml.XPath.XPathNavigator)
//public override void DeleteSelf()
//public override void PrependChildElement(string, string, string, string)
//public override void AppendChildElement(string, string, string, string)
//public override void InsertElementBefore(string, string, string, string)
//public override void InsertElementAfter(string, string, string, string)
//public override void CreateAttribute(string, string, string, string)
//public override bool Equals(object)
//public override Int32 GetHashCode()
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Uncomment for more asserts (slows down tests)
// This will add additional asserts to help debugging issues
//#define ASSERT_VERBOSE
// This will trigger comparison between attributes and namespaces
// Currently XDocument is sorting attributes while other XPathNavigators aren't
//#define CHECK_ATTRIBUTE_ORDER
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using Xunit;
namespace System.Xml.XPath.XDocument.Tests.XDocument
{
public class NavigatorComparer : XPathNavigator
{
private XPathNavigator _nav1, _nav2;
private static void CompareNavigators(XPathNavigator a, XPathNavigator b)
{
#if ASSERT_VERBOSE
Assert.NotNull(a);
Assert.NotNull(b);
CompareNodeTypes(a.NodeType, b.NodeType);
if (AreComparableNodes(a.NodeType, b.NodeType))
{
CompareValues(a, b);
Assert.Equal(a.Name, b.Name);
}
#endif
}
private static bool IsWhitespaceOrText(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Whitespace || nodeType == XPathNodeType.Text || nodeType == XPathNodeType.SignificantWhitespace;
}
private static bool IsNamespaceOrAttribute(XPathNodeType nodeType)
{
return nodeType == XPathNodeType.Namespace || nodeType == XPathNodeType.Attribute;
}
private static bool AreComparableNodes(XPathNodeType a, XPathNodeType b)
{
bool areBothTextOrWhitespaces = IsWhitespaceOrText(a) && IsWhitespaceOrText(b);
bool areBothNamespacesOrAttributes = IsNamespaceOrAttribute(a) && IsNamespaceOrAttribute(b);
#if CHECK_ATTRIBUTE_ORDER
areBothNamespacesOrAttributes = false
#endif
return !areBothTextOrWhitespaces && !areBothNamespacesOrAttributes;
}
private static void CompareNodeTypes(XPathNodeType a, XPathNodeType b)
{
// XPath.XDocument interprets whitespace as XPathNodeType.Text
// while other XPath navigators do it properly
Assert.Equal(IsWhitespaceOrText(a), IsWhitespaceOrText(b));
Assert.Equal(IsNamespaceOrAttribute(a), IsNamespaceOrAttribute(b));
if (!IsWhitespaceOrText(a) && !IsNamespaceOrAttribute(a))
{
Assert.Equal(a, b);
}
}
private static void CompareValues(XPathNavigator a, XPathNavigator b)
{
// In order to account for Desktop vs CoreCLR difference in implementation of XmlDocument we need to normalize line endings to conform XML specification.
string sa = a.Value.Replace("\r\n", "\n").Replace("\r", "\n");
string sb = b.Value.Replace("\r\n", "\n").Replace("\r", "\n");
Assert.Equal(sa, sb);
}
public NavigatorComparer(XPathNavigator nav1, XPathNavigator nav2)
{
_nav1 = nav1;
_nav2 = nav2;
}
public override string ToString()
{
var r1 = _nav1.ToString();
var r2 = _nav2.ToString();
Assert.Equal(r1, r2);
return r1;
}
public override void SetValue(string value)
{
_nav1.SetValue(value);
_nav2.SetValue(value);
CompareNavigators(_nav1, _nav2);
}
public override object TypedValue
{
get
{
// No point of comparing by ref
return _nav1.TypedValue;
}
}
public override void SetTypedValue(object value)
{
_nav1.SetTypedValue(value);
_nav2.SetTypedValue(value);
CompareNavigators(_nav1, _nav2);
}
public override Type ValueType
{
get
{
var r1 = _nav1.ValueType;
var r2 = _nav2.ValueType;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool ValueAsBoolean
{
get
{
var r1 = _nav1.ValueAsBoolean;
var r2 = _nav2.ValueAsBoolean;
Assert.Equal(r1, r2);
return r1;
}
}
public override DateTime ValueAsDateTime
{
get
{
var r1 = _nav1.ValueAsDateTime;
var r2 = _nav2.ValueAsDateTime;
Assert.Equal(r1, r2);
return r1;
}
}
public override double ValueAsDouble
{
get
{
var r1 = _nav1.ValueAsDouble;
var r2 = _nav2.ValueAsDouble;
Assert.Equal(r1, r2);
return r1;
}
}
public override int ValueAsInt
{
get
{
var r1 = _nav1.ValueAsInt;
var r2 = _nav2.ValueAsInt;
Assert.Equal(r1, r2);
return r1;
}
}
public override long ValueAsLong
{
get
{
var r1 = _nav1.ValueAsLong;
var r2 = _nav2.ValueAsLong;
Assert.Equal(r1, r2);
return r1;
}
}
public override object ValueAs(Type type, IXmlNamespaceResolver resolver)
{
var r1 = _nav1.ValueAs(type, resolver);
var r2 = _nav2.ValueAs(type, resolver);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator CreateNavigator()
{
var r1 = _nav1.CreateNavigator();
var r2 = _nav2.CreateNavigator();
return new NavigatorComparer(r1, r2);
}
public override XmlNameTable NameTable
{
get
{
// comparing NameTable might be unreliable
return _nav1.NameTable;
}
}
public override string LookupNamespace(string value)
{
var r1 = _nav1.LookupNamespace(value);
var r2 = _nav2.LookupNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override string LookupPrefix(string value)
{
var r1 = _nav1.LookupPrefix(value);
var r2 = _nav2.LookupPrefix(value);
Assert.Equal(r1, r2);
return r1;
}
public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope value)
{
var r1 = _nav1.GetNamespacesInScope(value);
var r2 = _nav2.GetNamespacesInScope(value);
Assert.Equal(r1, r2);
return r1;
}
public override XPathNavigator Clone()
{
return new NavigatorComparer(_nav1.Clone(), _nav2.Clone());
}
public override XPathNodeType NodeType
{
get
{
var r1 = _nav1.NodeType;
var r2 = _nav2.NodeType;
CompareNodeTypes(r1, r2);
return r1;
}
}
public override string LocalName
{
get
{
var r1 = _nav1.LocalName;
var r2 = _nav2.LocalName;
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string Name
{
get
{
var r1 = _nav1.Name;
var r2 = _nav2.Name;
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
}
public override string NamespaceURI
{
get
{
var r1 = _nav1.NamespaceURI;
var r2 = _nav2.NamespaceURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override string Prefix
{
get
{
var r1 = _nav1.Prefix;
var r2 = _nav2.Prefix;
Assert.Equal(r1, r2);
return r1;
}
}
public override string BaseURI
{
get
{
var r1 = _nav1.BaseURI;
var r2 = _nav2.BaseURI;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsEmptyElement
{
get
{
var r1 = _nav1.IsEmptyElement;
var r2 = _nav2.IsEmptyElement;
Assert.Equal(r1, r2);
return r1;
}
}
public override string XmlLang
{
get
{
var r1 = _nav1.XmlLang;
var r2 = _nav2.XmlLang;
Assert.Equal(r1, r2);
return r1;
}
}
public override XmlReader ReadSubtree()
{
// no point of comparing
return _nav1.ReadSubtree();
}
public override void WriteSubtree(XmlWriter writer)
{
throw new NotSupportedException("WriteSubtree not supported yet.");
}
public override object UnderlyingObject
{
get
{
// no point of comparing
return _nav1.UnderlyingObject;
}
}
public override bool HasAttributes
{
get
{
var r1 = _nav1.HasAttributes;
var r2 = _nav2.HasAttributes;
Assert.Equal(r1, r2);
return r1;
}
}
public override string GetAttribute(string a, string b)
{
var r1 = _nav1.GetAttribute(a, b);
var r2 = _nav2.GetAttribute(a, b);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToAttribute(string a, string b)
{
var r1 = _nav1.MoveToAttribute(a, b);
var r2 = _nav2.MoveToAttribute(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstAttribute()
{
var r1 = _nav1.MoveToFirstAttribute();
var r2 = _nav2.MoveToFirstAttribute();
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextAttribute()
{
var r1 = _nav1.MoveToNextAttribute();
var r2 = _nav2.MoveToNextAttribute();
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override string GetNamespace(string value)
{
var r1 = _nav1.GetNamespace(value);
var r2 = _nav2.GetNamespace(value);
Assert.Equal(r1, r2);
return r1;
}
public override bool MoveToNamespace(string value)
{
var r1 = _nav1.MoveToNamespace(value);
var r2 = _nav2.MoveToNamespace(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToFirstNamespace(value);
var r2 = _nav2.MoveToFirstNamespace(value);
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNextNamespace(XPathNamespaceScope value)
{
var r1 = _nav1.MoveToNextNamespace(value);
var r2 = _nav2.MoveToNextNamespace(value);
Assert.Equal(r1, r2);
#if CHECK_ATTRIBUTE_ORDER
CompareNavigators(nav1, nav2);
#endif
return r1;
}
public override bool MoveToNext()
{
var r1 = _nav1.MoveToNext();
var r2 = _nav2.MoveToNext();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToPrevious()
{
var r1 = _nav1.MoveToPrevious();
var r2 = _nav2.MoveToPrevious();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirst()
{
var r1 = _nav1.MoveToFirst();
var r2 = _nav2.MoveToFirst();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFirstChild()
{
var r1 = _nav1.MoveToFirstChild();
var r2 = _nav2.MoveToFirstChild();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToParent()
{
var r1 = _nav1.MoveToParent();
var r2 = _nav2.MoveToParent();
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override void MoveToRoot()
{
_nav1.MoveToRoot();
_nav2.MoveToRoot();
CompareNavigators(_nav1, _nav2);
}
public override bool MoveTo(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp == null)
{
throw new NotSupportedException("MoveTo(XPathNavigator) not supported.");
}
var r1 = _nav1.MoveTo(comp._nav1);
var r2 = _nav2.MoveTo(comp._nav2);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToId(string value)
{
var r1 = _nav1.MoveToId(value);
var r2 = _nav2.MoveToId(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(string a, string b)
{
var r1 = _nav1.MoveToChild(a, b);
var r2 = _nav2.MoveToChild(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToChild(XPathNodeType value)
{
var r1 = _nav1.MoveToChild(value);
var r2 = _nav2.MoveToChild(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(string a, string b, XPathNavigator c)
{
throw new NotSupportedException("MoveToFollowing(string, string, XPathNavigator) not supported.");
}
public override bool MoveToFollowing(XPathNodeType value)
{
var r1 = _nav1.MoveToFollowing(value);
var r2 = _nav2.MoveToFollowing(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToFollowing(XPathNodeType a, XPathNavigator b)
{
var r1 = _nav1.MoveToFollowing(a, b);
var r2 = _nav2.MoveToFollowing(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(string a, string b)
{
var r1 = _nav1.MoveToNext(a, b);
var r2 = _nav2.MoveToNext(a, b);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool MoveToNext(XPathNodeType value)
{
var r1 = _nav1.MoveToNext(value);
var r2 = _nav2.MoveToNext(value);
Assert.Equal(r1, r2);
CompareNavigators(_nav1, _nav2);
return r1;
}
public override bool HasChildren
{
get
{
var r1 = _nav1.HasChildren;
var r2 = _nav2.HasChildren;
Assert.Equal(r1, r2);
return r1;
}
}
public override bool IsSamePosition(XPathNavigator value)
{
NavigatorComparer comp = value as NavigatorComparer;
if (comp != null)
{
var r1 = _nav1.IsSamePosition(comp._nav1);
var r2 = _nav2.IsSamePosition(comp._nav2);
#if CHECK_ATTRIBUTE_ORDER
Assert.Equal(r1, r2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
Assert.Equal(r1, r2);
}
#endif
return r1;
}
else
{
throw new NotSupportedException("IsSamePosition is not supported.");
}
}
public override string Value
{
get
{
#if CHECK_ATTRIBUTE_ORDER
CompareValues(_nav1, _nav2);
#else
CompareNodeTypes(_nav1.NodeType, _nav2.NodeType);
if (!IsNamespaceOrAttribute(_nav1.NodeType))
{
CompareValues(_nav1, _nav2);
}
#endif
return _nav1.Value;
}
}
public override object ValueAs(Type value)
{
var r1 = _nav1.ValueAs(value);
return r1;
}
// consider adding in the future
//public override bool IsDescendant(XPathNavigator value)
//public override XmlNodeOrder ComparePosition(XPathNavigator value)
//public override XPathExpression Compile(string value)
//public override XPathNavigator SelectSingleNode(string value)
//public override XPathNavigator SelectSingleNode(string a, IXmlNamespaceResolver b)
//public override XPathNavigator SelectSingleNode(XPathExpression value)
//public override XPathNodeIterator Select(string value);
//public override XPathNodeIterator Select(string a, IXmlNamespaceResolver b)
//public override XPathNodeIterator Select(XPathExpression value)
//public override object Evaluate(string a)
//public override object Evaluate(string, System.Xml.IXmlNamespaceResolver)
//public override object Evaluate(System.Xml.XPath.XPathExpression)
//public override object Evaluate(System.Xml.XPath.XPathExpression, System.Xml.XPath.XPathNodeIterator)
//public override bool Matches(System.Xml.XPath.XPathExpression)
//public override bool Matches(string)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(System.Xml.XPath.XPathNodeType)
//public override System.Xml.XPath.XPathNodeIterator SelectChildren(string, string)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectAncestors(string, string, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(System.Xml.XPath.XPathNodeType, bool)
//public override System.Xml.XPath.XPathNodeIterator SelectDescendants(string, string, bool)
//public override bool get_CanEdit()
//public override System.Xml.XmlWriter PrependChild()
//public override System.Xml.XmlWriter AppendChild()
//public override System.Xml.XmlWriter InsertAfter()
//public override System.Xml.XmlWriter InsertBefore()
//public override System.Xml.XmlWriter CreateAttributes()
//public override System.Xml.XmlWriter ReplaceRange(System.Xml.XPath.XPathNavigator)
//public override void ReplaceSelf(string)
//public override void ReplaceSelf(System.Xml.XmlReader)
//public override void ReplaceSelf(System.Xml.XPath.XPathNavigator)
//public override string get_OuterXml()
//public override void set_OuterXml(string)
//public override string get_InnerXml()
//public override void set_InnerXml(string)
//public override void AppendChild(string)
//public override void AppendChild(System.Xml.XmlReader)
//public override void AppendChild(System.Xml.XPath.XPathNavigator)
//public override void PrependChild(string)
//public override void PrependChild(System.Xml.XmlReader)
//public override void PrependChild(System.Xml.XPath.XPathNavigator)
//public override void InsertBefore(string)
//public override void InsertBefore(System.Xml.XmlReader)
//public override void InsertBefore(System.Xml.XPath.XPathNavigator)
//public override void InsertAfter(string)
//public override void InsertAfter(System.Xml.XmlReader)
//public override void InsertAfter(System.Xml.XPath.XPathNavigator)
//public override void DeleteRange(System.Xml.XPath.XPathNavigator)
//public override void DeleteSelf()
//public override void PrependChildElement(string, string, string, string)
//public override void AppendChildElement(string, string, string, string)
//public override void InsertElementBefore(string, string, string, string)
//public override void InsertElementAfter(string, string, string, string)
//public override void CreateAttribute(string, string, string, string)
//public override bool Equals(object)
//public override Int32 GetHashCode()
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.ComponentModel.TypeConverter/tests/MultilineStringConverterTests.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.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Tests
{
public class MultilineStringConverterTests : ConverterTestBase
{
[Fact]
public static void ConvertTo_WithContext_MultilineStringConverter()
{
using (new ThreadCultureChange(null, CultureInfo.InvariantCulture))
{
ConvertTo_WithContext(new object[1, 3]
{
{ "any string", "(Text)", null }
},
new MultilineStringConverter());
}
}
}
}
| // 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.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.ComponentModel.Tests
{
public class MultilineStringConverterTests : ConverterTestBase
{
[Fact]
public static void ConvertTo_WithContext_MultilineStringConverter()
{
using (new ThreadCultureChange(null, CultureInfo.InvariantCulture))
{
ConvertTo_WithContext(new object[1, 3]
{
{ "any string", "(Text)", null }
},
new MultilineStringConverter());
}
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.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.Globalization;
using System.IO;
namespace System.Net.NetworkInformation
{
internal static partial class StringParsingHelpers
{
private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting
internal static int ParseNumSocketConnections(string filePath, string protocolName)
{
// Parse the number of active connections out of /proc/net/sockstat
string sockstatFile = ReadAllText(filePath);
int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal);
int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal);
string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
StringParser sockstatParser = new StringParser(tcpLineData, ' ');
sockstatParser.MoveNextOrFail(); // Skip "<name>:"
sockstatParser.MoveNextOrFail(); // Skip: "inuse"
return sockstatParser.ParseNextInt32();
}
internal static TcpConnectionInformation[] ParseActiveTcpConnectionsFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
string tcp4FileContents = ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
// First line is header in each file.
TcpConnectionInformation[] connections = new TcpConnectionInformation[count];
int index = 0;
int skip = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
connections[index] = ParseTcpConnectionInformationFromLine(line);
if (connections[index].State == TcpState.Listen)
{
skip++;
}
else
{
index++;
}
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
connections[index] = ParseTcpConnectionInformationFromLine(line);
if (connections[index].State == TcpState.Listen)
{
skip++;
}
else
{
index++;
}
}
if (skip != 0)
{
Array.Resize(ref connections, connections.Length - skip);
}
return connections;
}
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
string tcp4FileContents = ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[count];
int index = 0;
int skip = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v4connections[i]);
if (ti.State == TcpState.Listen)
{
endPoints[index] = ti.LocalEndPoint;
index++;
}
else
{
skip++;
}
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v6connections[i]);
if (ti.State == TcpState.Listen)
{
endPoints[index] = ti.LocalEndPoint;
index++;
}
else
{
skip++;
}
}
if (skip != 0)
{
Array.Resize(ref endPoints, endPoints.Length - skip);
}
return endPoints;
}
public static IPEndPoint[] ParseActiveUdpListenersFromFiles(string udp4File, string udp6File)
{
string udp4FileContents = ReadAllText(udp4File);
string[] v4connections = udp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string udp6FileContents = ReadAllText(udp6File);
string[] v6connections = udp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
IPEndPoint[] endPoints = new IPEndPoint[count];
int index = 0;
// UDP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// UDP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
// Parsing logic for local and remote addresses and ports, as well as socket state.
internal static TcpConnectionInformation ParseTcpConnectionInformationFromLine(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext(); // local_address
IPEndPoint localEndPoint = ParseAddressAndPort(localAddressAndPort);
string remoteAddressAndPort = parser.MoveAndExtractNext(); // rem_address
IPEndPoint remoteEndPoint = ParseAddressAndPort(remoteAddressAndPort);
string socketStateHex = parser.MoveAndExtractNext();
int nativeTcpState;
if (!int.TryParse(socketStateHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out nativeTcpState))
{
throw ExceptionHelper.CreateForParseFailure();
}
TcpState tcpState = MapTcpState(nativeTcpState);
return new SimpleTcpConnectionInformation(localEndPoint, remoteEndPoint, tcpState);
}
// Common parsing logic for the local connection information.
private static IPEndPoint ParseLocalConnectionInformation(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext();
int indexOfColon = localAddressAndPort.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
IPAddress localIPAddress = ParseHexIPAddress(localAddressAndPort.AsSpan(0, indexOfColon));
ReadOnlySpan<char> portSpan = localAddressAndPort.AsSpan(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1));
int localPort;
if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(localIPAddress, localPort);
}
private static IPEndPoint ParseAddressAndPort(string colonSeparatedAddress)
{
int indexOfColon = colonSeparatedAddress.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
IPAddress ipAddress = ParseHexIPAddress(colonSeparatedAddress.AsSpan(0, indexOfColon));
ReadOnlySpan<char> portSpan = colonSeparatedAddress.AsSpan(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1));
int port;
if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(ipAddress, port);
}
// Maps from Linux TCP states to .NET TcpStates.
private static TcpState MapTcpState(int state)
{
return Interop.Sys.MapTcpState((int)state);
}
internal static IPAddress ParseHexIPAddress(ReadOnlySpan<char> remoteAddressString)
{
if (remoteAddressString.Length <= 8) // IPv4 Address
{
return ParseIPv4HexString(remoteAddressString);
}
else if (remoteAddressString.Length == 32) // IPv6 Address
{
return ParseIPv6HexString(remoteAddressString);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
// Simply converts the hex string into a long and uses the IPAddress(long) constructor.
// Strings passed to this method must be 8 or less characters in length (32-bit address).
private static IPAddress ParseIPv4HexString(ReadOnlySpan<char> hexAddress)
{
IPAddress ipAddress;
long addressValue;
if (!long.TryParse(hexAddress, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out addressValue))
{
throw ExceptionHelper.CreateForParseFailure();
}
ipAddress = new IPAddress(addressValue);
return ipAddress;
}
// Parses a 128-bit IPv6 Address stored as 4 concatenated 32-bit hex numbers.
// If isSequence is true it assumes that hexAddress is in sequence of IPv6 bytes.
// First number corresponds to lower address part
// E.g. IP-address: fe80::215:5dff:fe00:402
// It's bytes in direct order: FE-80-00-00 00-00-00-00 02-15-5D-FF FE-00-04-02
// It's represenation in /proc/net/tcp6: 00-00-80-FE 00-00-00-00 FF-5D-15-02 02-04-00-FE
// (dashes and spaces added above for readability)
// Strings passed to this must be 32 characters in length.
private static IPAddress ParseIPv6HexString(ReadOnlySpan<char> hexAddress, bool isNetworkOrder = false)
{
Debug.Assert(hexAddress.Length == 32);
Span<byte> addressBytes = stackalloc byte[16];
if (isNetworkOrder || !BitConverter.IsLittleEndian)
{
for (int i = 0; i < 16; i++)
{
addressBytes[i] = (byte)(HexToByte(hexAddress[(i * 2)]) * 16
+ HexToByte(hexAddress[(i * 2) + 1]));
}
}
else
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
int srcIndex = i * 4 + 3 - j;
int targetIndex = i * 4 + j;
addressBytes[targetIndex] = (byte)(HexToByte(hexAddress[srcIndex * 2]) * 16
+ HexToByte(hexAddress[srcIndex * 2 + 1]));
}
}
}
IPAddress ipAddress = new IPAddress(addressBytes);
return ipAddress;
}
private static byte HexToByte(char val)
{
int result = HexConverter.FromChar(val);
if (result == 0xFF)
{
throw ExceptionHelper.CreateForParseFailure();
}
return (byte)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.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Net.NetworkInformation
{
internal static partial class StringParsingHelpers
{
private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting
internal static int ParseNumSocketConnections(string filePath, string protocolName)
{
// Parse the number of active connections out of /proc/net/sockstat
string sockstatFile = ReadAllText(filePath);
int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal);
int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal);
string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
StringParser sockstatParser = new StringParser(tcpLineData, ' ');
sockstatParser.MoveNextOrFail(); // Skip "<name>:"
sockstatParser.MoveNextOrFail(); // Skip: "inuse"
return sockstatParser.ParseNextInt32();
}
internal static TcpConnectionInformation[] ParseActiveTcpConnectionsFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
string tcp4FileContents = ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
// First line is header in each file.
TcpConnectionInformation[] connections = new TcpConnectionInformation[count];
int index = 0;
int skip = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
connections[index] = ParseTcpConnectionInformationFromLine(line);
if (connections[index].State == TcpState.Listen)
{
skip++;
}
else
{
index++;
}
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
connections[index] = ParseTcpConnectionInformationFromLine(line);
if (connections[index].State == TcpState.Listen)
{
skip++;
}
else
{
index++;
}
}
if (skip != 0)
{
Array.Resize(ref connections, connections.Length - skip);
}
return connections;
}
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
string tcp4FileContents = ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[count];
int index = 0;
int skip = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v4connections[i]);
if (ti.State == TcpState.Listen)
{
endPoints[index] = ti.LocalEndPoint;
index++;
}
else
{
skip++;
}
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v6connections[i]);
if (ti.State == TcpState.Listen)
{
endPoints[index] = ti.LocalEndPoint;
index++;
}
else
{
skip++;
}
}
if (skip != 0)
{
Array.Resize(ref endPoints, endPoints.Length - skip);
}
return endPoints;
}
public static IPEndPoint[] ParseActiveUdpListenersFromFiles(string udp4File, string udp6File)
{
string udp4FileContents = ReadAllText(udp4File);
string[] v4connections = udp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string udp6FileContents = ReadAllText(udp6File);
string[] v6connections = udp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file. On WSL, this file may be empty.
int count = 0;
if (v4connections.Length > 0)
{
count += v4connections.Length - 1;
}
if (v6connections.Length > 0)
{
count += v6connections.Length - 1;
}
IPEndPoint[] endPoints = new IPEndPoint[count];
int index = 0;
// UDP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// UDP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
// Parsing logic for local and remote addresses and ports, as well as socket state.
internal static TcpConnectionInformation ParseTcpConnectionInformationFromLine(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext(); // local_address
IPEndPoint localEndPoint = ParseAddressAndPort(localAddressAndPort);
string remoteAddressAndPort = parser.MoveAndExtractNext(); // rem_address
IPEndPoint remoteEndPoint = ParseAddressAndPort(remoteAddressAndPort);
string socketStateHex = parser.MoveAndExtractNext();
int nativeTcpState;
if (!int.TryParse(socketStateHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out nativeTcpState))
{
throw ExceptionHelper.CreateForParseFailure();
}
TcpState tcpState = MapTcpState(nativeTcpState);
return new SimpleTcpConnectionInformation(localEndPoint, remoteEndPoint, tcpState);
}
// Common parsing logic for the local connection information.
private static IPEndPoint ParseLocalConnectionInformation(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext();
int indexOfColon = localAddressAndPort.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
IPAddress localIPAddress = ParseHexIPAddress(localAddressAndPort.AsSpan(0, indexOfColon));
ReadOnlySpan<char> portSpan = localAddressAndPort.AsSpan(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1));
int localPort;
if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(localIPAddress, localPort);
}
private static IPEndPoint ParseAddressAndPort(string colonSeparatedAddress)
{
int indexOfColon = colonSeparatedAddress.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
IPAddress ipAddress = ParseHexIPAddress(colonSeparatedAddress.AsSpan(0, indexOfColon));
ReadOnlySpan<char> portSpan = colonSeparatedAddress.AsSpan(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1));
int port;
if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(ipAddress, port);
}
// Maps from Linux TCP states to .NET TcpStates.
private static TcpState MapTcpState(int state)
{
return Interop.Sys.MapTcpState((int)state);
}
internal static IPAddress ParseHexIPAddress(ReadOnlySpan<char> remoteAddressString)
{
if (remoteAddressString.Length <= 8) // IPv4 Address
{
return ParseIPv4HexString(remoteAddressString);
}
else if (remoteAddressString.Length == 32) // IPv6 Address
{
return ParseIPv6HexString(remoteAddressString);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
// Simply converts the hex string into a long and uses the IPAddress(long) constructor.
// Strings passed to this method must be 8 or less characters in length (32-bit address).
private static IPAddress ParseIPv4HexString(ReadOnlySpan<char> hexAddress)
{
IPAddress ipAddress;
long addressValue;
if (!long.TryParse(hexAddress, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out addressValue))
{
throw ExceptionHelper.CreateForParseFailure();
}
ipAddress = new IPAddress(addressValue);
return ipAddress;
}
// Parses a 128-bit IPv6 Address stored as 4 concatenated 32-bit hex numbers.
// If isSequence is true it assumes that hexAddress is in sequence of IPv6 bytes.
// First number corresponds to lower address part
// E.g. IP-address: fe80::215:5dff:fe00:402
// It's bytes in direct order: FE-80-00-00 00-00-00-00 02-15-5D-FF FE-00-04-02
// It's represenation in /proc/net/tcp6: 00-00-80-FE 00-00-00-00 FF-5D-15-02 02-04-00-FE
// (dashes and spaces added above for readability)
// Strings passed to this must be 32 characters in length.
private static IPAddress ParseIPv6HexString(ReadOnlySpan<char> hexAddress, bool isNetworkOrder = false)
{
Debug.Assert(hexAddress.Length == 32);
Span<byte> addressBytes = stackalloc byte[16];
if (isNetworkOrder || !BitConverter.IsLittleEndian)
{
for (int i = 0; i < 16; i++)
{
addressBytes[i] = (byte)(HexToByte(hexAddress[(i * 2)]) * 16
+ HexToByte(hexAddress[(i * 2) + 1]));
}
}
else
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
int srcIndex = i * 4 + 3 - j;
int targetIndex = i * 4 + j;
addressBytes[targetIndex] = (byte)(HexToByte(hexAddress[srcIndex * 2]) * 16
+ HexToByte(hexAddress[srcIndex * 2 + 1]));
}
}
}
IPAddress ipAddress = new IPAddress(addressBytes);
return ipAddress;
}
private static byte HexToByte(char val)
{
int result = HexConverter.FromChar(val);
if (result == 0xFF)
{
throw ExceptionHelper.CreateForParseFailure();
}
return (byte)result;
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ZeroExtendWideningUpper.Vector128.UInt16.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 ZeroExtendWideningUpper_Vector128_UInt16()
{
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
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 SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt16, 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 struct TestStruct
{
public Vector128<UInt16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16 testClass)
{
var result = AdvSimd.ZeroExtendWideningUpper(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16 testClass)
{
fixed (Vector128<UInt16>* pFld1 = &_fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar1;
private Vector128<UInt16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, new UInt32[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.ZeroExtendWideningUpper(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ZeroExtendWideningUpper), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ZeroExtendWideningUpper), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ZeroExtendWideningUpper(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.ZeroExtendWideningUpper(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.ZeroExtendWideningUpper(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
var result = AdvSimd.ZeroExtendWideningUpper(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
fixed (Vector128<UInt16>* pFld1 = &test._fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ZeroExtendWideningUpper(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt16>* pFld1 = &_fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ZeroExtendWideningUpper(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<UInt16> op1, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ZeroExtendWideningUpper(firstOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ZeroExtendWideningUpper)}<UInt32>(Vector128<UInt16>): {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.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 ZeroExtendWideningUpper_Vector128_UInt16()
{
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
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 SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt16, 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 struct TestStruct
{
public Vector128<UInt16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16 testClass)
{
var result = AdvSimd.ZeroExtendWideningUpper(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16 testClass)
{
fixed (Vector128<UInt16>* pFld1 = &_fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar1;
private Vector128<UInt16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, new UInt32[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.ZeroExtendWideningUpper(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ZeroExtendWideningUpper), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ZeroExtendWideningUpper), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ZeroExtendWideningUpper(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.ZeroExtendWideningUpper(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.ZeroExtendWideningUpper(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
var result = AdvSimd.ZeroExtendWideningUpper(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__ZeroExtendWideningUpper_Vector128_UInt16();
fixed (Vector128<UInt16>* pFld1 = &test._fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ZeroExtendWideningUpper(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt16>* pFld1 = &_fld1)
{
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ZeroExtendWideningUpper(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ZeroExtendWideningUpper(
AdvSimd.LoadVector128((UInt16*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<UInt16> op1, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ZeroExtendWideningUpper(firstOp, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ZeroExtendWideningUpper)}<UInt32>(Vector128<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Runtime.Extensions/tests/System/Runtime/ProfileOptimization.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.IO;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Runtime.Tests
{
public class ProfileOptimizationTest : FileCleanupTestBase
{
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(false)]
[InlineData(true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/31853", TestRuntimes.Mono)]
public void ProfileOptimization_CheckFileExists(bool stopProfile)
{
string profileFile = GetTestFileName();
RemoteExecutor.Invoke((_profileFile, _stopProfile) =>
{
// Perform the test work
ProfileOptimization.SetProfileRoot(Path.GetDirectoryName(_profileFile));
ProfileOptimization.StartProfile(Path.GetFileName(_profileFile));
if (bool.Parse(_stopProfile))
{
ProfileOptimization.StartProfile(null);
CheckProfileFileExists(_profileFile);
}
}, profileFile, stopProfile.ToString()).Dispose();
CheckProfileFileExists(profileFile);
}
static void CheckProfileFileExists(string profileFile)
{
// profileFile should deterministically exist now -- if not, wait 5 seconds
bool existed = File.Exists(profileFile);
if (!existed)
{
Thread.Sleep(5000);
}
Assert.True(File.Exists(profileFile), $"'{profileFile}' does not exist");
Assert.True(new FileInfo(profileFile).Length > 0, $"'{profileFile}' is empty");
Assert.True(existed, $"'{profileFile}' did not immediately exist, but did exist 5 seconds later");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Runtime.Tests
{
public class ProfileOptimizationTest : FileCleanupTestBase
{
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(false)]
[InlineData(true)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/31853", TestRuntimes.Mono)]
public void ProfileOptimization_CheckFileExists(bool stopProfile)
{
string profileFile = GetTestFileName();
RemoteExecutor.Invoke((_profileFile, _stopProfile) =>
{
// Perform the test work
ProfileOptimization.SetProfileRoot(Path.GetDirectoryName(_profileFile));
ProfileOptimization.StartProfile(Path.GetFileName(_profileFile));
if (bool.Parse(_stopProfile))
{
ProfileOptimization.StartProfile(null);
CheckProfileFileExists(_profileFile);
}
}, profileFile, stopProfile.ToString()).Dispose();
CheckProfileFileExists(profileFile);
}
static void CheckProfileFileExists(string profileFile)
{
// profileFile should deterministically exist now -- if not, wait 5 seconds
bool existed = File.Exists(profileFile);
if (!existed)
{
Thread.Sleep(5000);
}
Assert.True(File.Exists(profileFile), $"'{profileFile}' does not exist");
Assert.True(new FileInfo(profileFile).Length > 0, $"'{profileFile}' is empty");
Assert.True(existed, $"'{profileFile}' did not immediately exist, but did exist 5 seconds later");
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/opt/virtualstubdispatch/hashcode/cderived4.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 VirtFunc
{
public class CDerived4
{
public override int GetHashCode() { return 4; }
}
}
| // 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 VirtFunc
{
public class CDerived4
{
public override int GetHashCode() { return 4; }
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.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.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using Internal.TypeSystem;
using System.Collections.Generic;
namespace Internal.TypeSystem.Ecma
{
public struct EcmaSignatureParser
{
private TypeSystemContext _tsc;
private Func<EntityHandle, NotFoundBehavior, TypeDesc> _typeResolver;
private NotFoundBehavior _notFoundBehavior;
private EcmaModule _ecmaModule;
private BlobReader _reader;
private ResolutionFailure _resolutionFailure;
private Stack<int> _indexStack;
private List<EmbeddedSignatureData> _embeddedSignatureDataList;
public EcmaSignatureParser(TypeSystemContext tsc, Func<EntityHandle, NotFoundBehavior, TypeDesc> typeResolver, BlobReader reader, NotFoundBehavior notFoundBehavior)
{
_notFoundBehavior = notFoundBehavior;
_ecmaModule = null;
_tsc = tsc;
_typeResolver = typeResolver;
_reader = reader;
_indexStack = null;
_embeddedSignatureDataList = null;
_resolutionFailure = null;
}
public EcmaSignatureParser(EcmaModule ecmaModule, BlobReader reader, NotFoundBehavior notFoundBehavior)
{
_notFoundBehavior = notFoundBehavior;
_ecmaModule = ecmaModule;
_tsc = ecmaModule.Context;
_typeResolver = null;
_reader = reader;
_indexStack = null;
_embeddedSignatureDataList = null;
_resolutionFailure = null;
}
void SetResolutionFailure(ResolutionFailure failure)
{
if (_resolutionFailure == null)
_resolutionFailure = failure;
}
public ResolutionFailure ResolutionFailure => _resolutionFailure;
private TypeDesc ResolveHandle(EntityHandle handle)
{
object resolvedValue;
if (_ecmaModule != null)
{
resolvedValue = _ecmaModule.GetObject(handle, _notFoundBehavior);
}
else
{
resolvedValue = _typeResolver(handle, _notFoundBehavior);
}
if (resolvedValue == null)
return null;
if (resolvedValue is ResolutionFailure failure)
{
SetResolutionFailure(failure);
return null;
}
if (resolvedValue is TypeDesc type)
{
return type;
}
else
{
throw new BadImageFormatException("Type expected");
}
}
private TypeDesc GetWellKnownType(WellKnownType wellKnownType)
{
return _tsc.GetWellKnownType(wellKnownType);
}
private TypeDesc ParseType(SignatureTypeCode typeCode)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
TypeDesc result = ParseTypeImpl(typeCode);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private TypeDesc ParseTypeImpl(SignatureTypeCode typeCode)
{
// Switch on the type.
switch (typeCode)
{
case SignatureTypeCode.Void:
return GetWellKnownType(WellKnownType.Void);
case SignatureTypeCode.Boolean:
return GetWellKnownType(WellKnownType.Boolean);
case SignatureTypeCode.SByte:
return GetWellKnownType(WellKnownType.SByte);
case SignatureTypeCode.Byte:
return GetWellKnownType(WellKnownType.Byte);
case SignatureTypeCode.Int16:
return GetWellKnownType(WellKnownType.Int16);
case SignatureTypeCode.UInt16:
return GetWellKnownType(WellKnownType.UInt16);
case SignatureTypeCode.Int32:
return GetWellKnownType(WellKnownType.Int32);
case SignatureTypeCode.UInt32:
return GetWellKnownType(WellKnownType.UInt32);
case SignatureTypeCode.Int64:
return GetWellKnownType(WellKnownType.Int64);
case SignatureTypeCode.UInt64:
return GetWellKnownType(WellKnownType.UInt64);
case SignatureTypeCode.Single:
return GetWellKnownType(WellKnownType.Single);
case SignatureTypeCode.Double:
return GetWellKnownType(WellKnownType.Double);
case SignatureTypeCode.Char:
return GetWellKnownType(WellKnownType.Char);
case SignatureTypeCode.String:
return GetWellKnownType(WellKnownType.String);
case SignatureTypeCode.IntPtr:
return GetWellKnownType(WellKnownType.IntPtr);
case SignatureTypeCode.UIntPtr:
return GetWellKnownType(WellKnownType.UIntPtr);
case SignatureTypeCode.Object:
return GetWellKnownType(WellKnownType.Object);
case SignatureTypeCode.TypeHandle:
return ResolveHandle(_reader.ReadTypeHandle());
case SignatureTypeCode.SZArray:
{
var elementType = ParseType();
if (elementType == null)
return null;
return _tsc.GetArrayType(elementType);
}
case SignatureTypeCode.Array:
{
var elementType = ParseType();
var rank = _reader.ReadCompressedInteger();
if (_embeddedSignatureDataList != null)
{
var boundsCount = _reader.ReadCompressedInteger();
int []bounds = boundsCount > 0 ? new int[boundsCount] : Array.Empty<int>();
for (int i = 0; i < boundsCount; i++)
bounds[i] = _reader.ReadCompressedInteger();
var lowerBoundsCount = _reader.ReadCompressedInteger();
int []lowerBounds = lowerBoundsCount > 0 ? new int[lowerBoundsCount] : Array.Empty<int>();
bool nonZeroLowerBounds = false;
for (int j = 0; j < lowerBoundsCount; j++)
{
int loBound = _reader.ReadCompressedSignedInteger();
if (loBound != 0)
nonZeroLowerBounds = true;
lowerBounds[j] = loBound;
}
if (boundsCount != 0 || lowerBoundsCount != rank || nonZeroLowerBounds)
{
StringBuilder arrayShapeString = new StringBuilder();
arrayShapeString.Append(string.Join(",", bounds));
arrayShapeString.Append('|');
arrayShapeString.Append(string.Join(",", lowerBounds));
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack) + "|" + arrayShapeString.ToString(), kind = EmbeddedSignatureDataKind.ArrayShape, type = null });
}
}
else
{
var boundsCount = _reader.ReadCompressedInteger();
for (int i = 0; i < boundsCount; i++)
_reader.ReadCompressedInteger();
var lowerBoundsCount = _reader.ReadCompressedInteger();
for (int j = 0; j < lowerBoundsCount; j++)
_reader.ReadCompressedSignedInteger();
}
if (elementType != null)
return _tsc.GetArrayType(elementType, rank);
else
return null;
}
case SignatureTypeCode.ByReference:
{
TypeDesc byRefedType = ParseType();
if (byRefedType != null)
return byRefedType.MakeByRefType();
else
return null;
}
case SignatureTypeCode.Pointer:
{
TypeDesc pointedAtType = ParseType();
if (pointedAtType != null)
return _tsc.GetPointerType(pointedAtType);
else
return null;
}
case SignatureTypeCode.GenericTypeParameter:
return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), false);
case SignatureTypeCode.GenericMethodParameter:
return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), true);
case SignatureTypeCode.GenericTypeInstance:
{
TypeDesc typeDef = ParseType();
MetadataType metadataTypeDef = null;
if (typeDef != null)
{
metadataTypeDef = typeDef as MetadataType;
if (metadataTypeDef == null)
throw new BadImageFormatException();
}
TypeDesc[] instance = new TypeDesc[_reader.ReadCompressedInteger()];
for (int i = 0; i < instance.Length; i++)
{
instance[i] = ParseType();
if (instance[i] == null)
metadataTypeDef = null;
}
if (metadataTypeDef != null)
return _tsc.GetInstantiatedType(metadataTypeDef, new Instantiation(instance));
else
return null;
}
case SignatureTypeCode.TypedReference:
return GetWellKnownType(WellKnownType.TypedReference);
case SignatureTypeCode.FunctionPointer:
MethodSignature sig = ParseMethodSignatureInternal(skipEmbeddedSignatureData: true);
if (sig != null)
return _tsc.GetFunctionPointerType(sig);
else
return null;
default:
ThrowHelper.ThrowBadImageFormatException();
return null;
}
}
private SignatureTypeCode ParseTypeCode(bool skipPinned = true)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
SignatureTypeCode result = ParseTypeCodeImpl(skipPinned);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private SignatureTypeCode ParseTypeCodeImpl(bool skipPinned = true)
{
for (; ; )
{
SignatureTypeCode typeCode = _reader.ReadSignatureTypeCode();
if (typeCode == SignatureTypeCode.RequiredModifier)
{
EntityHandle typeHandle = _reader.ReadTypeHandle();
if (_embeddedSignatureDataList != null)
{
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.RequiredCustomModifier, type = ResolveHandle(typeHandle) });
}
continue;
}
if (typeCode == SignatureTypeCode.OptionalModifier)
{
EntityHandle typeHandle = _reader.ReadTypeHandle();
if (_embeddedSignatureDataList != null)
{
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.OptionalCustomModifier, type = ResolveHandle(typeHandle) });
}
continue;
}
// TODO: treat PINNED in the signature same as modopts (it matters
// in signature matching - you can actually define overloads on this)
if (skipPinned && typeCode == SignatureTypeCode.Pinned)
{
continue;
}
return typeCode;
}
}
public TypeDesc ParseType()
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
TypeDesc result = ParseTypeImpl();
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private TypeDesc ParseTypeImpl()
{
return ParseType(ParseTypeCode());
}
public bool IsFieldSignature
{
get
{
BlobReader peek = _reader;
return peek.ReadSignatureHeader().Kind == SignatureKind.Field;
}
}
public MethodSignature ParseMethodSignature()
{
try
{
_indexStack = new Stack<int>();
_indexStack.Push(0);
_embeddedSignatureDataList = new List<EmbeddedSignatureData>();
return ParseMethodSignatureInternal(skipEmbeddedSignatureData: false);
}
finally
{
_indexStack = null;
_embeddedSignatureDataList = null;
}
}
private MethodSignature ParseMethodSignatureInternal(bool skipEmbeddedSignatureData)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
MethodSignature result = ParseMethodSignatureImpl(skipEmbeddedSignatureData);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private MethodSignature ParseMethodSignatureImpl(bool skipEmbeddedSignatureData)
{
SignatureHeader header = _reader.ReadSignatureHeader();
MethodSignatureFlags flags = 0;
SignatureCallingConvention signatureCallConv = header.CallingConvention;
if (signatureCallConv != SignatureCallingConvention.Default)
{
// Verify that it is safe to convert CallingConvention to MethodSignatureFlags via a simple cast
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionCdecl == (int)SignatureCallingConvention.CDecl);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionStdCall == (int)SignatureCallingConvention.StdCall);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionThisCall == (int)SignatureCallingConvention.ThisCall);
Debug.Assert((int)MethodSignatureFlags.CallingConventionVarargs == (int)SignatureCallingConvention.VarArgs);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConvention == (int)SignatureCallingConvention.Unmanaged);
flags = (MethodSignatureFlags)signatureCallConv;
}
if (!header.IsInstance)
flags |= MethodSignatureFlags.Static;
int arity = header.IsGeneric ? _reader.ReadCompressedInteger() : 0;
int count = _reader.ReadCompressedInteger();
TypeDesc returnType = ParseType();
TypeDesc[] parameters;
if (count > 0)
{
// Get all of the parameters.
parameters = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
parameters[i] = ParseType();
}
}
else
{
parameters = TypeDesc.EmptyTypes;
}
EmbeddedSignatureData[] embeddedSignatureDataArray = (_embeddedSignatureDataList == null || _embeddedSignatureDataList.Count == 0 || skipEmbeddedSignatureData) ? null : _embeddedSignatureDataList.ToArray();
if (_resolutionFailure == null)
return new MethodSignature(flags, arity, returnType, parameters, embeddedSignatureDataArray);
else
return null;
}
public PropertySignature ParsePropertySignature()
{
// As PropertySignature is a struct, we cannot return null
if (_notFoundBehavior != NotFoundBehavior.Throw)
throw new ArgumentException();
SignatureHeader header = _reader.ReadSignatureHeader();
if (header.Kind != SignatureKind.Property)
throw new BadImageFormatException();
bool isStatic = !header.IsInstance;
int count = _reader.ReadCompressedInteger();
TypeDesc returnType = ParseType();
TypeDesc[] parameters;
if (count > 0)
{
// Get all of the parameters.
parameters = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
parameters[i] = ParseType();
}
}
else
{
parameters = TypeDesc.EmptyTypes;
}
return new PropertySignature(isStatic, parameters, returnType);
}
public TypeDesc ParseFieldSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.Field)
throw new BadImageFormatException();
return ParseType();
}
public LocalVariableDefinition[] ParseLocalsSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.LocalVariables)
throw new BadImageFormatException();
int count = _reader.ReadCompressedInteger();
LocalVariableDefinition[] locals;
if (count > 0)
{
locals = new LocalVariableDefinition[count];
for (int i = 0; i < count; i++)
{
bool isPinned = false;
SignatureTypeCode typeCode = ParseTypeCode(skipPinned: false);
if (typeCode == SignatureTypeCode.Pinned)
{
isPinned = true;
typeCode = ParseTypeCode();
}
locals[i] = new LocalVariableDefinition(ParseType(typeCode), isPinned);
}
}
else
{
locals = Array.Empty<LocalVariableDefinition>();
}
if (_resolutionFailure == null)
return locals;
else
return null;
}
public TypeDesc[] ParseMethodSpecSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.MethodSpecification)
throw new BadImageFormatException();
int count = _reader.ReadCompressedInteger();
if (count <= 0)
throw new BadImageFormatException();
TypeDesc[] arguments = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
arguments[i] = ParseType();
}
if (_resolutionFailure == null)
return arguments;
else
return null;
}
public MarshalAsDescriptor ParseMarshalAsDescriptor()
{
Debug.Assert(_reader.RemainingBytes != 0);
NativeTypeKind type = (NativeTypeKind)_reader.ReadByte();
NativeTypeKind arraySubType = NativeTypeKind.Default;
uint? paramNum = null, numElem = null;
string cookie = null;
TypeDesc marshallerType = null;
switch (type)
{
case NativeTypeKind.Array:
{
if (_reader.RemainingBytes != 0)
{
arraySubType = (NativeTypeKind)_reader.ReadByte();
}
if (_reader.RemainingBytes != 0)
{
paramNum = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
int flag = _reader.ReadCompressedInteger();
if (flag == 0)
{
paramNum = null; //paramNum is just a place holder so that numElem can be present
}
}
}
break;
case NativeTypeKind.ByValArray:
{
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
arraySubType = (NativeTypeKind)_reader.ReadByte();
}
}
break;
case NativeTypeKind.ByValTStr:
{
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
}
break;
case NativeTypeKind.SafeArray:
{
// There's nobody to consume SafeArrays, so let's just parse the data
// to avoid asserting later.
// Get optional VARTYPE for the element
if (_reader.RemainingBytes != 0)
{
_reader.ReadCompressedInteger();
}
// VARTYPE can be followed by optional type name
if (_reader.RemainingBytes != 0)
{
_reader.ReadSerializedString();
}
}
break;
case NativeTypeKind.CustomMarshaler:
{
// Read typelib guid
_reader.ReadSerializedString();
// Read native type name
_reader.ReadSerializedString();
// Read managed marshaler name
var customMarshallerTypeName = _reader.ReadSerializedString();
marshallerType = _ecmaModule.GetTypeByCustomAttributeTypeName(customMarshallerTypeName, true);
// Read cookie
cookie = _reader.ReadSerializedString();
}
break;
default:
break;
}
Debug.Assert(_reader.RemainingBytes == 0);
return new MarshalAsDescriptor(type, arraySubType, paramNum, numElem, marshallerType, cookie);
}
}
}
| // 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.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using Internal.TypeSystem;
using System.Collections.Generic;
namespace Internal.TypeSystem.Ecma
{
public struct EcmaSignatureParser
{
private TypeSystemContext _tsc;
private Func<EntityHandle, NotFoundBehavior, TypeDesc> _typeResolver;
private NotFoundBehavior _notFoundBehavior;
private EcmaModule _ecmaModule;
private BlobReader _reader;
private ResolutionFailure _resolutionFailure;
private Stack<int> _indexStack;
private List<EmbeddedSignatureData> _embeddedSignatureDataList;
public EcmaSignatureParser(TypeSystemContext tsc, Func<EntityHandle, NotFoundBehavior, TypeDesc> typeResolver, BlobReader reader, NotFoundBehavior notFoundBehavior)
{
_notFoundBehavior = notFoundBehavior;
_ecmaModule = null;
_tsc = tsc;
_typeResolver = typeResolver;
_reader = reader;
_indexStack = null;
_embeddedSignatureDataList = null;
_resolutionFailure = null;
}
public EcmaSignatureParser(EcmaModule ecmaModule, BlobReader reader, NotFoundBehavior notFoundBehavior)
{
_notFoundBehavior = notFoundBehavior;
_ecmaModule = ecmaModule;
_tsc = ecmaModule.Context;
_typeResolver = null;
_reader = reader;
_indexStack = null;
_embeddedSignatureDataList = null;
_resolutionFailure = null;
}
void SetResolutionFailure(ResolutionFailure failure)
{
if (_resolutionFailure == null)
_resolutionFailure = failure;
}
public ResolutionFailure ResolutionFailure => _resolutionFailure;
private TypeDesc ResolveHandle(EntityHandle handle)
{
object resolvedValue;
if (_ecmaModule != null)
{
resolvedValue = _ecmaModule.GetObject(handle, _notFoundBehavior);
}
else
{
resolvedValue = _typeResolver(handle, _notFoundBehavior);
}
if (resolvedValue == null)
return null;
if (resolvedValue is ResolutionFailure failure)
{
SetResolutionFailure(failure);
return null;
}
if (resolvedValue is TypeDesc type)
{
return type;
}
else
{
throw new BadImageFormatException("Type expected");
}
}
private TypeDesc GetWellKnownType(WellKnownType wellKnownType)
{
return _tsc.GetWellKnownType(wellKnownType);
}
private TypeDesc ParseType(SignatureTypeCode typeCode)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
TypeDesc result = ParseTypeImpl(typeCode);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private TypeDesc ParseTypeImpl(SignatureTypeCode typeCode)
{
// Switch on the type.
switch (typeCode)
{
case SignatureTypeCode.Void:
return GetWellKnownType(WellKnownType.Void);
case SignatureTypeCode.Boolean:
return GetWellKnownType(WellKnownType.Boolean);
case SignatureTypeCode.SByte:
return GetWellKnownType(WellKnownType.SByte);
case SignatureTypeCode.Byte:
return GetWellKnownType(WellKnownType.Byte);
case SignatureTypeCode.Int16:
return GetWellKnownType(WellKnownType.Int16);
case SignatureTypeCode.UInt16:
return GetWellKnownType(WellKnownType.UInt16);
case SignatureTypeCode.Int32:
return GetWellKnownType(WellKnownType.Int32);
case SignatureTypeCode.UInt32:
return GetWellKnownType(WellKnownType.UInt32);
case SignatureTypeCode.Int64:
return GetWellKnownType(WellKnownType.Int64);
case SignatureTypeCode.UInt64:
return GetWellKnownType(WellKnownType.UInt64);
case SignatureTypeCode.Single:
return GetWellKnownType(WellKnownType.Single);
case SignatureTypeCode.Double:
return GetWellKnownType(WellKnownType.Double);
case SignatureTypeCode.Char:
return GetWellKnownType(WellKnownType.Char);
case SignatureTypeCode.String:
return GetWellKnownType(WellKnownType.String);
case SignatureTypeCode.IntPtr:
return GetWellKnownType(WellKnownType.IntPtr);
case SignatureTypeCode.UIntPtr:
return GetWellKnownType(WellKnownType.UIntPtr);
case SignatureTypeCode.Object:
return GetWellKnownType(WellKnownType.Object);
case SignatureTypeCode.TypeHandle:
return ResolveHandle(_reader.ReadTypeHandle());
case SignatureTypeCode.SZArray:
{
var elementType = ParseType();
if (elementType == null)
return null;
return _tsc.GetArrayType(elementType);
}
case SignatureTypeCode.Array:
{
var elementType = ParseType();
var rank = _reader.ReadCompressedInteger();
if (_embeddedSignatureDataList != null)
{
var boundsCount = _reader.ReadCompressedInteger();
int []bounds = boundsCount > 0 ? new int[boundsCount] : Array.Empty<int>();
for (int i = 0; i < boundsCount; i++)
bounds[i] = _reader.ReadCompressedInteger();
var lowerBoundsCount = _reader.ReadCompressedInteger();
int []lowerBounds = lowerBoundsCount > 0 ? new int[lowerBoundsCount] : Array.Empty<int>();
bool nonZeroLowerBounds = false;
for (int j = 0; j < lowerBoundsCount; j++)
{
int loBound = _reader.ReadCompressedSignedInteger();
if (loBound != 0)
nonZeroLowerBounds = true;
lowerBounds[j] = loBound;
}
if (boundsCount != 0 || lowerBoundsCount != rank || nonZeroLowerBounds)
{
StringBuilder arrayShapeString = new StringBuilder();
arrayShapeString.Append(string.Join(",", bounds));
arrayShapeString.Append('|');
arrayShapeString.Append(string.Join(",", lowerBounds));
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack) + "|" + arrayShapeString.ToString(), kind = EmbeddedSignatureDataKind.ArrayShape, type = null });
}
}
else
{
var boundsCount = _reader.ReadCompressedInteger();
for (int i = 0; i < boundsCount; i++)
_reader.ReadCompressedInteger();
var lowerBoundsCount = _reader.ReadCompressedInteger();
for (int j = 0; j < lowerBoundsCount; j++)
_reader.ReadCompressedSignedInteger();
}
if (elementType != null)
return _tsc.GetArrayType(elementType, rank);
else
return null;
}
case SignatureTypeCode.ByReference:
{
TypeDesc byRefedType = ParseType();
if (byRefedType != null)
return byRefedType.MakeByRefType();
else
return null;
}
case SignatureTypeCode.Pointer:
{
TypeDesc pointedAtType = ParseType();
if (pointedAtType != null)
return _tsc.GetPointerType(pointedAtType);
else
return null;
}
case SignatureTypeCode.GenericTypeParameter:
return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), false);
case SignatureTypeCode.GenericMethodParameter:
return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), true);
case SignatureTypeCode.GenericTypeInstance:
{
TypeDesc typeDef = ParseType();
MetadataType metadataTypeDef = null;
if (typeDef != null)
{
metadataTypeDef = typeDef as MetadataType;
if (metadataTypeDef == null)
throw new BadImageFormatException();
}
TypeDesc[] instance = new TypeDesc[_reader.ReadCompressedInteger()];
for (int i = 0; i < instance.Length; i++)
{
instance[i] = ParseType();
if (instance[i] == null)
metadataTypeDef = null;
}
if (metadataTypeDef != null)
return _tsc.GetInstantiatedType(metadataTypeDef, new Instantiation(instance));
else
return null;
}
case SignatureTypeCode.TypedReference:
return GetWellKnownType(WellKnownType.TypedReference);
case SignatureTypeCode.FunctionPointer:
MethodSignature sig = ParseMethodSignatureInternal(skipEmbeddedSignatureData: true);
if (sig != null)
return _tsc.GetFunctionPointerType(sig);
else
return null;
default:
ThrowHelper.ThrowBadImageFormatException();
return null;
}
}
private SignatureTypeCode ParseTypeCode(bool skipPinned = true)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
SignatureTypeCode result = ParseTypeCodeImpl(skipPinned);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private SignatureTypeCode ParseTypeCodeImpl(bool skipPinned = true)
{
for (; ; )
{
SignatureTypeCode typeCode = _reader.ReadSignatureTypeCode();
if (typeCode == SignatureTypeCode.RequiredModifier)
{
EntityHandle typeHandle = _reader.ReadTypeHandle();
if (_embeddedSignatureDataList != null)
{
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.RequiredCustomModifier, type = ResolveHandle(typeHandle) });
}
continue;
}
if (typeCode == SignatureTypeCode.OptionalModifier)
{
EntityHandle typeHandle = _reader.ReadTypeHandle();
if (_embeddedSignatureDataList != null)
{
_embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.OptionalCustomModifier, type = ResolveHandle(typeHandle) });
}
continue;
}
// TODO: treat PINNED in the signature same as modopts (it matters
// in signature matching - you can actually define overloads on this)
if (skipPinned && typeCode == SignatureTypeCode.Pinned)
{
continue;
}
return typeCode;
}
}
public TypeDesc ParseType()
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
TypeDesc result = ParseTypeImpl();
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private TypeDesc ParseTypeImpl()
{
return ParseType(ParseTypeCode());
}
public bool IsFieldSignature
{
get
{
BlobReader peek = _reader;
return peek.ReadSignatureHeader().Kind == SignatureKind.Field;
}
}
public MethodSignature ParseMethodSignature()
{
try
{
_indexStack = new Stack<int>();
_indexStack.Push(0);
_embeddedSignatureDataList = new List<EmbeddedSignatureData>();
return ParseMethodSignatureInternal(skipEmbeddedSignatureData: false);
}
finally
{
_indexStack = null;
_embeddedSignatureDataList = null;
}
}
private MethodSignature ParseMethodSignatureInternal(bool skipEmbeddedSignatureData)
{
if (_indexStack != null)
{
int was = _indexStack.Pop();
_indexStack.Push(was + 1);
_indexStack.Push(0);
}
MethodSignature result = ParseMethodSignatureImpl(skipEmbeddedSignatureData);
if (_indexStack != null)
{
_indexStack.Pop();
}
return result;
}
private MethodSignature ParseMethodSignatureImpl(bool skipEmbeddedSignatureData)
{
SignatureHeader header = _reader.ReadSignatureHeader();
MethodSignatureFlags flags = 0;
SignatureCallingConvention signatureCallConv = header.CallingConvention;
if (signatureCallConv != SignatureCallingConvention.Default)
{
// Verify that it is safe to convert CallingConvention to MethodSignatureFlags via a simple cast
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionCdecl == (int)SignatureCallingConvention.CDecl);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionStdCall == (int)SignatureCallingConvention.StdCall);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionThisCall == (int)SignatureCallingConvention.ThisCall);
Debug.Assert((int)MethodSignatureFlags.CallingConventionVarargs == (int)SignatureCallingConvention.VarArgs);
Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConvention == (int)SignatureCallingConvention.Unmanaged);
flags = (MethodSignatureFlags)signatureCallConv;
}
if (!header.IsInstance)
flags |= MethodSignatureFlags.Static;
int arity = header.IsGeneric ? _reader.ReadCompressedInteger() : 0;
int count = _reader.ReadCompressedInteger();
TypeDesc returnType = ParseType();
TypeDesc[] parameters;
if (count > 0)
{
// Get all of the parameters.
parameters = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
parameters[i] = ParseType();
}
}
else
{
parameters = TypeDesc.EmptyTypes;
}
EmbeddedSignatureData[] embeddedSignatureDataArray = (_embeddedSignatureDataList == null || _embeddedSignatureDataList.Count == 0 || skipEmbeddedSignatureData) ? null : _embeddedSignatureDataList.ToArray();
if (_resolutionFailure == null)
return new MethodSignature(flags, arity, returnType, parameters, embeddedSignatureDataArray);
else
return null;
}
public PropertySignature ParsePropertySignature()
{
// As PropertySignature is a struct, we cannot return null
if (_notFoundBehavior != NotFoundBehavior.Throw)
throw new ArgumentException();
SignatureHeader header = _reader.ReadSignatureHeader();
if (header.Kind != SignatureKind.Property)
throw new BadImageFormatException();
bool isStatic = !header.IsInstance;
int count = _reader.ReadCompressedInteger();
TypeDesc returnType = ParseType();
TypeDesc[] parameters;
if (count > 0)
{
// Get all of the parameters.
parameters = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
parameters[i] = ParseType();
}
}
else
{
parameters = TypeDesc.EmptyTypes;
}
return new PropertySignature(isStatic, parameters, returnType);
}
public TypeDesc ParseFieldSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.Field)
throw new BadImageFormatException();
return ParseType();
}
public LocalVariableDefinition[] ParseLocalsSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.LocalVariables)
throw new BadImageFormatException();
int count = _reader.ReadCompressedInteger();
LocalVariableDefinition[] locals;
if (count > 0)
{
locals = new LocalVariableDefinition[count];
for (int i = 0; i < count; i++)
{
bool isPinned = false;
SignatureTypeCode typeCode = ParseTypeCode(skipPinned: false);
if (typeCode == SignatureTypeCode.Pinned)
{
isPinned = true;
typeCode = ParseTypeCode();
}
locals[i] = new LocalVariableDefinition(ParseType(typeCode), isPinned);
}
}
else
{
locals = Array.Empty<LocalVariableDefinition>();
}
if (_resolutionFailure == null)
return locals;
else
return null;
}
public TypeDesc[] ParseMethodSpecSignature()
{
if (_reader.ReadSignatureHeader().Kind != SignatureKind.MethodSpecification)
throw new BadImageFormatException();
int count = _reader.ReadCompressedInteger();
if (count <= 0)
throw new BadImageFormatException();
TypeDesc[] arguments = new TypeDesc[count];
for (int i = 0; i < count; i++)
{
arguments[i] = ParseType();
}
if (_resolutionFailure == null)
return arguments;
else
return null;
}
public MarshalAsDescriptor ParseMarshalAsDescriptor()
{
Debug.Assert(_reader.RemainingBytes != 0);
NativeTypeKind type = (NativeTypeKind)_reader.ReadByte();
NativeTypeKind arraySubType = NativeTypeKind.Default;
uint? paramNum = null, numElem = null;
string cookie = null;
TypeDesc marshallerType = null;
switch (type)
{
case NativeTypeKind.Array:
{
if (_reader.RemainingBytes != 0)
{
arraySubType = (NativeTypeKind)_reader.ReadByte();
}
if (_reader.RemainingBytes != 0)
{
paramNum = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
int flag = _reader.ReadCompressedInteger();
if (flag == 0)
{
paramNum = null; //paramNum is just a place holder so that numElem can be present
}
}
}
break;
case NativeTypeKind.ByValArray:
{
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
if (_reader.RemainingBytes != 0)
{
arraySubType = (NativeTypeKind)_reader.ReadByte();
}
}
break;
case NativeTypeKind.ByValTStr:
{
if (_reader.RemainingBytes != 0)
{
numElem = (uint)_reader.ReadCompressedInteger();
}
}
break;
case NativeTypeKind.SafeArray:
{
// There's nobody to consume SafeArrays, so let's just parse the data
// to avoid asserting later.
// Get optional VARTYPE for the element
if (_reader.RemainingBytes != 0)
{
_reader.ReadCompressedInteger();
}
// VARTYPE can be followed by optional type name
if (_reader.RemainingBytes != 0)
{
_reader.ReadSerializedString();
}
}
break;
case NativeTypeKind.CustomMarshaler:
{
// Read typelib guid
_reader.ReadSerializedString();
// Read native type name
_reader.ReadSerializedString();
// Read managed marshaler name
var customMarshallerTypeName = _reader.ReadSerializedString();
marshallerType = _ecmaModule.GetTypeByCustomAttributeTypeName(customMarshallerTypeName, true);
// Read cookie
cookie = _reader.ReadSerializedString();
}
break;
default:
break;
}
Debug.Assert(_reader.RemainingBytes == 0);
return new MarshalAsDescriptor(type, arraySubType, paramNum, numElem, marshallerType, cookie);
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/GenericParameterDesc.RuntimeDetermined.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
partial class GenericParameterDesc
{
public sealed override bool IsRuntimeDeterminedSubtype
{
get
{
Debug.Fail("IsRuntimeDeterminedSubtype of an indefinite type");
return false;
}
}
public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Debug.Assert(false);
return this;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
partial class GenericParameterDesc
{
public sealed override bool IsRuntimeDeterminedSubtype
{
get
{
Debug.Fail("IsRuntimeDeterminedSubtype of an indefinite type");
return false;
}
}
public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Debug.Assert(false);
return this;
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Private.CoreLib/src/System/Collections/DictionaryEntry.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.ComponentModel;
namespace System.Collections
{
// A DictionaryEntry holds a key and a value from a dictionary.
// It is returned by IDictionaryEnumerator::GetEntry().
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct DictionaryEntry
{
private object _key; // Do not rename (binary serialization)
private object? _value; // Do not rename (binary serialization)
// Constructs a new DictionaryEnumerator by setting the Key
// and Value fields appropriately.
public DictionaryEntry(object key, object? value)
{
_key = key;
_value = value;
}
public object Key
{
get => _key;
set => _key = value;
}
public object? Value
{
get => _value;
set => _value = value;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void Deconstruct(out object key, out object? value)
{
key = Key;
value = Value;
}
public override string ToString() =>
KeyValuePair.PairToString(_key, _value);
}
}
| // 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.ComponentModel;
namespace System.Collections
{
// A DictionaryEntry holds a key and a value from a dictionary.
// It is returned by IDictionaryEnumerator::GetEntry().
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct DictionaryEntry
{
private object _key; // Do not rename (binary serialization)
private object? _value; // Do not rename (binary serialization)
// Constructs a new DictionaryEnumerator by setting the Key
// and Value fields appropriately.
public DictionaryEntry(object key, object? value)
{
_key = key;
_value = value;
}
public object Key
{
get => _key;
set => _key = value;
}
public object? Value
{
get => _value;
set => _value = value;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void Deconstruct(out object key, out object? value)
{
key = Key;
value = Value;
}
public override string ToString() =>
KeyValuePair.PairToString(_key, _value);
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/GC/Scenarios/GCSimulator/GCSimulator_332.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 3 -dp 0.0 -dw 0.0</CLRTestExecutionArguments>
<IsGCSimulatorTest>true</IsGCSimulatorTest>
<CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="GCSimulator.cs" />
<Compile Include="lifetimefx.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 3 -dp 0.0 -dw 0.0</CLRTestExecutionArguments>
<IsGCSimulatorTest>true</IsGCSimulatorTest>
<CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="GCSimulator.cs" />
<Compile Include="lifetimefx.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/coreclr/tools/aot/Directory.Build.props | <Project>
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
</Project>
| <Project>
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
</Project>
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest269/Generated269.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 Generated269 { .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 MyStruct319`2<T0, T1>
extends [mscorlib]System.ValueType
implements class IBase1`1<!T0>, class IBase2`2<!T0,class BaseClass1>
{
.pack 0
.size 1
.method public hidebysig virtual instance string Method4() cil managed noinlining {
ldstr "MyStruct319::Method4.2557()"
ret
}
.method public hidebysig newslot virtual instance string 'IBase1<T0>.Method4'() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ret
}
.method public hidebysig virtual instance string Method5() cil managed noinlining {
ldstr "MyStruct319::Method5.2559()"
ret
}
.method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ret
}
.method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining {
ldstr "MyStruct319::Method6.2561<"
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 'IBase1<T0>.Method6'<M0>() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method6<[1]>()
ldstr "MyStruct319::Method6.MI.2562<"
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 string Method7<M0>() cil managed noinlining {
ldstr "MyStruct319::Method7.2563<"
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<T0,class BaseClass1>.Method7'<M0>() cil managed noinlining {
.override method instance string class IBase2`2<!T0,class BaseClass1>::Method7<[1]>()
ldstr "MyStruct319::Method7.MI.2564<"
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 ClassMethod635() cil managed noinlining {
ldstr "MyStruct319::ClassMethod635.2565()"
ret
}
.method public hidebysig newslot instance string ClassMethod636() cil managed noinlining {
ldstr "MyStruct319::ClassMethod636.2566()"
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 IBase1`1<+T0>
{
.method public hidebysig newslot abstract virtual instance string Method4() cil managed { }
.method public hidebysig newslot abstract virtual instance string Method5() cil managed { }
.method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { }
}
.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 Generated269 {
.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.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method6<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
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.MyStruct319.T.T<T0,T1,(valuetype MyStruct319`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.T.T<T0,T1,(valuetype MyStruct319`2<!!T0,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase2`2<!!T0,class BaseClass1>::Method7<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.MyStruct319.A.T<T1,(valuetype MyStruct319`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.T<T1,(valuetype MyStruct319`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
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.MyStruct319.A.A<(valuetype MyStruct319`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.A<(valuetype MyStruct319`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,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.MyStruct319.A.B<(valuetype MyStruct319`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.B<(valuetype MyStruct319`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
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.MyStruct319.B.T<T1,(valuetype MyStruct319`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.T<T1,(valuetype MyStruct319`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
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.MyStruct319.B.A<(valuetype MyStruct319`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.A<(valuetype MyStruct319`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
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.MyStruct319.B.B<(valuetype MyStruct319`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.B<(valuetype MyStruct319`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_1)
ldloca V_1
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloca V_1
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ToString() pop
pop
ldloc V_1
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_1
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_2)
ldloca V_2
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloca V_2
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ToString() pop
pop
ldloc V_2
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_2
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_3)
ldloca V_3
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloca V_3
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ToString() pop
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_4)
ldloca V_4
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloca V_4
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ToString() pop
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_5)
ldloca V_5
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
.try { ldloc V_5
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0:
.try { ldloc V_5
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4:
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_6)
ldloca V_6
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
.try { ldloc V_6
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV5
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5:
.try { ldloc V_6
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV6
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV7
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV8
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV9
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_7)
ldloca V_7
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV12
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV13
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV14
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV15
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV16
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV17
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV18
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV19
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_8)
ldloca V_8
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV20
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20:
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV21
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV22
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV23
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV24
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24:
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV27
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV28
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV29
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29:
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 MyStruct319`2<class BaseClass0,class BaseClass0> V_9)
ldloca V_9
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
.try { ldloc V_9
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2:
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_10)
ldloca V_10
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
.try { ldloc V_10
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.T<class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_11)
ldloca V_11
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
.try { ldloc V_11
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_12)
ldloca V_12
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
.try { ldloc V_12
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.T<class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.B<valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_13)
ldloca V_13
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0> ldnull
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_14)
ldloca V_14
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1> ldnull
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_15)
ldloca V_15
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0> ldnull
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_16)
ldloca V_16
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1> ldnull
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`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 Generated269::MethodCallingTest()
call void Generated269::ConstrainedCallsTest()
call void Generated269::StructConstrainedInterfaceCallsTest()
call void Generated269::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 Generated269 { .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 MyStruct319`2<T0, T1>
extends [mscorlib]System.ValueType
implements class IBase1`1<!T0>, class IBase2`2<!T0,class BaseClass1>
{
.pack 0
.size 1
.method public hidebysig virtual instance string Method4() cil managed noinlining {
ldstr "MyStruct319::Method4.2557()"
ret
}
.method public hidebysig newslot virtual instance string 'IBase1<T0>.Method4'() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ret
}
.method public hidebysig virtual instance string Method5() cil managed noinlining {
ldstr "MyStruct319::Method5.2559()"
ret
}
.method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ret
}
.method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining {
ldstr "MyStruct319::Method6.2561<"
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 'IBase1<T0>.Method6'<M0>() cil managed noinlining {
.override method instance string class IBase1`1<!T0>::Method6<[1]>()
ldstr "MyStruct319::Method6.MI.2562<"
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 string Method7<M0>() cil managed noinlining {
ldstr "MyStruct319::Method7.2563<"
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<T0,class BaseClass1>.Method7'<M0>() cil managed noinlining {
.override method instance string class IBase2`2<!T0,class BaseClass1>::Method7<[1]>()
ldstr "MyStruct319::Method7.MI.2564<"
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 ClassMethod635() cil managed noinlining {
ldstr "MyStruct319::ClassMethod635.2565()"
ret
}
.method public hidebysig newslot instance string ClassMethod636() cil managed noinlining {
ldstr "MyStruct319::ClassMethod636.2566()"
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 IBase1`1<+T0>
{
.method public hidebysig newslot abstract virtual instance string Method4() cil managed { }
.method public hidebysig newslot abstract virtual instance string Method5() cil managed { }
.method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { }
}
.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 Generated269 {
.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.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<!!T0>::Method6<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 8
.locals init (string[] actualResults)
ldc.i4.s 3
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 3
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. !!W
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
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.MyStruct319.T.T<T0,T1,(valuetype MyStruct319`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.T.T<T0,T1,(valuetype MyStruct319`2<!!T0,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase1`1<!!T0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<!!T0,!!T1>
callvirt instance string class IBase2`2<!!T0,class BaseClass1>::Method7<object>()
stelem.ref
ldloc.s actualResults
call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[])
ret
}
.method static void M.MyStruct319.A.T<T1,(valuetype MyStruct319`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.T<T1,(valuetype MyStruct319`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,!!T1>
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.MyStruct319.A.A<(valuetype MyStruct319`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.A<(valuetype MyStruct319`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,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.MyStruct319.A.B<(valuetype MyStruct319`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.A.B<(valuetype MyStruct319`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
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.MyStruct319.B.T<T1,(valuetype MyStruct319`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.T<T1,(valuetype MyStruct319`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,!!T1>
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.MyStruct319.B.A<(valuetype MyStruct319`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.A<(valuetype MyStruct319`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
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.MyStruct319.B.B<(valuetype MyStruct319`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed {
.maxstack 9
.locals init (string[] actualResults)
ldc.i4.s 4
newarr string
stloc.s actualResults
ldarg.1
ldstr "M.MyStruct319.B.B<(valuetype MyStruct319`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)"
ldc.i4.s 4
ldloc.s actualResults
ldc.i4.s 0
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
stelem.ref
ldloc.s actualResults
ldc.i4.s 1
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
stelem.ref
ldloc.s actualResults
ldc.i4.s 2
ldarga.s 0
constrained. valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
stelem.ref
ldloc.s actualResults
ldc.i4.s 3
ldarga.s 0
constrained. valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_1)
ldloca V_1
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloca V_1
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ToString() pop
pop
ldloc V_1
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_1
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_2)
ldloca V_2
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloca V_2
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ToString() pop
pop
ldloc V_2
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_2
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_3)
ldloca V_3
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloca V_3
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ToString() pop
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_3
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_4)
ldloca V_4
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloca V_4
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod635()
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod636()
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type MyStruct319"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup ldnull call instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Equals(object) pop
dup call instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::GetHashCode() pop
dup call instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ToString() pop
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method4()
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method5()
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
dup
callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>()
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
pop
ldloc V_4
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
dup
callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_5)
ldloca V_5
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
.try { ldloc V_5
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0:
.try { ldloc V_5
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3:
.try { ldloc V_5
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4:
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_6)
ldloca V_6
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
.try { ldloc V_6
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV5
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5:
.try { ldloc V_6
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV6
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV7
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV8
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8:
.try { ldloc V_6
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV9
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_7)
ldloca V_7
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV12
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV13
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV14
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV15
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15:
.try { ldloc V_7
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV16
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV17
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV18
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18:
.try { ldloc V_7
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV19
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_8)
ldloca V_8
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV20
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20:
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV21
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV22
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV23
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.B.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV24
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24:
.try { ldloc V_8
ldstr "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#MyStruct319::Method5.MI.2560()#MyStruct319::Method6.MI.2562<System.Object>()#"
call void Generated269::M.IBase1.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV27
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.T<class BaseClass1,valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV28
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28:
.try { ldloc V_8
ldstr "MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.IBase2.A.B<valuetype MyStruct319`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV29
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29:
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 MyStruct319`2<class BaseClass0,class BaseClass0> V_9)
ldloca V_9
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
.try { ldloc V_9
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.A<valuetype MyStruct319`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2:
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_10)
ldloca V_10
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
.try { ldloc V_10
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.T<class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.A.B<valuetype MyStruct319`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_11)
ldloca V_11
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
.try { ldloc V_11
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.T<class BaseClass0,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.A<valuetype MyStruct319`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8
} catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8:
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_12)
ldloca V_12
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
.try { ldloc V_12
ldstr "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.T<class BaseClass1,valuetype MyStruct319`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 "MyStruct319::Method4.MI.2558()#" +
"MyStruct319::Method5.MI.2560()#" +
"MyStruct319::Method6.MI.2562<System.Object>()#" +
"MyStruct319::Method7.MI.2564<System.Object>()#"
call void Generated269::M.MyStruct319.B.B<valuetype MyStruct319`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 MyStruct319`2<class BaseClass0,class BaseClass0> V_13)
ldloca V_13
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0> ldnull
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13 box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldloc V_13
box valuetype MyStruct319`2<class BaseClass0,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass0,class BaseClass1> V_14)
ldloca V_14
initobj valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1> ldnull
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14 box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldloc V_14
box valuetype MyStruct319`2<class BaseClass0,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass0,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass0> V_15)
ldloca V_15
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0> ldnull
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15 box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldloc V_15
box valuetype MyStruct319`2<class BaseClass1,class BaseClass0>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass0>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
.locals init (valuetype MyStruct319`2<class BaseClass1,class BaseClass1> V_16)
ldloca V_16
initobj valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.2557()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.2559()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.2561<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.2563<System.Object>()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod635()
calli default string(object)
ldstr "MyStruct319::ClassMethod635.2565()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ClassMethod636()
calli default string(object)
ldstr "MyStruct319::ClassMethod636.2566()"
ldstr "valuetype MyStruct319`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1> ldnull
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance bool valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance int32 valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16 box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string valuetype MyStruct319`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4()
calli default string(object)
ldstr "MyStruct319::Method4.MI.2558()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5()
calli default string(object)
ldstr "MyStruct319::Method5.MI.2560()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>()
calli default string(object)
ldstr "MyStruct319::Method6.MI.2562<System.Object>()"
ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct319`2<class BaseClass1,class BaseClass1>"
call void [TestFramework]TestFramework::MethodCallTest(string,string,string)
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldloc V_16
box valuetype MyStruct319`2<class BaseClass1,class BaseClass1>
ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>()
calli default string(object)
ldstr "MyStruct319::Method7.MI.2564<System.Object>()"
ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct319`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 Generated269::MethodCallingTest()
call void Generated269::ConstrainedCallsTest()
call void Generated269::StructConstrainedInterfaceCallsTest()
call void Generated269::CalliTest()
ldc.i4 100
ret
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/ReAllocHGlobalTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class ReAllocHGlobalTests
{
[Fact]
public void ReAllocHGlobal_Invoke_DataCopied()
{
const int Size = 3;
IntPtr p1 = Marshal.AllocHGlobal((IntPtr)Size);
IntPtr p2 = p1;
try
{
for (int i = 0; i < Size; i++)
{
Marshal.WriteByte(p1 + i, (byte)i);
}
int add = 1;
do
{
p2 = Marshal.ReAllocHGlobal(p2, (IntPtr)(Size + add));
for (int i = 0; i < Size; i++)
{
Assert.Equal((byte)i, Marshal.ReadByte(p2 + i));
}
add++;
}
while (p2 == p1); // stop once we've validated moved case
}
finally
{
Marshal.FreeHGlobal(p2);
}
}
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[Theory]
public void ReAllocHGlobal_PositiveSize(int size)
{
IntPtr p = Marshal.ReAllocHGlobal(IntPtr.Zero, (IntPtr)size);
Assert.NotEqual(IntPtr.Zero, p);
IntPtr p1 = Marshal.ReAllocHGlobal(p, (IntPtr)(size + 1));
Assert.NotEqual(IntPtr.Zero, p1);
// ReAllocHGlobal never returns null, even for 0 size (different from standard C/C++ realloc)
IntPtr p2 = Marshal.ReAllocHGlobal(p1, IntPtr.Zero);
Assert.NotEqual(IntPtr.Zero, p2);
Marshal.FreeHGlobal(p2);
}
[Fact]
public void ReAllocHGlobal_NegativeSize_ThrowsOutOfMemoryException()
{
Assert.Throws<OutOfMemoryException>(() => Marshal.ReAllocHGlobal(IntPtr.Zero, (IntPtr)(-1)));
IntPtr p = Marshal.AllocHGlobal((IntPtr)1);
Assert.Throws<OutOfMemoryException>(() => Marshal.ReAllocHGlobal(p, (IntPtr)(-1)));
Marshal.FreeHGlobal(p);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class ReAllocHGlobalTests
{
[Fact]
public void ReAllocHGlobal_Invoke_DataCopied()
{
const int Size = 3;
IntPtr p1 = Marshal.AllocHGlobal((IntPtr)Size);
IntPtr p2 = p1;
try
{
for (int i = 0; i < Size; i++)
{
Marshal.WriteByte(p1 + i, (byte)i);
}
int add = 1;
do
{
p2 = Marshal.ReAllocHGlobal(p2, (IntPtr)(Size + add));
for (int i = 0; i < Size; i++)
{
Assert.Equal((byte)i, Marshal.ReadByte(p2 + i));
}
add++;
}
while (p2 == p1); // stop once we've validated moved case
}
finally
{
Marshal.FreeHGlobal(p2);
}
}
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
[Theory]
public void ReAllocHGlobal_PositiveSize(int size)
{
IntPtr p = Marshal.ReAllocHGlobal(IntPtr.Zero, (IntPtr)size);
Assert.NotEqual(IntPtr.Zero, p);
IntPtr p1 = Marshal.ReAllocHGlobal(p, (IntPtr)(size + 1));
Assert.NotEqual(IntPtr.Zero, p1);
// ReAllocHGlobal never returns null, even for 0 size (different from standard C/C++ realloc)
IntPtr p2 = Marshal.ReAllocHGlobal(p1, IntPtr.Zero);
Assert.NotEqual(IntPtr.Zero, p2);
Marshal.FreeHGlobal(p2);
}
[Fact]
public void ReAllocHGlobal_NegativeSize_ThrowsOutOfMemoryException()
{
Assert.Throws<OutOfMemoryException>(() => Marshal.ReAllocHGlobal(IntPtr.Zero, (IntPtr)(-1)));
IntPtr p = Marshal.AllocHGlobal((IntPtr)1);
Assert.Throws<OutOfMemoryException>(() => Marshal.ReAllocHGlobal(p, (IntPtr)(-1)));
Marshal.FreeHGlobal(p);
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/Loader/classloader/generics/Instantiation/Negative/param04.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 System.Console { }
.assembly extern xunit.core {}
// DESCRIPTION:
// This tests that a TypeLoadException is thrown when an instance method
// of a generic class with one formal type parameter is invoked via the call
// instruction with two actual type parameters.
// This call is in the method GenTest<T>.InternalTest().
// Microsoft (R) .NET Framework IL Disassembler. Version 1.1.2019.0
// Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
// Metadata version: v1.1.2019
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.hash = (73 26 79 1F 31 96 69 CE 57 B9 48 24 EE A8 34 F1 // s&y.1.i.W.H$..4.
42 87 88 29 ) // B..)
.ver 1:1:3300:0
}
.assembly 'param04'
{
// --- The following custom attribute is added automatically, do not uncomment -------
// .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool,
// bool) = ( 01 00 00 01 00 00 )
.hash algorithm 0x00008004
.ver 0:0:0:0
}
// MVID: {B86C7C7A-5711-4AC7-8792-3E7302C1FCD0}
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 512
.corflags 0x00000001
// Image base: 0x034B0000
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi beforefieldinit Gen<([mscorlib]System.Object) T>
extends [mscorlib]System.Object
{
.method public hidebysig instance void
Dummy() cil managed
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
} // end of method Gen::Dummy
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Gen::.ctor
} // end of class Gen
.class public auto ansi beforefieldinit GenTest<([mscorlib]System.Object) T>
extends [mscorlib]System.Object
{
.method private hidebysig instance void
InternalTest() cil managed
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj instance void class Gen<!0>::.ctor()
IL_0005: call instance void class Gen<!0,!0>::Dummy()
IL_000a: ret
} // end of method GenTest::InternalTest
.method private hidebysig instance void
IndirectTest() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void class GenTest<!0>::InternalTest()
IL_0006: ret
} // end of method GenTest::IndirectTest
.method public hidebysig instance bool
Test_param04() cil managed
{
// Code size 48 (0x30)
.maxstack 2
.locals init (class [mscorlib]System.Exception V_0,
bool V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call instance void class GenTest<!0>::IndirectTest()
IL_0006: ldstr "Test did not throw expected TypeLoadException"
IL_000b: call void [System.Console]System.Console::WriteLine(string)
IL_0010: ldc.i4.0
IL_0011: stloc.1
IL_0012: leave.s IL_002e
} // end .try
catch [mscorlib]System.TypeLoadException
{
IL_0014: pop
IL_0015: ldc.i4.1
IL_0016: stloc.1
IL_0017: leave.s IL_002e
} // end handler
catch [mscorlib]System.Exception
{
IL_0019: stloc.0
IL_001a: ldstr "Test caught unexpected Exception "
IL_001f: ldloc.0
IL_0020: call string [mscorlib]System.String::Concat(object,
object)
IL_0025: call void [System.Console]System.Console::WriteLine(string)
IL_002a: ldc.i4.0
IL_002b: stloc.1
IL_002c: leave.s IL_002e
} // end handler
IL_002e: ldloc.1
IL_002f: ret
} // end of method GenTest::Test
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method GenTest::.ctor
} // end of class GenTest
.class public auto ansi beforefieldinit Test_param04
extends [mscorlib]System.Object
{
.field public static int32 counter
.field public static bool result
.method public hidebysig static void Eval(bool exp) cil managed
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldsfld int32 Test_param04::counter
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: stsfld int32 Test_param04::counter
IL_000c: ldarg.0
IL_000d: brtrue.s IL_002e
IL_000f: ldarg.0
IL_0010: stsfld bool Test_param04::result
IL_0015: ldstr "Test Failed at location: "
IL_001a: ldsfld int32 Test_param04::counter
IL_001f: box [mscorlib]System.Int32
IL_0024: call string [mscorlib]System.String::Concat(object,
object)
IL_0029: call void [System.Console]System.Console::WriteLine(string)
IL_002e: ret
} // end of method Test::Eval
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
// Code size 113 (0x71)
.maxstack 1
.locals init (int32 V_0)
IL_0000: newobj instance void class GenTest<int32>::.ctor()
IL_0005: call instance bool class GenTest<int32>::Test_param04()
IL_000a: call void Test_param04::Eval(bool)
IL_000f: newobj instance void class GenTest<float64>::.ctor()
IL_0014: call instance bool class GenTest<float64>::Test_param04()
IL_0019: call void Test_param04::Eval(bool)
IL_001e: newobj instance void class GenTest<valuetype [mscorlib]System.Guid>::.ctor()
IL_0023: call instance bool class GenTest<valuetype [mscorlib]System.Guid>::Test_param04()
IL_0028: call void Test_param04::Eval(bool)
IL_002d: newobj instance void class GenTest<string>::.ctor()
IL_0032: call instance bool class GenTest<string>::Test_param04()
IL_0037: call void Test_param04::Eval(bool)
IL_003c: newobj instance void class GenTest<object>::.ctor()
IL_0041: call instance bool class GenTest<object>::Test_param04()
IL_0046: call void Test_param04::Eval(bool)
IL_004b: ldsfld bool Test_param04::result
IL_0050: brfalse.s IL_0061
IL_0052: ldstr "Test Passed"
IL_0057: call void [System.Console]System.Console::WriteLine(string)
IL_005c: ldc.i4.s 100
IL_005e: stloc.0
IL_005f: br.s IL_006f
IL_0061: ldstr "Test Failed"
IL_0066: call void [System.Console]System.Console::WriteLine(string)
IL_006b: ldc.i4.1
IL_006c: stloc.0
IL_006d: br.s IL_006f
IL_006f: ldloc.0
IL_0070: ret
} // end of method Test::Main
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: stsfld int32 Test_param04::counter
IL_0006: ldc.i4.1
IL_0007: stsfld bool Test_param04::result
IL_000c: ret
} // end of method Test::.cctor
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Test::.ctor
} // end of class Test
// =============================================================
//*********** DISASSEMBLY COMPLETE ***********************
// WARNING: Created Win32 resource file param03.res
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern System.Console { }
.assembly extern xunit.core {}
// DESCRIPTION:
// This tests that a TypeLoadException is thrown when an instance method
// of a generic class with one formal type parameter is invoked via the call
// instruction with two actual type parameters.
// This call is in the method GenTest<T>.InternalTest().
// Microsoft (R) .NET Framework IL Disassembler. Version 1.1.2019.0
// Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
// Metadata version: v1.1.2019
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.hash = (73 26 79 1F 31 96 69 CE 57 B9 48 24 EE A8 34 F1 // s&y.1.i.W.H$..4.
42 87 88 29 ) // B..)
.ver 1:1:3300:0
}
.assembly 'param04'
{
// --- The following custom attribute is added automatically, do not uncomment -------
// .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(bool,
// bool) = ( 01 00 00 01 00 00 )
.hash algorithm 0x00008004
.ver 0:0:0:0
}
// MVID: {B86C7C7A-5711-4AC7-8792-3E7302C1FCD0}
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 512
.corflags 0x00000001
// Image base: 0x034B0000
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi beforefieldinit Gen<([mscorlib]System.Object) T>
extends [mscorlib]System.Object
{
.method public hidebysig instance void
Dummy() cil managed
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
} // end of method Gen::Dummy
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Gen::.ctor
} // end of class Gen
.class public auto ansi beforefieldinit GenTest<([mscorlib]System.Object) T>
extends [mscorlib]System.Object
{
.method private hidebysig instance void
InternalTest() cil managed
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: newobj instance void class Gen<!0>::.ctor()
IL_0005: call instance void class Gen<!0,!0>::Dummy()
IL_000a: ret
} // end of method GenTest::InternalTest
.method private hidebysig instance void
IndirectTest() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void class GenTest<!0>::InternalTest()
IL_0006: ret
} // end of method GenTest::IndirectTest
.method public hidebysig instance bool
Test_param04() cil managed
{
// Code size 48 (0x30)
.maxstack 2
.locals init (class [mscorlib]System.Exception V_0,
bool V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call instance void class GenTest<!0>::IndirectTest()
IL_0006: ldstr "Test did not throw expected TypeLoadException"
IL_000b: call void [System.Console]System.Console::WriteLine(string)
IL_0010: ldc.i4.0
IL_0011: stloc.1
IL_0012: leave.s IL_002e
} // end .try
catch [mscorlib]System.TypeLoadException
{
IL_0014: pop
IL_0015: ldc.i4.1
IL_0016: stloc.1
IL_0017: leave.s IL_002e
} // end handler
catch [mscorlib]System.Exception
{
IL_0019: stloc.0
IL_001a: ldstr "Test caught unexpected Exception "
IL_001f: ldloc.0
IL_0020: call string [mscorlib]System.String::Concat(object,
object)
IL_0025: call void [System.Console]System.Console::WriteLine(string)
IL_002a: ldc.i4.0
IL_002b: stloc.1
IL_002c: leave.s IL_002e
} // end handler
IL_002e: ldloc.1
IL_002f: ret
} // end of method GenTest::Test
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method GenTest::.ctor
} // end of class GenTest
.class public auto ansi beforefieldinit Test_param04
extends [mscorlib]System.Object
{
.field public static int32 counter
.field public static bool result
.method public hidebysig static void Eval(bool exp) cil managed
{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldsfld int32 Test_param04::counter
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: stsfld int32 Test_param04::counter
IL_000c: ldarg.0
IL_000d: brtrue.s IL_002e
IL_000f: ldarg.0
IL_0010: stsfld bool Test_param04::result
IL_0015: ldstr "Test Failed at location: "
IL_001a: ldsfld int32 Test_param04::counter
IL_001f: box [mscorlib]System.Int32
IL_0024: call string [mscorlib]System.String::Concat(object,
object)
IL_0029: call void [System.Console]System.Console::WriteLine(string)
IL_002e: ret
} // end of method Test::Eval
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
// Code size 113 (0x71)
.maxstack 1
.locals init (int32 V_0)
IL_0000: newobj instance void class GenTest<int32>::.ctor()
IL_0005: call instance bool class GenTest<int32>::Test_param04()
IL_000a: call void Test_param04::Eval(bool)
IL_000f: newobj instance void class GenTest<float64>::.ctor()
IL_0014: call instance bool class GenTest<float64>::Test_param04()
IL_0019: call void Test_param04::Eval(bool)
IL_001e: newobj instance void class GenTest<valuetype [mscorlib]System.Guid>::.ctor()
IL_0023: call instance bool class GenTest<valuetype [mscorlib]System.Guid>::Test_param04()
IL_0028: call void Test_param04::Eval(bool)
IL_002d: newobj instance void class GenTest<string>::.ctor()
IL_0032: call instance bool class GenTest<string>::Test_param04()
IL_0037: call void Test_param04::Eval(bool)
IL_003c: newobj instance void class GenTest<object>::.ctor()
IL_0041: call instance bool class GenTest<object>::Test_param04()
IL_0046: call void Test_param04::Eval(bool)
IL_004b: ldsfld bool Test_param04::result
IL_0050: brfalse.s IL_0061
IL_0052: ldstr "Test Passed"
IL_0057: call void [System.Console]System.Console::WriteLine(string)
IL_005c: ldc.i4.s 100
IL_005e: stloc.0
IL_005f: br.s IL_006f
IL_0061: ldstr "Test Failed"
IL_0066: call void [System.Console]System.Console::WriteLine(string)
IL_006b: ldc.i4.1
IL_006c: stloc.0
IL_006d: br.s IL_006f
IL_006f: ldloc.0
IL_0070: ret
} // end of method Test::Main
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: stsfld int32 Test_param04::counter
IL_0006: ldc.i4.1
IL_0007: stsfld bool Test_param04::result
IL_000c: ret
} // end of method Test::.cctor
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Test::.ctor
} // end of class Test
// =============================================================
//*********** DISASSEMBLY COMPLETE ***********************
// WARNING: Created Win32 resource file param03.res
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.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.Buffers;
using System.Diagnostics;
using System.Formats.Asn1;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
internal static partial class RSAImplementation
{
public sealed partial class RSASecurityTransforms : RSA
{
private SecKeyPair? _keys;
public RSASecurityTransforms()
: this(2048)
{
}
public RSASecurityTransforms(int keySize)
{
base.KeySize = keySize;
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
return new KeySizes[]
{
// All values are in bits.
// 1024 was achieved via experimentation.
// 1024 and 1024+8 both generated successfully, 1024-8 produced errSecParam.
new KeySizes(minSize: 1024, maxSize: 16384, skipSize: 8),
};
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
ThrowIfDisposed();
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
SecKeyPair keys = GetKeys();
if (includePrivateParameters && keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
bool gotKeyBlob = Interop.AppleCrypto.TrySecKeyCopyExternalRepresentation(
includePrivateParameters ? keys.PrivateKey! : keys.PublicKey,
out byte[] keyBlob);
if (!gotKeyBlob)
{
return ExportParametersFromLegacyKey(keys, includePrivateParameters);
}
try
{
if (!includePrivateParameters)
{
// When exporting a key handle opened from a certificate, it seems to
// export as a PKCS#1 blob instead of an X509 SubjectPublicKeyInfo blob.
// So, check for that.
// NOTE: It doesn't affect macOS Mojave when SecCertificateCopyKey API
// is used.
RSAParameters key;
AsnReader reader = new AsnReader(keyBlob, AsnEncodingRules.BER);
AsnReader sequenceReader = reader.ReadSequence();
if (sequenceReader.PeekTag().Equals(Asn1Tag.Integer))
{
AlgorithmIdentifierAsn ignored = default;
RSAKeyFormatHelper.ReadRsaPublicKey(keyBlob, ignored, out key);
}
else
{
RSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
keyBlob,
out int localRead,
out key);
Debug.Assert(localRead == keyBlob.Length);
}
return key;
}
else
{
AlgorithmIdentifierAsn ignored = default;
RSAKeyFormatHelper.FromPkcs1PrivateKey(
keyBlob,
ignored,
out RSAParameters key);
return key;
}
}
finally
{
CryptographicOperations.ZeroMemory(keyBlob);
}
}
public override void ImportParameters(RSAParameters parameters)
{
ValidateParameters(parameters);
ThrowIfDisposed();
bool isPrivateKey = parameters.D != null;
if (isPrivateKey)
{
// Start with the private key, in case some of the private key fields
// don't match the public key fields.
//
// Public import should go off without a hitch.
ImportPrivateKey(
parameters,
out SafeSecKeyRefHandle privateKey,
out SafeSecKeyRefHandle publicKey);
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
public override unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead)
{
ThrowIfDisposed();
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
// Validate the DER value and get the number of bytes.
RSAKeyFormatHelper.ReadRsaPublicKey(
manager.Memory,
out int localRead);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.CreateDataKey(
source.Slice(0, localRead),
Interop.AppleCrypto.PAL_KeyAlgorithm.RSA,
isPublic: true);
SetKey(SecKeyPair.PublicOnly(publicKey));
bytesRead = localRead;
}
}
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!)
{
ThrowIfDisposed();
// The size of encrypt is always the keysize (in ceiling-bytes)
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TryEncrypt(data, output, padding, out int bytesWritten))
{
Debug.Fail($"TryEncrypt with a preallocated buffer should not fail");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
{
ThrowIfDisposed();
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
if (data.Length == 0)
{
RsaPaddingProcessor? processor;
switch (padding.Mode)
{
case RSAEncryptionPaddingMode.Pkcs1:
processor = null;
break;
case RSAEncryptionPaddingMode.Oaep:
processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm);
break;
default:
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> tmp = new Span<byte>(rented, 0, rsaSize);
try
{
if (processor != null)
{
processor.PadOaep(data, tmp);
}
else
{
Debug.Assert(padding.Mode == RSAEncryptionPaddingMode.Pkcs1);
RsaPaddingProcessor.PadPkcs1Encryption(data, tmp);
}
return Interop.AppleCrypto.TryRsaEncryptionPrimitive(
GetKeys().PublicKey,
tmp,
destination,
out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(tmp);
CryptoPool.Return(rented, clearSize: 0);
}
}
return Interop.AppleCrypto.TryRsaEncrypt(
GetKeys().PublicKey,
data,
destination,
padding,
out bytesWritten);
}
public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding);
}
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return TryDecrypt(keys.PrivateKey, data, destination, padding, out bytesWritten);
}
private bool TryDecrypt(
SafeSecKeyRefHandle privateKey,
ReadOnlySpan<byte> data,
Span<byte> destination,
RSAEncryptionPadding padding,
out int bytesWritten)
{
Debug.Assert(privateKey != null);
if (padding.Mode != RSAEncryptionPaddingMode.Pkcs1 &&
padding.Mode != RSAEncryptionPaddingMode.Oaep)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
return Interop.AppleCrypto.TryRsaDecrypt(privateKey, data, destination, padding, out bytesWritten);
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int expectedSize;
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
return Interop.AppleCrypto.CreateSignature(
keys.PrivateKey,
hash,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1);
}
// A signature will always be the keysize (in ceiling-bytes) in length.
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TrySignHash(hash, output, hashAlgorithm, padding, out int bytesWritten))
{
Debug.Fail("TrySignHash failed with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
RsaPaddingProcessor? processor = null;
if (padding.Mode == RSASignaturePaddingMode.Pss)
{
processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
}
else if (padding != RSASignaturePadding.Pkcs1)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (processor == null)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
return Interop.AppleCrypto.TryCreateSignature(
keys.PrivateKey,
hash,
destination,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1,
out bytesWritten);
}
Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> buf = new Span<byte>(rented, 0, rsaSize);
processor.EncodePss(hash, buf, keySize);
try
{
return Interop.AppleCrypto.TryRsaSignaturePrimitive(keys.PrivateKey, buf, destination, out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(buf);
CryptoPool.Return(rented, clearSize: 0);
}
}
public override bool VerifyHash(
byte[] hash!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out _);
return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
signature,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1);
}
else if (padding.Mode == RSASignaturePaddingMode.Pss)
{
RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
SafeSecKeyRefHandle publicKey = GetKeys().PublicKey;
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (signature.Length != rsaSize)
{
return false;
}
if (hash.Length != processor.HashLength)
{
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> unwrapped = new Span<byte>(rented, 0, rsaSize);
try
{
if (!Interop.AppleCrypto.TryRsaVerificationPrimitive(
publicKey,
signature,
unwrapped,
out int bytesWritten))
{
Debug.Fail($"TryRsaVerificationPrimitive with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == rsaSize);
return processor.VerifyPss(hash, unwrapped, keySize);
}
finally
{
CryptographicOperations.ZeroMemory(unwrapped);
CryptoPool.Return(rented, clearSize: 0);
}
}
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
HashOneShotHelpers.HashData(hashAlgorithm, new ReadOnlySpan<byte>(data, offset, count));
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
HashOneShotHelpers.HashData(hashAlgorithm, data);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
HashOneShotHelpers.TryHashData(hashAlgorithm, data, destination, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
// Do not set _keys to null, in order to prevent rehydration.
_keys.Dispose();
}
}
base.Dispose(disposing);
}
private static Interop.AppleCrypto.PAL_HashAlgorithm PalAlgorithmFromAlgorithmName(
HashAlgorithmName hashAlgorithmName,
out int hashSizeInBytes)
{
if (hashAlgorithmName == HashAlgorithmName.MD5)
{
hashSizeInBytes = MD5.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Md5;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
hashSizeInBytes = SHA1.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha1;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
hashSizeInBytes = SHA256.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha256;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
hashSizeInBytes = SHA384.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha384;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
hashSizeInBytes = SHA512.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha512;
}
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name);
}
private void ThrowIfDisposed()
{
SecKeyPair? current = _keys;
if (current != null && current.PublicKey == null)
{
throw new ObjectDisposedException(nameof(RSA));
}
}
internal SecKeyPair GetKeys()
{
ThrowIfDisposed();
SecKeyPair? current = _keys;
if (current != null)
{
return current;
}
SafeSecKeyRefHandle publicKey;
SafeSecKeyRefHandle privateKey;
Interop.AppleCrypto.RsaGenerateKey(KeySizeValue, out publicKey, out privateKey);
current = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
_keys = current;
return current;
}
private void SetKey(SecKeyPair newKeyPair)
{
ThrowIfDisposed();
SecKeyPair? current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
KeySizeValue = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey);
}
}
private static SafeSecKeyRefHandle ImportKey(RSAParameters parameters)
{
AsnWriter keyWriter;
bool hasPrivateKey;
if (parameters.D != null)
{
keyWriter = RSAKeyFormatHelper.WritePkcs1PrivateKey(parameters);
hasPrivateKey = true;
}
else
{
keyWriter = RSAKeyFormatHelper.WritePkcs1PublicKey(parameters);
hasPrivateKey = false;
}
byte[] rented = CryptoPool.Rent(keyWriter.GetEncodedLength());
if (!keyWriter.TryEncode(rented, out int written))
{
Debug.Fail("TryEncode failed with a pre-allocated buffer");
throw new InvalidOperationException();
}
// Explicitly clear the inner buffer
keyWriter.Reset();
try
{
return Interop.AppleCrypto.CreateDataKey(
rented.AsSpan(0, written),
Interop.AppleCrypto.PAL_KeyAlgorithm.RSA,
isPublic: !hasPrivateKey);
}
finally
{
CryptoPool.Return(rented, written);
}
}
private static void ValidateParameters(in RSAParameters parameters)
{
if (parameters.Modulus == null || parameters.Exponent == null)
throw new CryptographicException(SR.Argument_InvalidValue);
if (!HasConsistentPrivateKey(parameters))
throw new CryptographicException(SR.Argument_InvalidValue);
}
private static bool HasConsistentPrivateKey(in RSAParameters parameters)
{
if (parameters.D == null)
{
if (parameters.P != null ||
parameters.DP != null ||
parameters.Q != null ||
parameters.DQ != null ||
parameters.InverseQ != null)
{
return false;
}
}
else
{
if (parameters.P == null ||
parameters.DP == null ||
parameters.Q == null ||
parameters.DQ == null ||
parameters.InverseQ == null)
{
return false;
}
}
return true;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Formats.Asn1;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
internal static partial class RSAImplementation
{
public sealed partial class RSASecurityTransforms : RSA
{
private SecKeyPair? _keys;
public RSASecurityTransforms()
: this(2048)
{
}
public RSASecurityTransforms(int keySize)
{
base.KeySize = keySize;
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
return new KeySizes[]
{
// All values are in bits.
// 1024 was achieved via experimentation.
// 1024 and 1024+8 both generated successfully, 1024-8 produced errSecParam.
new KeySizes(minSize: 1024, maxSize: 16384, skipSize: 8),
};
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
ThrowIfDisposed();
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
SecKeyPair keys = GetKeys();
if (includePrivateParameters && keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
bool gotKeyBlob = Interop.AppleCrypto.TrySecKeyCopyExternalRepresentation(
includePrivateParameters ? keys.PrivateKey! : keys.PublicKey,
out byte[] keyBlob);
if (!gotKeyBlob)
{
return ExportParametersFromLegacyKey(keys, includePrivateParameters);
}
try
{
if (!includePrivateParameters)
{
// When exporting a key handle opened from a certificate, it seems to
// export as a PKCS#1 blob instead of an X509 SubjectPublicKeyInfo blob.
// So, check for that.
// NOTE: It doesn't affect macOS Mojave when SecCertificateCopyKey API
// is used.
RSAParameters key;
AsnReader reader = new AsnReader(keyBlob, AsnEncodingRules.BER);
AsnReader sequenceReader = reader.ReadSequence();
if (sequenceReader.PeekTag().Equals(Asn1Tag.Integer))
{
AlgorithmIdentifierAsn ignored = default;
RSAKeyFormatHelper.ReadRsaPublicKey(keyBlob, ignored, out key);
}
else
{
RSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
keyBlob,
out int localRead,
out key);
Debug.Assert(localRead == keyBlob.Length);
}
return key;
}
else
{
AlgorithmIdentifierAsn ignored = default;
RSAKeyFormatHelper.FromPkcs1PrivateKey(
keyBlob,
ignored,
out RSAParameters key);
return key;
}
}
finally
{
CryptographicOperations.ZeroMemory(keyBlob);
}
}
public override void ImportParameters(RSAParameters parameters)
{
ValidateParameters(parameters);
ThrowIfDisposed();
bool isPrivateKey = parameters.D != null;
if (isPrivateKey)
{
// Start with the private key, in case some of the private key fields
// don't match the public key fields.
//
// Public import should go off without a hitch.
ImportPrivateKey(
parameters,
out SafeSecKeyRefHandle privateKey,
out SafeSecKeyRefHandle publicKey);
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
public override unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead)
{
ThrowIfDisposed();
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
// Validate the DER value and get the number of bytes.
RSAKeyFormatHelper.ReadRsaPublicKey(
manager.Memory,
out int localRead);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.CreateDataKey(
source.Slice(0, localRead),
Interop.AppleCrypto.PAL_KeyAlgorithm.RSA,
isPublic: true);
SetKey(SecKeyPair.PublicOnly(publicKey));
bytesRead = localRead;
}
}
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!)
{
ThrowIfDisposed();
// The size of encrypt is always the keysize (in ceiling-bytes)
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TryEncrypt(data, output, padding, out int bytesWritten))
{
Debug.Fail($"TryEncrypt with a preallocated buffer should not fail");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
{
ThrowIfDisposed();
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
if (data.Length == 0)
{
RsaPaddingProcessor? processor;
switch (padding.Mode)
{
case RSAEncryptionPaddingMode.Pkcs1:
processor = null;
break;
case RSAEncryptionPaddingMode.Oaep:
processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm);
break;
default:
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> tmp = new Span<byte>(rented, 0, rsaSize);
try
{
if (processor != null)
{
processor.PadOaep(data, tmp);
}
else
{
Debug.Assert(padding.Mode == RSAEncryptionPaddingMode.Pkcs1);
RsaPaddingProcessor.PadPkcs1Encryption(data, tmp);
}
return Interop.AppleCrypto.TryRsaEncryptionPrimitive(
GetKeys().PublicKey,
tmp,
destination,
out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(tmp);
CryptoPool.Return(rented, clearSize: 0);
}
}
return Interop.AppleCrypto.TryRsaEncrypt(
GetKeys().PublicKey,
data,
destination,
padding,
out bytesWritten);
}
public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding);
}
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return TryDecrypt(keys.PrivateKey, data, destination, padding, out bytesWritten);
}
private bool TryDecrypt(
SafeSecKeyRefHandle privateKey,
ReadOnlySpan<byte> data,
Span<byte> destination,
RSAEncryptionPadding padding,
out int bytesWritten)
{
Debug.Assert(privateKey != null);
if (padding.Mode != RSAEncryptionPaddingMode.Pkcs1 &&
padding.Mode != RSAEncryptionPaddingMode.Oaep)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
return Interop.AppleCrypto.TryRsaDecrypt(privateKey, data, destination, padding, out bytesWritten);
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int expectedSize;
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
return Interop.AppleCrypto.CreateSignature(
keys.PrivateKey,
hash,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1);
}
// A signature will always be the keysize (in ceiling-bytes) in length.
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TrySignHash(hash, output, hashAlgorithm, padding, out int bytesWritten))
{
Debug.Fail("TrySignHash failed with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
RsaPaddingProcessor? processor = null;
if (padding.Mode == RSASignaturePaddingMode.Pss)
{
processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
}
else if (padding != RSASignaturePadding.Pkcs1)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (processor == null)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
return Interop.AppleCrypto.TryCreateSignature(
keys.PrivateKey,
hash,
destination,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1,
out bytesWritten);
}
Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> buf = new Span<byte>(rented, 0, rsaSize);
processor.EncodePss(hash, buf, keySize);
try
{
return Interop.AppleCrypto.TryRsaSignaturePrimitive(keys.PrivateKey, buf, destination, out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(buf);
CryptoPool.Return(rented, clearSize: 0);
}
}
public override bool VerifyHash(
byte[] hash!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out _);
return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
signature,
palAlgId,
Interop.AppleCrypto.PAL_SignatureAlgorithm.RsaPkcs1);
}
else if (padding.Mode == RSASignaturePaddingMode.Pss)
{
RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
SafeSecKeyRefHandle publicKey = GetKeys().PublicKey;
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (signature.Length != rsaSize)
{
return false;
}
if (hash.Length != processor.HashLength)
{
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> unwrapped = new Span<byte>(rented, 0, rsaSize);
try
{
if (!Interop.AppleCrypto.TryRsaVerificationPrimitive(
publicKey,
signature,
unwrapped,
out int bytesWritten))
{
Debug.Fail($"TryRsaVerificationPrimitive with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == rsaSize);
return processor.VerifyPss(hash, unwrapped, keySize);
}
finally
{
CryptographicOperations.ZeroMemory(unwrapped);
CryptoPool.Return(rented, clearSize: 0);
}
}
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
HashOneShotHelpers.HashData(hashAlgorithm, new ReadOnlySpan<byte>(data, offset, count));
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
HashOneShotHelpers.HashData(hashAlgorithm, data);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
HashOneShotHelpers.TryHashData(hashAlgorithm, data, destination, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
// Do not set _keys to null, in order to prevent rehydration.
_keys.Dispose();
}
}
base.Dispose(disposing);
}
private static Interop.AppleCrypto.PAL_HashAlgorithm PalAlgorithmFromAlgorithmName(
HashAlgorithmName hashAlgorithmName,
out int hashSizeInBytes)
{
if (hashAlgorithmName == HashAlgorithmName.MD5)
{
hashSizeInBytes = MD5.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Md5;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
hashSizeInBytes = SHA1.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha1;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
hashSizeInBytes = SHA256.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha256;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
hashSizeInBytes = SHA384.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha384;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
hashSizeInBytes = SHA512.HashSizeInBytes;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha512;
}
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name);
}
private void ThrowIfDisposed()
{
SecKeyPair? current = _keys;
if (current != null && current.PublicKey == null)
{
throw new ObjectDisposedException(nameof(RSA));
}
}
internal SecKeyPair GetKeys()
{
ThrowIfDisposed();
SecKeyPair? current = _keys;
if (current != null)
{
return current;
}
SafeSecKeyRefHandle publicKey;
SafeSecKeyRefHandle privateKey;
Interop.AppleCrypto.RsaGenerateKey(KeySizeValue, out publicKey, out privateKey);
current = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
_keys = current;
return current;
}
private void SetKey(SecKeyPair newKeyPair)
{
ThrowIfDisposed();
SecKeyPair? current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
KeySizeValue = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey);
}
}
private static SafeSecKeyRefHandle ImportKey(RSAParameters parameters)
{
AsnWriter keyWriter;
bool hasPrivateKey;
if (parameters.D != null)
{
keyWriter = RSAKeyFormatHelper.WritePkcs1PrivateKey(parameters);
hasPrivateKey = true;
}
else
{
keyWriter = RSAKeyFormatHelper.WritePkcs1PublicKey(parameters);
hasPrivateKey = false;
}
byte[] rented = CryptoPool.Rent(keyWriter.GetEncodedLength());
if (!keyWriter.TryEncode(rented, out int written))
{
Debug.Fail("TryEncode failed with a pre-allocated buffer");
throw new InvalidOperationException();
}
// Explicitly clear the inner buffer
keyWriter.Reset();
try
{
return Interop.AppleCrypto.CreateDataKey(
rented.AsSpan(0, written),
Interop.AppleCrypto.PAL_KeyAlgorithm.RSA,
isPublic: !hasPrivateKey);
}
finally
{
CryptoPool.Return(rented, written);
}
}
private static void ValidateParameters(in RSAParameters parameters)
{
if (parameters.Modulus == null || parameters.Exponent == null)
throw new CryptographicException(SR.Argument_InvalidValue);
if (!HasConsistentPrivateKey(parameters))
throw new CryptographicException(SR.Argument_InvalidValue);
}
private static bool HasConsistentPrivateKey(in RSAParameters parameters)
{
if (parameters.D == null)
{
if (parameters.P != null ||
parameters.DP != null ||
parameters.Q != null ||
parameters.DQ != null ||
parameters.InverseQ != null)
{
return false;
}
}
else
{
if (parameters.P == null ||
parameters.DP == null ||
parameters.Q == null ||
parameters.DQ == null ||
parameters.InverseQ == null)
{
return false;
}
}
return true;
}
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Security.Permissions/src/System/Security/Permissions/SiteIdentityPermissionAttribute.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.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage((AttributeTargets)(109), AllowMultiple = true, Inherited = false)]
public sealed partial class SiteIdentityPermissionAttribute : CodeAccessSecurityAttribute
{
public SiteIdentityPermissionAttribute(SecurityAction action) : base(default(SecurityAction)) { }
public string Site { get; set; }
public override IPermission CreatePermission() { return default(IPermission); }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage((AttributeTargets)(109), AllowMultiple = true, Inherited = false)]
public sealed partial class SiteIdentityPermissionAttribute : CodeAccessSecurityAttribute
{
public SiteIdentityPermissionAttribute(SecurityAction action) : base(default(SecurityAction)) { }
public string Site { get; set; }
public override IPermission CreatePermission() { return default(IPermission); }
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigEnvelopedSignatureTransformTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// XmlDsigEnvelopedSignatureTransformTest.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// (C) 2004 Novell Inc.
using System.IO;
using System.Xml;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
// Note: GetInnerXml is protected in XmlDsigEnvelopedSignatureTransform making it
// difficult to test properly. This class "open it up" :-)
public class UnprotectedXmlDsigEnvelopedSignatureTransform : XmlDsigEnvelopedSignatureTransform
{
public UnprotectedXmlDsigEnvelopedSignatureTransform()
{
}
public UnprotectedXmlDsigEnvelopedSignatureTransform(bool includeComments)
: base(includeComments)
{
}
public XmlNodeList UnprotectedGetInnerXml()
{
return base.GetInnerXml();
}
}
public class XmlDsigEnvelopedSignatureTransformTest
{
private UnprotectedXmlDsigEnvelopedSignatureTransform transform;
public XmlDsigEnvelopedSignatureTransformTest()
{
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform();
}
[Fact] // ctor ()
public void Constructor1()
{
CheckProperties(transform);
}
[Fact] // ctor (Boolean)
public void Constructor2()
{
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform(true);
CheckProperties(transform);
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform(false);
CheckProperties(transform);
}
void CheckProperties(XmlDsigEnvelopedSignatureTransform transform)
{
Assert.Equal("http://www.w3.org/2000/09/xmldsig#enveloped-signature",
transform.Algorithm);
Type[] input = transform.InputTypes;
Assert.Equal(3, input.Length);
// check presence of every supported input types
bool istream = false;
bool ixmldoc = false;
bool ixmlnl = false;
foreach (Type t in input)
{
if (t == typeof(XmlDocument))
ixmldoc = true;
if (t == typeof(XmlNodeList))
ixmlnl = true;
if (t == typeof(Stream))
istream = true;
}
Assert.True(istream, "Input Stream");
Assert.True(ixmldoc, "Input XmlDocument");
Assert.True(ixmlnl, "Input XmlNodeList");
Type[] output = transform.OutputTypes;
Assert.Equal(2, output.Length);
// check presence of every supported output types
bool oxmlnl = false;
bool oxmldoc = false;
foreach (Type t in output)
{
if (t == typeof(XmlNodeList))
oxmlnl = true;
if (t == typeof(XmlDocument))
oxmldoc = true;
}
Assert.True(oxmlnl, "Output XmlNodeList");
Assert.True(oxmldoc, "Output XmlDocument");
}
void AssertEquals(XmlNodeList expected, XmlNodeList actual, string msg)
{
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i].OuterXml, actual[i].OuterXml);
}
}
[Fact]
public void GetInnerXml()
{
// Always returns null
Assert.Null(transform.UnprotectedGetInnerXml());
}
private XmlDocument GetDoc()
{
string dsig = "<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\" /><SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#dsa-sha1\" /><Reference URI=\"\"><Transforms><Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" /></Transforms><DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" /><DigestValue>fdy6S2NLpnT4fMdokUHSHsmpcvo=</DigestValue></Reference></Signature>";
string test = "<Envelope> " + dsig + " </Envelope>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(test);
return doc;
}
[Fact]
public void LoadInputAsXmlDocument()
{
XmlDocument doc = GetDoc();
transform.LoadInput(doc);
object o = transform.GetOutput();
Assert.Equal(doc, o);
}
[Fact]
public void LoadInputAsXmlNodeList()
{
XmlDocument doc = GetDoc();
transform.LoadInput(doc.ChildNodes);
XmlNodeList xnl = (XmlNodeList)transform.GetOutput();
AssertEquals(doc.ChildNodes, xnl, "EnvelopedSignature result");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// XmlDsigEnvelopedSignatureTransformTest.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// (C) 2004 Novell Inc.
using System.IO;
using System.Xml;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
// Note: GetInnerXml is protected in XmlDsigEnvelopedSignatureTransform making it
// difficult to test properly. This class "open it up" :-)
public class UnprotectedXmlDsigEnvelopedSignatureTransform : XmlDsigEnvelopedSignatureTransform
{
public UnprotectedXmlDsigEnvelopedSignatureTransform()
{
}
public UnprotectedXmlDsigEnvelopedSignatureTransform(bool includeComments)
: base(includeComments)
{
}
public XmlNodeList UnprotectedGetInnerXml()
{
return base.GetInnerXml();
}
}
public class XmlDsigEnvelopedSignatureTransformTest
{
private UnprotectedXmlDsigEnvelopedSignatureTransform transform;
public XmlDsigEnvelopedSignatureTransformTest()
{
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform();
}
[Fact] // ctor ()
public void Constructor1()
{
CheckProperties(transform);
}
[Fact] // ctor (Boolean)
public void Constructor2()
{
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform(true);
CheckProperties(transform);
transform = new UnprotectedXmlDsigEnvelopedSignatureTransform(false);
CheckProperties(transform);
}
void CheckProperties(XmlDsigEnvelopedSignatureTransform transform)
{
Assert.Equal("http://www.w3.org/2000/09/xmldsig#enveloped-signature",
transform.Algorithm);
Type[] input = transform.InputTypes;
Assert.Equal(3, input.Length);
// check presence of every supported input types
bool istream = false;
bool ixmldoc = false;
bool ixmlnl = false;
foreach (Type t in input)
{
if (t == typeof(XmlDocument))
ixmldoc = true;
if (t == typeof(XmlNodeList))
ixmlnl = true;
if (t == typeof(Stream))
istream = true;
}
Assert.True(istream, "Input Stream");
Assert.True(ixmldoc, "Input XmlDocument");
Assert.True(ixmlnl, "Input XmlNodeList");
Type[] output = transform.OutputTypes;
Assert.Equal(2, output.Length);
// check presence of every supported output types
bool oxmlnl = false;
bool oxmldoc = false;
foreach (Type t in output)
{
if (t == typeof(XmlNodeList))
oxmlnl = true;
if (t == typeof(XmlDocument))
oxmldoc = true;
}
Assert.True(oxmlnl, "Output XmlNodeList");
Assert.True(oxmldoc, "Output XmlDocument");
}
void AssertEquals(XmlNodeList expected, XmlNodeList actual, string msg)
{
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i].OuterXml, actual[i].OuterXml);
}
}
[Fact]
public void GetInnerXml()
{
// Always returns null
Assert.Null(transform.UnprotectedGetInnerXml());
}
private XmlDocument GetDoc()
{
string dsig = "<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\" /><SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#dsa-sha1\" /><Reference URI=\"\"><Transforms><Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" /></Transforms><DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" /><DigestValue>fdy6S2NLpnT4fMdokUHSHsmpcvo=</DigestValue></Reference></Signature>";
string test = "<Envelope> " + dsig + " </Envelope>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(test);
return doc;
}
[Fact]
public void LoadInputAsXmlDocument()
{
XmlDocument doc = GetDoc();
transform.LoadInput(doc);
object o = transform.GetOutput();
Assert.Equal(doc, o);
}
[Fact]
public void LoadInputAsXmlNodeList()
{
XmlDocument doc = GetDoc();
transform.LoadInput(doc.ChildNodes);
XmlNodeList xnl = (XmlNodeList)transform.GetOutput();
AssertEquals(doc.ChildNodes, xnl, "EnvelopedSignature result");
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/FreeHGlobalTests.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.Runtime.InteropServices.Tests
{
public class FreeHGlobalTests
{
[Fact]
public void FreeHGlobal_ValidPointer_Success()
{
IntPtr mem = Marshal.AllocHGlobal(10);
Marshal.FreeHGlobal(mem);
}
[Fact]
public void FreeHGlobal_Zero_Nop()
{
Marshal.FreeHGlobal(IntPtr.Zero);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void FreeHGlobal_Win32Atom_Nop()
{
// Windows Marshal has specific checks that do not free
// anything if the ptr is less than 64K.
Marshal.FreeHGlobal((IntPtr)1);
}
}
}
| // 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.Runtime.InteropServices.Tests
{
public class FreeHGlobalTests
{
[Fact]
public void FreeHGlobal_ValidPointer_Success()
{
IntPtr mem = Marshal.AllocHGlobal(10);
Marshal.FreeHGlobal(mem);
}
[Fact]
public void FreeHGlobal_Zero_Nop()
{
Marshal.FreeHGlobal(IntPtr.Zero);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void FreeHGlobal_Win32Atom_Nop()
{
// Windows Marshal has specific checks that do not free
// anything if the ptr is less than 64K.
Marshal.FreeHGlobal((IntPtr)1);
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/Performance/CodeQuality/Benchstones/BenchF/InProd/InProd.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 Benchstone.BenchF
{
public static class InProd
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 70;
#endif
private const int RowSize = 10 * Iterations;
private static int s_seed;
private static T[][] AllocArray<T>(int n1, int n2)
{
T[][] a = new T[n1][];
for (int i = 0; i < n1; ++i)
{
a[i] = new T[n2];
}
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Bench()
{
double[][] rma = AllocArray<double>(RowSize, RowSize);
double[][] rmb = AllocArray<double>(RowSize, RowSize);
double[][] rmr = AllocArray<double>(RowSize, RowSize);
double sum;
Inner(rma, rmb, rmr);
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
sum = 0;
for (int k = 1; k < RowSize; k++)
{
sum = sum + rma[i][k] * rmb[k][j];
}
if (rmr[i][j] != sum)
{
return false;
}
}
}
return true;
}
private static void InitRand()
{
s_seed = 7774755;
}
private static int Rand()
{
s_seed = (s_seed * 77 + 13218009) % 3687091;
return s_seed;
}
private static void InitMatrix(double[][] m)
{
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
m[i][j] = (Rand() % 120 - 60) / 3;
}
}
}
private static void InnerProduct(out double result, double[][] a, double[][] b, int row, int col)
{
result = 0.0;
for (int i = 1; i < RowSize; i++)
{
result = result + a[row][i] * b[i][col];
}
}
private static void Inner(double[][] rma, double[][] rmb, double[][] rmr)
{
InitRand();
InitMatrix(rma);
InitMatrix(rmb);
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
InnerProduct(out rmr[i][j], rma, rmb, i, j);
}
}
}
public static int Main()
{
bool result = Bench();
return (result ? 100 : -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 Benchstone.BenchF
{
public static class InProd
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 70;
#endif
private const int RowSize = 10 * Iterations;
private static int s_seed;
private static T[][] AllocArray<T>(int n1, int n2)
{
T[][] a = new T[n1][];
for (int i = 0; i < n1; ++i)
{
a[i] = new T[n2];
}
return a;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool Bench()
{
double[][] rma = AllocArray<double>(RowSize, RowSize);
double[][] rmb = AllocArray<double>(RowSize, RowSize);
double[][] rmr = AllocArray<double>(RowSize, RowSize);
double sum;
Inner(rma, rmb, rmr);
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
sum = 0;
for (int k = 1; k < RowSize; k++)
{
sum = sum + rma[i][k] * rmb[k][j];
}
if (rmr[i][j] != sum)
{
return false;
}
}
}
return true;
}
private static void InitRand()
{
s_seed = 7774755;
}
private static int Rand()
{
s_seed = (s_seed * 77 + 13218009) % 3687091;
return s_seed;
}
private static void InitMatrix(double[][] m)
{
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
m[i][j] = (Rand() % 120 - 60) / 3;
}
}
}
private static void InnerProduct(out double result, double[][] a, double[][] b, int row, int col)
{
result = 0.0;
for (int i = 1; i < RowSize; i++)
{
result = result + a[row][i] * b[i][col];
}
}
private static void Inner(double[][] rma, double[][] rmb, double[][] rmr)
{
InitRand();
InitMatrix(rma);
InitMatrix(rmb);
for (int i = 1; i < RowSize; i++)
{
for (int j = 1; j < RowSize; j++)
{
InnerProduct(out rmr[i][j], rma, rmb, i, j);
}
}
}
public static int Main()
{
bool result = Bench();
return (result ? 100 : -1);
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Security.Permissions/src/System/Security/Permissions/FileIOPermissionAttribute.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.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class FileIOPermissionAttribute : CodeAccessSecurityAttribute
{
public FileIOPermissionAttribute(SecurityAction action) : base(action) { }
public string Read { get; set; }
public string Write { get; set; }
public string Append { get; set; }
public string PathDiscovery { get; set; }
public string ViewAccessControl { get; set; }
public string ChangeAccessControl { get; set; }
[Obsolete]
public string All { get; set; }
public string ViewAndModify { get; set; }
public FileIOPermissionAccess AllFiles { get; set; }
public FileIOPermissionAccess AllLocalFiles { get; set; }
public override IPermission CreatePermission() { return null; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Security.Permissions
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class FileIOPermissionAttribute : CodeAccessSecurityAttribute
{
public FileIOPermissionAttribute(SecurityAction action) : base(action) { }
public string Read { get; set; }
public string Write { get; set; }
public string Append { get; set; }
public string PathDiscovery { get; set; }
public string ViewAccessControl { get; set; }
public string ChangeAccessControl { get; set; }
[Obsolete]
public string All { get; set; }
public string ViewAndModify { get; set; }
public FileIOPermissionAccess AllFiles { get; set; }
public FileIOPermissionAccess AllLocalFiles { get; set; }
public override IPermission CreatePermission() { return null; }
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/Methodical/cctor/xassem/xprecise4_cs_do.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
<RequiresProcessIsolation>true</RequiresProcessIsolation>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="xprecise4.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="testlib.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
<RequiresProcessIsolation>true</RequiresProcessIsolation>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="xprecise4.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="testlib.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.Speech/src/Internal/ObjectToken/RegistryDataKey.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;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Speech.Internal.SapiInterop;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.Speech.Internal.ObjectTokens
{
[DebuggerDisplay("{Name}")]
internal class RegistryDataKey : ISpDataKey, IEnumerable<RegistryDataKey>, IDisposable
{
#region Constructors
protected RegistryDataKey(string fullPath, SafeRegistryHandle regHandle)
{
ISpRegDataKey regKey = (ISpRegDataKey)new SpDataKey();
SAPIErrorCodes hresult = (SAPIErrorCodes)regKey.SetKey(regHandle, false);
regHandle?.Close();
if ((hresult != SAPIErrorCodes.S_OK) && (hresult != SAPIErrorCodes.SPERR_ALREADY_INITIALIZED))
{
throw new InvalidOperationException();
}
_sapiRegKey = regKey;
_sKeyId = fullPath;
_disposeSapiKey = true;
}
protected RegistryDataKey(string fullPath, RegistryKey managedRegKey) :
this(fullPath, managedRegKey.Handle)
{
}
protected RegistryDataKey(string fullPath, RegistryDataKey copyKey)
{
this._sKeyId = fullPath;
this._sapiRegKey = copyKey._sapiRegKey;
this._disposeSapiKey = copyKey._disposeSapiKey;
}
protected RegistryDataKey(string fullPath, ISpDataKey copyKey, bool shouldDispose)
{
this._sKeyId = fullPath;
this._sapiRegKey = copyKey;
this._disposeSapiKey = shouldDispose;
}
protected RegistryDataKey(ISpObjectToken sapiToken) :
this(GetTokenIdFromToken(sapiToken), sapiToken, false)
{
}
internal static RegistryDataKey Open(string registryPath, bool fCreateIfNotExist)
{
// Sanity check
if (string.IsNullOrEmpty(registryPath))
{
return null;
}
// If the last character is a '\', get rid of it
registryPath = registryPath.Trim(new char[] { '\\' });
string rootPath = GetFirstKeyAndParseRemainder(ref registryPath);
// Get the native registry handle and subkey path
SafeRegistryHandle regHandle = RootHKEYFromRegPath(rootPath);
// If there's no root, we can't do anything.
if (regHandle == null || regHandle.IsInvalid)
{
return null;
}
RegistryDataKey rootKey = new(rootPath, regHandle);
// If the path was only a root, we can directly return the key; otherwise,
// we need to open a subkey and return that.
if (string.IsNullOrEmpty(registryPath))
{
return rootKey;
}
else
{
RegistryDataKey subKey = OpenSubKey(rootKey, registryPath, fCreateIfNotExist);
return subKey;
}
}
internal static RegistryDataKey Create(string keyId, RegistryKey hkey)
{
return new RegistryDataKey(keyId, hkey);
}
private static RegistryDataKey OpenSubKey(RegistryDataKey baseKey, string registryPath, bool createIfNotExist)
{
if (string.IsNullOrEmpty(registryPath) || null == baseKey)
{
return null;
}
string nextKeyPath = GetFirstKeyAndParseRemainder(ref registryPath);
RegistryDataKey nextKey = createIfNotExist ? baseKey.CreateKey(nextKeyPath) : baseKey.OpenKey(nextKeyPath);
if (string.IsNullOrEmpty(registryPath))
{
return nextKey;
}
else
{
RegistryDataKey recursiveKey = OpenSubKey(nextKey, registryPath, createIfNotExist);
return recursiveKey;
}
}
private static string GetTokenIdFromToken(ISpObjectToken sapiToken)
{
IntPtr sapiTokenId = IntPtr.Zero;
string tokenId;
try
{
sapiToken.GetId(out sapiTokenId);
tokenId = Marshal.PtrToStringUni(sapiTokenId);
}
finally
{
Marshal.FreeCoTaskMem(sapiTokenId);
}
return tokenId;
}
/// <summary>
/// Needed by IEnumerable
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region internal Methods
#region ISpDataKey Implementation
// ISpDataKey Methods
/// <summary>
/// Writes the specified binary data to the registry.
/// </summary>
[PreserveSig]
public int SetData(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] uint cbData,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data)
{
return _sapiRegKey.SetData(valueName, cbData, data);
}
/// <summary>
/// Reads the specified binary data from the registry.
/// </summary>
[PreserveSig]
public int GetData(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] ref uint pcbData,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data)
{
return _sapiRegKey.GetData(valueName, ref pcbData, data);
}
/// <summary>
/// Writes the specified string value from the registry. If valueName
/// is NULL then the default value of the registry key is read.
/// </summary>
[PreserveSig]
public int SetStringValue(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.LPWStr)] string value)
{
return _sapiRegKey.SetStringValue(valueName, value);
}
/// <summary>
/// Reads the specified string value to the registry. If valueName is
/// NULL then the default value of the registry key is read.
/// </summary>
[PreserveSig]
public int GetStringValue(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.LPWStr)] out string value)
{
return _sapiRegKey.GetStringValue(valueName, out value);
}
/// <summary>
/// Writes the specified DWORD to the registry.
/// </summary>
[PreserveSig]
public int SetDWORD(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] uint value)
{
return _sapiRegKey.SetDWORD(valueName, value);
}
/// <summary>
/// Reads the specified DWORD from the registry.
/// </summary>
[PreserveSig]
public int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pdwValue)
{
return _sapiRegKey.GetDWORD(valueName, ref pdwValue);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
[PreserveSig]
public int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey)
{
return _sapiRegKey.OpenKey(subKeyName, out ppSubKey);
}
/// <summary>
/// Creates a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
[PreserveSig]
public int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey)
{
return _sapiRegKey.CreateKey(subKeyName, out ppSubKey);
}
/// <summary>
/// Deletes the specified key.
/// </summary>
[PreserveSig]
public int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName)
{
return _sapiRegKey.DeleteKey(subKeyName);
}
/// <summary>
/// Deletes the specified value from the key.
/// </summary>
[PreserveSig]
public int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName)
{
return _sapiRegKey.DeleteValue(valueName);
}
/// <summary>
/// Retrieve a key name by index
/// </summary>
[PreserveSig]
public int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName)
{
return _sapiRegKey.EnumKeys(index, out ppszSubKeyName);
}
/// <summary>
/// Retrieves a key value by index
/// </summary>
[PreserveSig]
public int EnumValues(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string valueName)
{
return _sapiRegKey.EnumValues(index, out valueName);
}
#endregion
/// <summary>
/// Full path and name for the key
/// </summary>
internal string Id
{
get
{
return _sKeyId;
}
}
/// <summary>
/// Key Name (no path)
/// </summary>
internal string Name
{
get
{
int iPosSlash = _sKeyId.LastIndexOf('\\');
return _sKeyId.Substring(iPosSlash + 1);
}
}
// Disable parameter validation check
/// <summary>
/// Reads the specified string value to the registry. If valueName is
/// NULL then the default value of the registry key is read.
/// </summary>
internal bool TryGetString(string valueName, out string value)
{
if (null == valueName)
{
valueName = string.Empty;
}
return 0 == GetStringValue(valueName, out value);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal bool HasValue(string valueName)
{
string unusedString;
uint unusedUint = 0;
byte[] unusedBytes = Array.Empty<byte>();
return (
0 == _sapiRegKey.GetStringValue(valueName, out unusedString) ||
0 == _sapiRegKey.GetDWORD(valueName, ref unusedUint) ||
0 == _sapiRegKey.GetData(valueName, ref unusedUint, unusedBytes));
}
/// <summary>
/// Reads the specified DWORD from the registry.
/// </summary>
internal bool TryGetDWORD(string valueName, ref uint value)
{
if (string.IsNullOrEmpty(valueName))
{
return false;
}
return 0 == _sapiRegKey.GetDWORD(valueName, ref value);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal RegistryDataKey OpenKey(string keyName)
{
Helpers.ThrowIfEmptyOrNull(keyName, nameof(keyName));
ISpDataKey sapiSubKey;
if (0 != _sapiRegKey.OpenKey(keyName, out sapiSubKey))
{
return null;
}
else
{
return new RegistryDataKey(_sKeyId + @"\" + keyName, sapiSubKey, true);
}
}
/// <summary>
/// Creates a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal RegistryDataKey CreateKey(string keyName)
{
Helpers.ThrowIfEmptyOrNull(keyName, nameof(keyName));
ISpDataKey sapiSubKey;
if (0 != _sapiRegKey.CreateKey(keyName, out sapiSubKey))
{
return null;
}
else
{
return new RegistryDataKey(_sKeyId + @"\" + keyName, sapiSubKey, true);
}
}
/// <summary>
/// returns the name for all the values in this registry entry
/// </summary>
internal string[] GetValueNames()
{
List<string> valueNames = new();
string valueName;
for (uint i = 0; 0 == _sapiRegKey.EnumValues(i, out valueName); i++)
{
valueNames.Add(valueName);
}
return valueNames.ToArray();
}
#region IEnumerable implementation
IEnumerator<RegistryDataKey> IEnumerable<RegistryDataKey>.GetEnumerator()
{
string childKeyName = string.Empty;
for (uint i = 0; 0 == _sapiRegKey.EnumKeys(i, out childKeyName); i++)
{
yield return this.CreateKey(childKeyName);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<RegistryDataKey>)this).GetEnumerator();
}
#endregion
#endregion
#region Protected Methods
protected virtual void Dispose(bool disposing)
{
if (disposing && _sapiRegKey != null && _disposeSapiKey)
{
Marshal.ReleaseComObject(_sapiRegKey);
_sapiRegKey = null;
}
}
#endregion
#region Internal Fields
internal string _sKeyId;
internal ISpDataKey _sapiRegKey;
internal bool _disposeSapiKey;
#endregion
#region Private Methods
private static SafeRegistryHandle RootHKEYFromRegPath(string rootPath)
{
RegistryKey rootKey = RegKeyFromRootPath(rootPath);
if (null == rootKey)
{
return null;
}
return rootKey.Handle;
}
private static string GetFirstKeyAndParseRemainder(ref string registryPath)
{
int index = registryPath.IndexOf('\\');
string firstKey;
if (index >= 0)
{
firstKey = registryPath.Substring(0, index);
registryPath = registryPath.Substring(index + 1, registryPath.Length - index - 1);
}
else
{
firstKey = registryPath;
registryPath = string.Empty;
}
return firstKey;
}
private static RegistryKey RegKeyFromRootPath(string rootPath)
{
RegistryKey[] roots = new RegistryKey[] {
Registry.ClassesRoot,
Registry.LocalMachine,
Registry.CurrentUser,
Registry.CurrentConfig
};
foreach (RegistryKey key in roots)
{
if (key.Name.Equals(rootPath, StringComparison.OrdinalIgnoreCase))
{
return key;
}
}
return null;
}
#endregion
#region private Types
internal enum SAPIErrorCodes
{
STG_E_FILENOTFOUND = -2147287038, // 0x80030002
SPERR_ALREADY_INITIALIZED = -2147201022, // 0x80045002
SPERR_UNSUPPORTED_FORMAT = -2147201021, // 0x80045003
SPERR_DEVICE_BUSY = -2147201018, // 0x80045006
SPERR_DEVICE_NOT_SUPPORTED = -2147201017, // 0x80045007
SPERR_DEVICE_NOT_ENABLED = -2147201016, // 0x80045008
SPERR_NO_DRIVER = -2147201015, // 0x80045009
SPERR_TOO_MANY_GRAMMARS = -2147200990, // 0x80045022
SPERR_INVALID_IMPORT = -2147200988, // 0x80045024
SPERR_AUDIO_BUFFER_OVERFLOW = -2147200977, // 0x8004502F
SPERR_NO_AUDIO_DATA = -2147200976, // 0x80045030
SPERR_NO_MORE_ITEMS = -2147200967, // 0x80045039
SPERR_NOT_FOUND = -2147200966, // 0x8004503A
SPERR_GENERIC_MMSYS_ERROR = -2147200964, // 0x8004503C
SPERR_NOT_TOPLEVEL_RULE = -2147200940, // 0x80045054
SPERR_NOT_ACTIVE_SESSION = -2147200925, // 0x80045063
SPERR_SML_GENERATION_FAIL = -2147200921, // 0x80045067
SPERR_SHARED_ENGINE_DISABLED = -2147200906, // 0x80045076
SPERR_RECOGNIZER_NOT_FOUND = -2147200905, // 0x80045077
SPERR_AUDIO_NOT_FOUND = -2147200904, // 0x80045078
S_OK = 0, // 0x00000000
S_FALSE = 1, // 0x00000001
E_INVALIDARG = -2147024809, // 0x80070057
SP_NO_RULES_TO_ACTIVATE = 282747, // 0x0004507B
ERROR_MORE_DATA = 0x50EA,
}
#endregion
}
}
| // 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;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Speech.Internal.SapiInterop;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace System.Speech.Internal.ObjectTokens
{
[DebuggerDisplay("{Name}")]
internal class RegistryDataKey : ISpDataKey, IEnumerable<RegistryDataKey>, IDisposable
{
#region Constructors
protected RegistryDataKey(string fullPath, SafeRegistryHandle regHandle)
{
ISpRegDataKey regKey = (ISpRegDataKey)new SpDataKey();
SAPIErrorCodes hresult = (SAPIErrorCodes)regKey.SetKey(regHandle, false);
regHandle?.Close();
if ((hresult != SAPIErrorCodes.S_OK) && (hresult != SAPIErrorCodes.SPERR_ALREADY_INITIALIZED))
{
throw new InvalidOperationException();
}
_sapiRegKey = regKey;
_sKeyId = fullPath;
_disposeSapiKey = true;
}
protected RegistryDataKey(string fullPath, RegistryKey managedRegKey) :
this(fullPath, managedRegKey.Handle)
{
}
protected RegistryDataKey(string fullPath, RegistryDataKey copyKey)
{
this._sKeyId = fullPath;
this._sapiRegKey = copyKey._sapiRegKey;
this._disposeSapiKey = copyKey._disposeSapiKey;
}
protected RegistryDataKey(string fullPath, ISpDataKey copyKey, bool shouldDispose)
{
this._sKeyId = fullPath;
this._sapiRegKey = copyKey;
this._disposeSapiKey = shouldDispose;
}
protected RegistryDataKey(ISpObjectToken sapiToken) :
this(GetTokenIdFromToken(sapiToken), sapiToken, false)
{
}
internal static RegistryDataKey Open(string registryPath, bool fCreateIfNotExist)
{
// Sanity check
if (string.IsNullOrEmpty(registryPath))
{
return null;
}
// If the last character is a '\', get rid of it
registryPath = registryPath.Trim(new char[] { '\\' });
string rootPath = GetFirstKeyAndParseRemainder(ref registryPath);
// Get the native registry handle and subkey path
SafeRegistryHandle regHandle = RootHKEYFromRegPath(rootPath);
// If there's no root, we can't do anything.
if (regHandle == null || regHandle.IsInvalid)
{
return null;
}
RegistryDataKey rootKey = new(rootPath, regHandle);
// If the path was only a root, we can directly return the key; otherwise,
// we need to open a subkey and return that.
if (string.IsNullOrEmpty(registryPath))
{
return rootKey;
}
else
{
RegistryDataKey subKey = OpenSubKey(rootKey, registryPath, fCreateIfNotExist);
return subKey;
}
}
internal static RegistryDataKey Create(string keyId, RegistryKey hkey)
{
return new RegistryDataKey(keyId, hkey);
}
private static RegistryDataKey OpenSubKey(RegistryDataKey baseKey, string registryPath, bool createIfNotExist)
{
if (string.IsNullOrEmpty(registryPath) || null == baseKey)
{
return null;
}
string nextKeyPath = GetFirstKeyAndParseRemainder(ref registryPath);
RegistryDataKey nextKey = createIfNotExist ? baseKey.CreateKey(nextKeyPath) : baseKey.OpenKey(nextKeyPath);
if (string.IsNullOrEmpty(registryPath))
{
return nextKey;
}
else
{
RegistryDataKey recursiveKey = OpenSubKey(nextKey, registryPath, createIfNotExist);
return recursiveKey;
}
}
private static string GetTokenIdFromToken(ISpObjectToken sapiToken)
{
IntPtr sapiTokenId = IntPtr.Zero;
string tokenId;
try
{
sapiToken.GetId(out sapiTokenId);
tokenId = Marshal.PtrToStringUni(sapiTokenId);
}
finally
{
Marshal.FreeCoTaskMem(sapiTokenId);
}
return tokenId;
}
/// <summary>
/// Needed by IEnumerable
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region internal Methods
#region ISpDataKey Implementation
// ISpDataKey Methods
/// <summary>
/// Writes the specified binary data to the registry.
/// </summary>
[PreserveSig]
public int SetData(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] uint cbData,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data)
{
return _sapiRegKey.SetData(valueName, cbData, data);
}
/// <summary>
/// Reads the specified binary data from the registry.
/// </summary>
[PreserveSig]
public int GetData(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] ref uint pcbData,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data)
{
return _sapiRegKey.GetData(valueName, ref pcbData, data);
}
/// <summary>
/// Writes the specified string value from the registry. If valueName
/// is NULL then the default value of the registry key is read.
/// </summary>
[PreserveSig]
public int SetStringValue(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.LPWStr)] string value)
{
return _sapiRegKey.SetStringValue(valueName, value);
}
/// <summary>
/// Reads the specified string value to the registry. If valueName is
/// NULL then the default value of the registry key is read.
/// </summary>
[PreserveSig]
public int GetStringValue(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.LPWStr)] out string value)
{
return _sapiRegKey.GetStringValue(valueName, out value);
}
/// <summary>
/// Writes the specified DWORD to the registry.
/// </summary>
[PreserveSig]
public int SetDWORD(
[MarshalAs(UnmanagedType.LPWStr)] string valueName,
[MarshalAs(UnmanagedType.SysUInt)] uint value)
{
return _sapiRegKey.SetDWORD(valueName, value);
}
/// <summary>
/// Reads the specified DWORD from the registry.
/// </summary>
[PreserveSig]
public int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pdwValue)
{
return _sapiRegKey.GetDWORD(valueName, ref pdwValue);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
[PreserveSig]
public int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey)
{
return _sapiRegKey.OpenKey(subKeyName, out ppSubKey);
}
/// <summary>
/// Creates a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
[PreserveSig]
public int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey)
{
return _sapiRegKey.CreateKey(subKeyName, out ppSubKey);
}
/// <summary>
/// Deletes the specified key.
/// </summary>
[PreserveSig]
public int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName)
{
return _sapiRegKey.DeleteKey(subKeyName);
}
/// <summary>
/// Deletes the specified value from the key.
/// </summary>
[PreserveSig]
public int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName)
{
return _sapiRegKey.DeleteValue(valueName);
}
/// <summary>
/// Retrieve a key name by index
/// </summary>
[PreserveSig]
public int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName)
{
return _sapiRegKey.EnumKeys(index, out ppszSubKeyName);
}
/// <summary>
/// Retrieves a key value by index
/// </summary>
[PreserveSig]
public int EnumValues(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string valueName)
{
return _sapiRegKey.EnumValues(index, out valueName);
}
#endregion
/// <summary>
/// Full path and name for the key
/// </summary>
internal string Id
{
get
{
return _sKeyId;
}
}
/// <summary>
/// Key Name (no path)
/// </summary>
internal string Name
{
get
{
int iPosSlash = _sKeyId.LastIndexOf('\\');
return _sKeyId.Substring(iPosSlash + 1);
}
}
// Disable parameter validation check
/// <summary>
/// Reads the specified string value to the registry. If valueName is
/// NULL then the default value of the registry key is read.
/// </summary>
internal bool TryGetString(string valueName, out string value)
{
if (null == valueName)
{
valueName = string.Empty;
}
return 0 == GetStringValue(valueName, out value);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal bool HasValue(string valueName)
{
string unusedString;
uint unusedUint = 0;
byte[] unusedBytes = Array.Empty<byte>();
return (
0 == _sapiRegKey.GetStringValue(valueName, out unusedString) ||
0 == _sapiRegKey.GetDWORD(valueName, ref unusedUint) ||
0 == _sapiRegKey.GetData(valueName, ref unusedUint, unusedBytes));
}
/// <summary>
/// Reads the specified DWORD from the registry.
/// </summary>
internal bool TryGetDWORD(string valueName, ref uint value)
{
if (string.IsNullOrEmpty(valueName))
{
return false;
}
return 0 == _sapiRegKey.GetDWORD(valueName, ref value);
}
/// <summary>
/// Opens a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal RegistryDataKey OpenKey(string keyName)
{
Helpers.ThrowIfEmptyOrNull(keyName, nameof(keyName));
ISpDataKey sapiSubKey;
if (0 != _sapiRegKey.OpenKey(keyName, out sapiSubKey))
{
return null;
}
else
{
return new RegistryDataKey(_sKeyId + @"\" + keyName, sapiSubKey, true);
}
}
/// <summary>
/// Creates a sub-key and returns a new object which supports SpDataKey
/// for the specified sub-key.
/// </summary>
internal RegistryDataKey CreateKey(string keyName)
{
Helpers.ThrowIfEmptyOrNull(keyName, nameof(keyName));
ISpDataKey sapiSubKey;
if (0 != _sapiRegKey.CreateKey(keyName, out sapiSubKey))
{
return null;
}
else
{
return new RegistryDataKey(_sKeyId + @"\" + keyName, sapiSubKey, true);
}
}
/// <summary>
/// returns the name for all the values in this registry entry
/// </summary>
internal string[] GetValueNames()
{
List<string> valueNames = new();
string valueName;
for (uint i = 0; 0 == _sapiRegKey.EnumValues(i, out valueName); i++)
{
valueNames.Add(valueName);
}
return valueNames.ToArray();
}
#region IEnumerable implementation
IEnumerator<RegistryDataKey> IEnumerable<RegistryDataKey>.GetEnumerator()
{
string childKeyName = string.Empty;
for (uint i = 0; 0 == _sapiRegKey.EnumKeys(i, out childKeyName); i++)
{
yield return this.CreateKey(childKeyName);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<RegistryDataKey>)this).GetEnumerator();
}
#endregion
#endregion
#region Protected Methods
protected virtual void Dispose(bool disposing)
{
if (disposing && _sapiRegKey != null && _disposeSapiKey)
{
Marshal.ReleaseComObject(_sapiRegKey);
_sapiRegKey = null;
}
}
#endregion
#region Internal Fields
internal string _sKeyId;
internal ISpDataKey _sapiRegKey;
internal bool _disposeSapiKey;
#endregion
#region Private Methods
private static SafeRegistryHandle RootHKEYFromRegPath(string rootPath)
{
RegistryKey rootKey = RegKeyFromRootPath(rootPath);
if (null == rootKey)
{
return null;
}
return rootKey.Handle;
}
private static string GetFirstKeyAndParseRemainder(ref string registryPath)
{
int index = registryPath.IndexOf('\\');
string firstKey;
if (index >= 0)
{
firstKey = registryPath.Substring(0, index);
registryPath = registryPath.Substring(index + 1, registryPath.Length - index - 1);
}
else
{
firstKey = registryPath;
registryPath = string.Empty;
}
return firstKey;
}
private static RegistryKey RegKeyFromRootPath(string rootPath)
{
RegistryKey[] roots = new RegistryKey[] {
Registry.ClassesRoot,
Registry.LocalMachine,
Registry.CurrentUser,
Registry.CurrentConfig
};
foreach (RegistryKey key in roots)
{
if (key.Name.Equals(rootPath, StringComparison.OrdinalIgnoreCase))
{
return key;
}
}
return null;
}
#endregion
#region private Types
internal enum SAPIErrorCodes
{
STG_E_FILENOTFOUND = -2147287038, // 0x80030002
SPERR_ALREADY_INITIALIZED = -2147201022, // 0x80045002
SPERR_UNSUPPORTED_FORMAT = -2147201021, // 0x80045003
SPERR_DEVICE_BUSY = -2147201018, // 0x80045006
SPERR_DEVICE_NOT_SUPPORTED = -2147201017, // 0x80045007
SPERR_DEVICE_NOT_ENABLED = -2147201016, // 0x80045008
SPERR_NO_DRIVER = -2147201015, // 0x80045009
SPERR_TOO_MANY_GRAMMARS = -2147200990, // 0x80045022
SPERR_INVALID_IMPORT = -2147200988, // 0x80045024
SPERR_AUDIO_BUFFER_OVERFLOW = -2147200977, // 0x8004502F
SPERR_NO_AUDIO_DATA = -2147200976, // 0x80045030
SPERR_NO_MORE_ITEMS = -2147200967, // 0x80045039
SPERR_NOT_FOUND = -2147200966, // 0x8004503A
SPERR_GENERIC_MMSYS_ERROR = -2147200964, // 0x8004503C
SPERR_NOT_TOPLEVEL_RULE = -2147200940, // 0x80045054
SPERR_NOT_ACTIVE_SESSION = -2147200925, // 0x80045063
SPERR_SML_GENERATION_FAIL = -2147200921, // 0x80045067
SPERR_SHARED_ENGINE_DISABLED = -2147200906, // 0x80045076
SPERR_RECOGNIZER_NOT_FOUND = -2147200905, // 0x80045077
SPERR_AUDIO_NOT_FOUND = -2147200904, // 0x80045078
S_OK = 0, // 0x00000000
S_FALSE = 1, // 0x00000001
E_INVALIDARG = -2147024809, // 0x80070057
SP_NO_RULES_TO_ACTIVATE = 282747, // 0x0004507B
ERROR_MORE_DATA = 0x50EA,
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/HardwareIntrinsics/X86/Avx1/TestNotZAndNotC.UInt32.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 TestNotZAndNotCUInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 BooleanBinaryOpTest__TestNotZAndNotCUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCUInt32 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCUInt32 testClass)
{
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pClsVar1)),
Avx.LoadVector256((UInt32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
fixed (Vector256<UInt32>* pFld1 = &test._fld1)
fixed (Vector256<UInt32>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(&test._fld1)),
Avx.LoadVector256((UInt32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
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(Vector256<UInt32> op1, Vector256<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({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 TestNotZAndNotCUInt32()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 BooleanBinaryOpTest__TestNotZAndNotCUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCUInt32 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCUInt32 testClass)
{
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pClsVar1)),
Avx.LoadVector256((UInt32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt32();
fixed (Vector256<UInt32>* pFld1 = &test._fld1)
fixed (Vector256<UInt32>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt32>* pFld1 = &_fld1)
fixed (Vector256<UInt32>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(pFld1)),
Avx.LoadVector256((UInt32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt32*)(&test._fld1)),
Avx.LoadVector256((UInt32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
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(Vector256<UInt32> op1, Vector256<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddHighNarrowingLower.Vector64.UInt32.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 AddHighNarrowingLower_Vector64_UInt32()
{
var test = new SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32();
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 SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32 testClass)
{
var result = AdvSimd.AddHighNarrowingLower(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[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.AddHighNarrowingLower(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_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 = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingLower), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingLower), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddHighNarrowingLower(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddHighNarrowingLower(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddHighNarrowingLower(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32();
var result = AdvSimd.AddHighNarrowingLower(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__AddHighNarrowingLower_Vector64_UInt32();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddHighNarrowingLower(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(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 = AdvSimd.AddHighNarrowingLower(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 = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddHighNarrowing(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingLower)}<UInt32>(Vector128<UInt64>, Vector128<UInt64>): {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.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 AddHighNarrowingLower_Vector64_UInt32()
{
var test = new SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32();
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 SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32
{
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(UInt64[] inArray1, UInt64[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1;
public Vector128<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32 testClass)
{
var result = AdvSimd.AddHighNarrowingLower(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32 testClass)
{
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[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.AddHighNarrowingLower(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_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 = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingLower), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingLower), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddHighNarrowingLower(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pClsVar1)),
AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddHighNarrowingLower(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddHighNarrowingLower(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddHighNarrowingLower_Vector64_UInt32();
var result = AdvSimd.AddHighNarrowingLower(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__AddHighNarrowingLower_Vector64_UInt32();
fixed (Vector128<UInt64>* pFld1 = &test._fld1)
fixed (Vector128<UInt64>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddHighNarrowingLower(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt64>* pFld1 = &_fld1)
fixed (Vector128<UInt64>* pFld2 = &_fld2)
{
var result = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(pFld1)),
AdvSimd.LoadVector128((UInt64*)(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 = AdvSimd.AddHighNarrowingLower(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 = AdvSimd.AddHighNarrowingLower(
AdvSimd.LoadVector128((UInt64*)(&test._fld1)),
AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddHighNarrowing(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingLower)}<UInt32>(Vector128<UInt64>, Vector128<UInt64>): {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 | 66,216 | Add missing regex position check after BOL optimization | Fixes https://github.com/dotnet/runtime/issues/66212 | stephentoub | 2022-03-04T20:44:31Z | 2022-03-07T00:13:14Z | 9f513350e3cea5cc56f9d7fb8e006382ec5043ff | 277e12ba998ff91c49ef96c378b616369d7e9af7 | Add missing regex position check after BOL optimization. Fixes https://github.com/dotnet/runtime/issues/66212 | ./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.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;
namespace System.ComponentModel
{
/// <summary>
/// Provides a type converter to convert 8-bit unsigned integer objects to and from
/// various other representations.
/// </summary>
public class SByteConverter : BaseNumberConverter
{
/// <summary>
/// The Type this converter is targeting (e.g. Int16, UInt32, etc.)
/// </summary>
internal override Type TargetType => typeof(sbyte);
/// <summary>
/// Convert the given value to a string using the given radix
/// </summary>
internal override object FromString(string value, int radix) => Convert.ToSByte(value, radix);
/// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
internal override object FromString(string value, NumberFormatInfo? formatInfo)
{
return sbyte.Parse(value, NumberStyles.Integer, formatInfo);
}
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
internal override string ToString(object value, NumberFormatInfo? formatInfo)
{
return ((sbyte)value).ToString("G", formatInfo);
}
}
}
| // 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;
namespace System.ComponentModel
{
/// <summary>
/// Provides a type converter to convert 8-bit unsigned integer objects to and from
/// various other representations.
/// </summary>
public class SByteConverter : BaseNumberConverter
{
/// <summary>
/// The Type this converter is targeting (e.g. Int16, UInt32, etc.)
/// </summary>
internal override Type TargetType => typeof(sbyte);
/// <summary>
/// Convert the given value to a string using the given radix
/// </summary>
internal override object FromString(string value, int radix) => Convert.ToSByte(value, radix);
/// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
internal override object FromString(string value, NumberFormatInfo? formatInfo)
{
return sbyte.Parse(value, NumberStyles.Integer, formatInfo);
}
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
internal override string ToString(object value, NumberFormatInfo? formatInfo)
{
return ((sbyte)value).ToString("G", formatInfo);
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.Caching.Memory/ref/Microsoft.Extensions.Caching.Memory.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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Caching.Distributed
{
public partial class MemoryDistributedCache : Microsoft.Extensions.Caching.Distributed.IDistributedCache
{
public MemoryDistributedCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> optionsAccessor) { }
public MemoryDistributedCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> optionsAccessor, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
public byte[]? Get(string key) { throw null; }
public System.Threading.Tasks.Task<byte[]?> GetAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Refresh(string key) { }
public System.Threading.Tasks.Task RefreshAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Remove(string key) { }
public System.Threading.Tasks.Task RemoveAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Set(string key, byte[] value, Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions options) { }
public System.Threading.Tasks.Task SetAsync(string key, byte[] value, Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions options, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Microsoft.Extensions.Caching.Memory
{
public partial class MemoryCache : Microsoft.Extensions.Caching.Memory.IMemoryCache, System.IDisposable
{
public MemoryCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> optionsAccessor) { }
public MemoryCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> optionsAccessor, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
public int Count { get { throw null; } }
public void Compact(double percentage) { }
public Microsoft.Extensions.Caching.Memory.ICacheEntry CreateEntry(object key) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~MemoryCache() { }
public void Remove(object key) { }
public bool TryGetValue(object key, out object? result) { throw null; }
public void Clear() { }
}
public partial class MemoryCacheOptions : Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions>
{
public MemoryCacheOptions() { }
public Microsoft.Extensions.Internal.ISystemClock? Clock { get { throw null; } set { } }
public double CompactionPercentage { get { throw null; } set { } }
public System.TimeSpan ExpirationScanFrequency { get { throw null; } set { } }
Microsoft.Extensions.Caching.Memory.MemoryCacheOptions Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions>.Value { get { throw null; } }
public long? SizeLimit { get { throw null; } set { } }
public bool TrackLinkedCacheEntries { get { throw null; } set { } }
}
public partial class MemoryDistributedCacheOptions : Microsoft.Extensions.Caching.Memory.MemoryCacheOptions
{
public MemoryDistributedCacheOptions() { }
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static partial class MemoryCacheServiceCollectionExtensions
{
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddDistributedMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddDistributedMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Action<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> setupAction) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Action<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> setupAction) { throw null; }
}
}
| // 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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Caching.Distributed
{
public partial class MemoryDistributedCache : Microsoft.Extensions.Caching.Distributed.IDistributedCache
{
public MemoryDistributedCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> optionsAccessor) { }
public MemoryDistributedCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> optionsAccessor, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
public byte[]? Get(string key) { throw null; }
public System.Threading.Tasks.Task<byte[]?> GetAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Refresh(string key) { }
public System.Threading.Tasks.Task RefreshAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Remove(string key) { }
public System.Threading.Tasks.Task RemoveAsync(string key, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
public void Set(string key, byte[] value, Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions options) { }
public System.Threading.Tasks.Task SetAsync(string key, byte[] value, Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions options, System.Threading.CancellationToken token = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Microsoft.Extensions.Caching.Memory
{
public partial class MemoryCache : Microsoft.Extensions.Caching.Memory.IMemoryCache, System.IDisposable
{
public MemoryCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> optionsAccessor) { }
public MemoryCache(Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> optionsAccessor, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
public int Count { get { throw null; } }
public void Clear() { }
public void Compact(double percentage) { }
public Microsoft.Extensions.Caching.Memory.ICacheEntry CreateEntry(object key) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~MemoryCache() { }
public void Remove(object key) { }
public bool TryGetValue(object key, out object? result) { throw null; }
}
public partial class MemoryCacheOptions : Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions>
{
public MemoryCacheOptions() { }
public Microsoft.Extensions.Internal.ISystemClock? Clock { get { throw null; } set { } }
public double CompactionPercentage { get { throw null; } set { } }
public System.TimeSpan ExpirationScanFrequency { get { throw null; } set { } }
Microsoft.Extensions.Caching.Memory.MemoryCacheOptions Microsoft.Extensions.Options.IOptions<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions>.Value { get { throw null; } }
public long? SizeLimit { get { throw null; } set { } }
public bool TrackLinkedCacheEntries { get { throw null; } set { } }
}
public partial class MemoryDistributedCacheOptions : Microsoft.Extensions.Caching.Memory.MemoryCacheOptions
{
public MemoryDistributedCacheOptions() { }
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static partial class MemoryCacheServiceCollectionExtensions
{
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddDistributedMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddDistributedMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Action<Microsoft.Extensions.Caching.Memory.MemoryDistributedCacheOptions> setupAction) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) { throw null; }
public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddMemoryCache(this Microsoft.Extensions.DependencyInjection.IServiceCollection services, System.Action<Microsoft.Extensions.Caching.Memory.MemoryCacheOptions> setupAction) { throw null; }
}
}
| 1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.Configuration.Binder/ref/Microsoft.Extensions.Configuration.Binder.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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Configuration
{
public partial class BinderOptions
{
public BinderOptions() { }
public bool BindNonPublicProperties { get { throw null; } set { } }
public bool ErrorOnUnknownConfiguration { get { throw null; } set { } }
}
public static partial class ConfigurationBinder
{
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, object? instance) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Type type) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key, object defaultValue) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, T defaultValue) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; }
}
}
| // 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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Configuration
{
public partial class BinderOptions
{
public BinderOptions() { }
public bool BindNonPublicProperties { get { throw null; } set { } }
public bool ErrorOnUnknownConfiguration { get { throw null; } set { } }
}
public static partial class ConfigurationBinder
{
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")]
public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, object? instance) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Type type) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key, object? defaultValue) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, T defaultValue) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")]
public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; }
}
}
| 1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.Primitives/ref/Microsoft.Extensions.Primitives.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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Primitives
{
public partial class CancellationChangeToken : Microsoft.Extensions.Primitives.IChangeToken
{
public CancellationChangeToken(System.Threading.CancellationToken cancellationToken) { }
public bool ActiveChangeCallbacks { get { throw null; } }
public bool HasChanged { get { throw null; } }
public System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state) { throw null; }
}
public static partial class ChangeToken
{
public static System.IDisposable OnChange(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action changeTokenConsumer) { throw null; }
public static System.IDisposable OnChange<TState>(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action<TState> changeTokenConsumer, TState state) { throw null; }
}
public partial class CompositeChangeToken : Microsoft.Extensions.Primitives.IChangeToken
{
public CompositeChangeToken(System.Collections.Generic.IReadOnlyList<Microsoft.Extensions.Primitives.IChangeToken> changeTokens) { }
public bool ActiveChangeCallbacks { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Microsoft.Extensions.Primitives.IChangeToken> ChangeTokens { get { throw null; } }
public bool HasChanged { get { throw null; } }
public System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state) { throw null; }
}
public static partial class Extensions
{
public static System.Text.StringBuilder Append(this System.Text.StringBuilder builder, Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
}
public partial interface IChangeToken
{
bool ActiveChangeCallbacks { get; }
bool HasChanged { get; }
System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state);
}
public readonly partial struct StringSegment : System.IEquatable<Microsoft.Extensions.Primitives.StringSegment>, System.IEquatable<string?>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static readonly Microsoft.Extensions.Primitives.StringSegment Empty;
public StringSegment(string? buffer) { throw null; }
public StringSegment(string buffer, int offset, int length) { throw null; }
public string? Buffer { get { throw null; } }
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(Buffer))]
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(Value))]
public bool HasValue { get { throw null; } }
public char this[int index] { get { throw null; } }
public int Length { get { throw null; } }
public int Offset { get { throw null; } }
public string? Value { get { throw null; } }
public System.ReadOnlyMemory<char> AsMemory() { throw null; }
public System.ReadOnlySpan<char> AsSpan() { throw null; }
public System.ReadOnlySpan<char> AsSpan(int start) { throw null; }
public System.ReadOnlySpan<char> AsSpan(int start, int length) { throw null; }
public static int Compare(Microsoft.Extensions.Primitives.StringSegment a, Microsoft.Extensions.Primitives.StringSegment b, System.StringComparison comparisonType) { throw null; }
public bool EndsWith(string text, System.StringComparison comparisonType) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment other) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringSegment a, Microsoft.Extensions.Primitives.StringSegment b, System.StringComparison comparisonType) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment other, System.StringComparison comparisonType) { throw null; }
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; }
public bool Equals(string? text) { throw null; }
public bool Equals(string? text, System.StringComparison comparisonType) { throw null; }
public override int GetHashCode() { throw null; }
public int IndexOf(char c) { throw null; }
public int IndexOf(char c, int start) { throw null; }
public int IndexOf(char c, int start, int count) { throw null; }
public int IndexOfAny(char[] anyOf) { throw null; }
public int IndexOfAny(char[] anyOf, int startIndex) { throw null; }
public int IndexOfAny(char[] anyOf, int startIndex, int count) { throw null; }
public static bool IsNullOrEmpty(Microsoft.Extensions.Primitives.StringSegment value) { throw null; }
public int LastIndexOf(char value) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringSegment left, Microsoft.Extensions.Primitives.StringSegment right) { throw null; }
public static implicit operator System.ReadOnlyMemory<char>(Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
public static implicit operator System.ReadOnlySpan<char>(Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringSegment(string? value) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringSegment left, Microsoft.Extensions.Primitives.StringSegment right) { throw null; }
public Microsoft.Extensions.Primitives.StringTokenizer Split(char[] chars) { throw null; }
public bool StartsWith(string text, System.StringComparison comparisonType) { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Subsegment(int offset) { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Subsegment(int offset, int length) { throw null; }
public string Substring(int offset) { throw null; }
public string Substring(int offset, int length) { throw null; }
public override string ToString() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Trim() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment TrimEnd() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment TrimStart() { throw null; }
}
public partial class StringSegmentComparer : System.Collections.Generic.IComparer<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.Generic.IEqualityComparer<Microsoft.Extensions.Primitives.StringSegment>
{
internal StringSegmentComparer() { }
public static Microsoft.Extensions.Primitives.StringSegmentComparer Ordinal { get { throw null; } }
public static Microsoft.Extensions.Primitives.StringSegmentComparer OrdinalIgnoreCase { get { throw null; } }
public int Compare(Microsoft.Extensions.Primitives.StringSegment x, Microsoft.Extensions.Primitives.StringSegment y) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment x, Microsoft.Extensions.Primitives.StringSegment y) { throw null; }
public int GetHashCode(Microsoft.Extensions.Primitives.StringSegment obj) { throw null; }
}
public readonly partial struct StringTokenizer : System.Collections.Generic.IEnumerable<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.IEnumerable
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public StringTokenizer(Microsoft.Extensions.Primitives.StringSegment value, char[] separators) { throw null; }
public StringTokenizer(string value, char[] separators) { throw null; }
public Microsoft.Extensions.Primitives.StringTokenizer.Enumerator GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<Microsoft.Extensions.Primitives.StringSegment> System.Collections.Generic.IEnumerable<Microsoft.Extensions.Primitives.StringSegment>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial struct Enumerator : System.Collections.Generic.IEnumerator<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public Enumerator(ref Microsoft.Extensions.Primitives.StringTokenizer tokenizer) { throw null; }
public readonly Microsoft.Extensions.Primitives.StringSegment Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public readonly partial struct StringValues : System.Collections.Generic.ICollection<string?>, System.Collections.Generic.IEnumerable<string?>, System.Collections.Generic.IList<string?>, System.Collections.Generic.IReadOnlyCollection<string?>, System.Collections.Generic.IReadOnlyList<string?>, System.Collections.IEnumerable, System.IEquatable<Microsoft.Extensions.Primitives.StringValues>, System.IEquatable<string?>, System.IEquatable<string?[]>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static readonly Microsoft.Extensions.Primitives.StringValues Empty;
public StringValues(string? value) { throw null; }
public StringValues(string?[]? values) { throw null; }
public int Count { get { throw null; } }
public string? this[int index] { get { throw null; } }
bool System.Collections.Generic.ICollection<System.String?>.IsReadOnly { get { throw null; } }
string? System.Collections.Generic.IList<System.String?>.this[int index] { get { throw null; } set { } }
public static Microsoft.Extensions.Primitives.StringValues Concat(Microsoft.Extensions.Primitives.StringValues values1, Microsoft.Extensions.Primitives.StringValues values2) { throw null; }
public static Microsoft.Extensions.Primitives.StringValues Concat(in Microsoft.Extensions.Primitives.StringValues values, string? value) { throw null; }
public static Microsoft.Extensions.Primitives.StringValues Concat(string? value, in Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringValues other) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public override bool Equals(object? obj) { throw null; }
public bool Equals(string? other) { throw null; }
public static bool Equals(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public bool Equals(string?[]? other) { throw null; }
public static bool Equals(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public Microsoft.Extensions.Primitives.StringValues.Enumerator GetEnumerator() { throw null; }
public override int GetHashCode() { throw null; }
public static bool IsNullOrEmpty(Microsoft.Extensions.Primitives.StringValues value) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, object? right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public static bool operator ==(object? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static implicit operator string?(Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public static implicit operator string?[]?(Microsoft.Extensions.Primitives.StringValues value) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringValues(string? value) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringValues(string?[]? values) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, object? right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public static bool operator !=(object? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
void System.Collections.Generic.ICollection<System.String?>.Add(string? item) { }
void System.Collections.Generic.ICollection<System.String?>.Clear() { }
bool System.Collections.Generic.ICollection<System.String?>.Contains(string? item) { throw null; }
void System.Collections.Generic.ICollection<System.String?>.CopyTo(string?[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.String?>.Remove(string? item) { throw null; }
System.Collections.Generic.IEnumerator<string?> System.Collections.Generic.IEnumerable<System.String?>.GetEnumerator() { throw null; }
int System.Collections.Generic.IList<System.String?>.IndexOf(string? item) { throw null; }
void System.Collections.Generic.IList<System.String?>.Insert(int index, string? item) { }
void System.Collections.Generic.IList<System.String?>.RemoveAt(int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public string?[] ToArray() { throw null; }
public override string ToString() { throw null; }
public partial struct Enumerator : System.Collections.Generic.IEnumerator<string?>, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public Enumerator(ref Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public string? Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
}
| // 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.
// ------------------------------------------------------------------------------
namespace Microsoft.Extensions.Primitives
{
public partial class CancellationChangeToken : Microsoft.Extensions.Primitives.IChangeToken
{
public CancellationChangeToken(System.Threading.CancellationToken cancellationToken) { }
public bool ActiveChangeCallbacks { get { throw null; } }
public bool HasChanged { get { throw null; } }
public System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state) { throw null; }
}
public static partial class ChangeToken
{
public static System.IDisposable OnChange(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action changeTokenConsumer) { throw null; }
public static System.IDisposable OnChange<TState>(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action<TState> changeTokenConsumer, TState state) { throw null; }
}
public partial class CompositeChangeToken : Microsoft.Extensions.Primitives.IChangeToken
{
public CompositeChangeToken(System.Collections.Generic.IReadOnlyList<Microsoft.Extensions.Primitives.IChangeToken> changeTokens) { }
public bool ActiveChangeCallbacks { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Microsoft.Extensions.Primitives.IChangeToken> ChangeTokens { get { throw null; } }
public bool HasChanged { get { throw null; } }
public System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state) { throw null; }
}
public static partial class Extensions
{
public static System.Text.StringBuilder Append(this System.Text.StringBuilder builder, Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
}
public partial interface IChangeToken
{
bool ActiveChangeCallbacks { get; }
bool HasChanged { get; }
System.IDisposable RegisterChangeCallback(System.Action<object?> callback, object? state);
}
public readonly partial struct StringSegment : System.IEquatable<Microsoft.Extensions.Primitives.StringSegment>, System.IEquatable<string?>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static readonly Microsoft.Extensions.Primitives.StringSegment Empty;
public StringSegment(string? buffer) { throw null; }
public StringSegment(string buffer, int offset, int length) { throw null; }
public string? Buffer { get { throw null; } }
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(Buffer))]
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(Value))]
public bool HasValue { get { throw null; } }
public char this[int index] { get { throw null; } }
public int Length { get { throw null; } }
public int Offset { get { throw null; } }
public string? Value { get { throw null; } }
public System.ReadOnlyMemory<char> AsMemory() { throw null; }
public System.ReadOnlySpan<char> AsSpan() { throw null; }
public System.ReadOnlySpan<char> AsSpan(int start) { throw null; }
public System.ReadOnlySpan<char> AsSpan(int start, int length) { throw null; }
public static int Compare(Microsoft.Extensions.Primitives.StringSegment a, Microsoft.Extensions.Primitives.StringSegment b, System.StringComparison comparisonType) { throw null; }
public bool EndsWith(string text, System.StringComparison comparisonType) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment other) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringSegment a, Microsoft.Extensions.Primitives.StringSegment b, System.StringComparison comparisonType) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment other, System.StringComparison comparisonType) { throw null; }
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; }
public bool Equals(string? text) { throw null; }
public bool Equals(string? text, System.StringComparison comparisonType) { throw null; }
public override int GetHashCode() { throw null; }
public int IndexOf(char c) { throw null; }
public int IndexOf(char c, int start) { throw null; }
public int IndexOf(char c, int start, int count) { throw null; }
public int IndexOfAny(char[] anyOf) { throw null; }
public int IndexOfAny(char[] anyOf, int startIndex) { throw null; }
public int IndexOfAny(char[] anyOf, int startIndex, int count) { throw null; }
public static bool IsNullOrEmpty(Microsoft.Extensions.Primitives.StringSegment value) { throw null; }
public int LastIndexOf(char value) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringSegment left, Microsoft.Extensions.Primitives.StringSegment right) { throw null; }
public static implicit operator System.ReadOnlyMemory<char>(Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
public static implicit operator System.ReadOnlySpan<char>(Microsoft.Extensions.Primitives.StringSegment segment) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringSegment(string? value) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringSegment left, Microsoft.Extensions.Primitives.StringSegment right) { throw null; }
public Microsoft.Extensions.Primitives.StringTokenizer Split(char[] chars) { throw null; }
public bool StartsWith(string text, System.StringComparison comparisonType) { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Subsegment(int offset) { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Subsegment(int offset, int length) { throw null; }
public string Substring(int offset) { throw null; }
public string Substring(int offset, int length) { throw null; }
public override string ToString() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment Trim() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment TrimEnd() { throw null; }
public Microsoft.Extensions.Primitives.StringSegment TrimStart() { throw null; }
}
public partial class StringSegmentComparer : System.Collections.Generic.IComparer<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.Generic.IEqualityComparer<Microsoft.Extensions.Primitives.StringSegment>
{
internal StringSegmentComparer() { }
public static Microsoft.Extensions.Primitives.StringSegmentComparer Ordinal { get { throw null; } }
public static Microsoft.Extensions.Primitives.StringSegmentComparer OrdinalIgnoreCase { get { throw null; } }
public int Compare(Microsoft.Extensions.Primitives.StringSegment x, Microsoft.Extensions.Primitives.StringSegment y) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringSegment x, Microsoft.Extensions.Primitives.StringSegment y) { throw null; }
public int GetHashCode(Microsoft.Extensions.Primitives.StringSegment obj) { throw null; }
}
public readonly partial struct StringTokenizer : System.Collections.Generic.IEnumerable<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.IEnumerable
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public StringTokenizer(Microsoft.Extensions.Primitives.StringSegment value, char[] separators) { throw null; }
public StringTokenizer(string value, char[] separators) { throw null; }
public Microsoft.Extensions.Primitives.StringTokenizer.Enumerator GetEnumerator() { throw null; }
System.Collections.Generic.IEnumerator<Microsoft.Extensions.Primitives.StringSegment> System.Collections.Generic.IEnumerable<Microsoft.Extensions.Primitives.StringSegment>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public partial struct Enumerator : System.Collections.Generic.IEnumerator<Microsoft.Extensions.Primitives.StringSegment>, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public Enumerator(ref Microsoft.Extensions.Primitives.StringTokenizer tokenizer) { throw null; }
public readonly Microsoft.Extensions.Primitives.StringSegment Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
public void Reset() { }
}
}
public readonly partial struct StringValues : System.Collections.Generic.ICollection<string?>, System.Collections.Generic.IEnumerable<string?>, System.Collections.Generic.IList<string?>, System.Collections.Generic.IReadOnlyCollection<string?>, System.Collections.Generic.IReadOnlyList<string?>, System.Collections.IEnumerable, System.IEquatable<Microsoft.Extensions.Primitives.StringValues>, System.IEquatable<string?>, System.IEquatable<string?[]>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public static readonly Microsoft.Extensions.Primitives.StringValues Empty;
public StringValues(string? value) { throw null; }
public StringValues(string?[]? values) { throw null; }
public int Count { get { throw null; } }
public string? this[int index] { get { throw null; } }
bool System.Collections.Generic.ICollection<System.String?>.IsReadOnly { get { throw null; } }
string? System.Collections.Generic.IList<System.String?>.this[int index] { get { throw null; } set { } }
public static Microsoft.Extensions.Primitives.StringValues Concat(Microsoft.Extensions.Primitives.StringValues values1, Microsoft.Extensions.Primitives.StringValues values2) { throw null; }
public static Microsoft.Extensions.Primitives.StringValues Concat(in Microsoft.Extensions.Primitives.StringValues values, string? value) { throw null; }
public static Microsoft.Extensions.Primitives.StringValues Concat(string? value, in Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public bool Equals(Microsoft.Extensions.Primitives.StringValues other) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool Equals(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public override bool Equals(object? obj) { throw null; }
public bool Equals(string? other) { throw null; }
public static bool Equals(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public bool Equals(string?[]? other) { throw null; }
public static bool Equals(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public Microsoft.Extensions.Primitives.StringValues.Enumerator GetEnumerator() { throw null; }
public override int GetHashCode() { throw null; }
public static bool IsNullOrEmpty(Microsoft.Extensions.Primitives.StringValues value) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, object? right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool operator ==(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public static bool operator ==(object? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator ==(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static implicit operator string?(Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public static implicit operator string?[]?(Microsoft.Extensions.Primitives.StringValues value) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringValues(string? value) { throw null; }
public static implicit operator Microsoft.Extensions.Primitives.StringValues(string?[]? values) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, object? right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, string? right) { throw null; }
public static bool operator !=(Microsoft.Extensions.Primitives.StringValues left, string?[]? right) { throw null; }
public static bool operator !=(object? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(string? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
public static bool operator !=(string?[]? left, Microsoft.Extensions.Primitives.StringValues right) { throw null; }
void System.Collections.Generic.ICollection<System.String?>.Add(string? item) { }
void System.Collections.Generic.ICollection<System.String?>.Clear() { }
bool System.Collections.Generic.ICollection<System.String?>.Contains(string? item) { throw null; }
void System.Collections.Generic.ICollection<System.String?>.CopyTo(string?[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.String?>.Remove(string? item) { throw null; }
System.Collections.Generic.IEnumerator<string?> System.Collections.Generic.IEnumerable<System.String?>.GetEnumerator() { throw null; }
int System.Collections.Generic.IList<System.String?>.IndexOf(string? item) { throw null; }
void System.Collections.Generic.IList<System.String?>.Insert(int index, string? item) { }
void System.Collections.Generic.IList<System.String?>.RemoveAt(int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public string?[] ToArray() { throw null; }
public override string ToString() { throw null; }
public partial struct Enumerator : System.Collections.Generic.IEnumerator<string?>, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public Enumerator(ref Microsoft.Extensions.Primitives.StringValues values) { throw null; }
public string? Current { get { throw null; } }
object? System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
}
| 1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.Primitives/src/StringValues.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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics.Hashing;
using System.Runtime.CompilerServices;
using System.Text;
namespace Microsoft.Extensions.Primitives
{
/// <summary>
/// Represents zero/null, one, or many strings in an efficient way.
/// </summary>
public readonly struct StringValues : IList<string?>, IReadOnlyList<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?>
{
/// <summary>
/// A readonly instance of the <see cref="StringValues"/> struct whose value is an empty string array.
/// </summary>
/// <remarks>
/// In application code, this field is most commonly used to safely represent a <see cref="StringValues"/> that has null string values.
/// </remarks>
public static readonly StringValues Empty = new StringValues(Array.Empty<string>());
private readonly object? _values;
/// <summary>
/// Initializes a new instance of the <see cref="StringValues"/> structure using the specified string.
/// </summary>
/// <param name="value">A string value or <c>null</c>.</param>
public StringValues(string? value)
{
_values = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="StringValues"/> structure using the specified array of strings.
/// </summary>
/// <param name="values">A string array.</param>
public StringValues(string?[]? values)
{
_values = values;
}
/// <summary>
/// Defines an implicit conversion of a given string to a <see cref="StringValues"/>.
/// </summary>
/// <param name="value">A string to implicitly convert.</param>
public static implicit operator StringValues(string? value)
{
return new StringValues(value);
}
/// <summary>
/// Defines an implicit conversion of a given string array to a <see cref="StringValues"/>.
/// </summary>
/// <param name="values">A string array to implicitly convert.</param>
public static implicit operator StringValues(string?[]? values)
{
return new StringValues(values);
}
/// <summary>
/// Defines an implicit conversion of a given <see cref="StringValues"/> to a string, with multiple values joined as a comma separated string.
/// </summary>
/// <remarks>
/// Returns <c>null</c> where <see cref="StringValues"/> has been initialized from an empty string array or is <see cref="StringValues.Empty"/>.
/// </remarks>
/// <param name="values">A <see cref="StringValues"/> to implicitly convert.</param>
public static implicit operator string? (StringValues values)
{
return values.GetStringValue();
}
/// <summary>
/// Defines an implicit conversion of a given <see cref="StringValues"/> to a string array.
/// </summary>
/// <param name="value">A <see cref="StringValues"/> to implicitly convert.</param>
public static implicit operator string?[]? (StringValues value)
{
return value.GetArrayValue();
}
/// <summary>
/// Gets the number of <see cref="string"/> elements contained in this <see cref="StringValues" />.
/// </summary>
public int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is null)
{
return 0;
}
if (value is string)
{
return 1;
}
else
{
// Not string, not null, can only be string[]
return Unsafe.As<string?[]>(value).Length;
}
}
}
bool ICollection<string?>.IsReadOnly => true;
/// <summary>
/// Gets the <see cref="string"/> at index.
/// </summary>
/// <value>The string at the specified index.</value>
/// <param name="index">The zero-based index of the element to get.</param>
/// <exception cref="NotSupportedException">Set operations are not supported on readonly <see cref="StringValues"/>.</exception>
string? IList<string?>.this[int index]
{
get => this[index];
set => throw new NotSupportedException();
}
/// <summary>
/// Gets the <see cref="string"/> at index.
/// </summary>
/// <value>The string at the specified index.</value>
/// <param name="index">The zero-based index of the element to get.</param>
public string? this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string str)
{
if (index == 0)
{
return str;
}
}
else if (value != null)
{
// Not string, not null, can only be string[]
return Unsafe.As<string?[]>(value)[index]; // may throw
}
return OutOfBounds(); // throws
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string OutOfBounds()
{
return Array.Empty<string>()[0]; // throws
}
/// <summary>
/// Converts the value of the current <see cref="StringValues"/> object to its equivalent string representation, with multiple values joined as a comma separated string.
/// </summary>
/// <returns>A string representation of the value of the current <see cref="StringValues"/> object.</returns>
public override string ToString()
{
return GetStringValue() ?? string.Empty;
}
private string? GetStringValue()
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string s)
{
return s;
}
else
{
return GetStringValueFromArray(value);
}
static string? GetStringValueFromArray(object? value)
{
if (value is null)
{
return null;
}
Debug.Assert(value is string[]);
// value is not null or string, array, can only be string[]
string?[] values = Unsafe.As<string?[]>(value);
return values.Length switch
{
0 => null,
1 => values[0],
_ => GetJoinedStringValueFromArray(values),
};
}
static string GetJoinedStringValueFromArray(string?[] values)
{
// Calculate final length
int length = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
// Skip null and empty values
if (value != null && value.Length > 0)
{
if (length > 0)
{
// Add separator
length++;
}
length += value.Length;
}
}
#if NETCOREAPP
// Create the new string
return string.Create(length, values, (span, strings) => {
int offset = 0;
// Skip null and empty values
for (int i = 0; i < strings.Length; i++)
{
string? value = strings[i];
if (value != null && value.Length > 0)
{
if (offset > 0)
{
// Add separator
span[offset] = ',';
offset++;
}
value.AsSpan().CopyTo(span.Slice(offset));
offset += value.Length;
}
}
});
#else
var sb = new ValueStringBuilder(length);
bool hasAdded = false;
// Skip null and empty values
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (value != null && value.Length > 0)
{
if (hasAdded)
{
// Add separator
sb.Append(',');
}
sb.Append(value);
hasAdded = true;
}
}
return sb.ToString();
#endif
}
}
/// <summary>
/// Creates a string array from the current <see cref="StringValues"/> object.
/// </summary>
/// <returns>A string array represented by this instance.</returns>
/// <remarks>
/// <para>If the <see cref="StringValues"/> contains a single string internally, it is copied to a new array.</para>
/// <para>If the <see cref="StringValues"/> contains an array internally it returns that array instance.</para>
/// </remarks>
public string?[] ToArray()
{
return GetArrayValue() ?? Array.Empty<string>();
}
private string?[]? GetArrayValue()
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
return values;
}
else if (value != null)
{
// value not array, can only be string
return new[] { Unsafe.As<string>(value) };
}
else
{
return null;
}
}
/// <summary>
/// Returns the zero-based index of the first occurrence of an item in the <see cref="StringValues" />.
/// </summary>
/// <param name="item">The string to locate in the <see cref="StringValues"></see>.</param>
/// <returns>the zero-based index of the first occurrence of <paramref name="item" /> within the <see cref="StringValues"></see>, if found; otherwise, -1.</returns>
int IList<string?>.IndexOf(string? item)
{
return IndexOf(item);
}
private int IndexOf(string? item)
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
for (int i = 0; i < values.Length; i++)
{
if (string.Equals(values[i], item, StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
if (value != null)
{
// value not array, can only be string
return string.Equals(Unsafe.As<string>(value), item, StringComparison.Ordinal) ? 0 : -1;
}
return -1;
}
/// <summary>Determines whether a string is in the <see cref="StringValues" />.</summary>
/// <param name="item">The <see cref="string"/> to locate in the <see cref="StringValues" />.</param>
/// <returns>true if <paramref name="item">item</paramref> is found in the <see cref="StringValues" />; otherwise, false.</returns>
bool ICollection<string?>.Contains(string? item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copies the entire <see cref="StringValues" />to a string array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array" /> that is the destination of the elements copied from. The <see cref="Array" /> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in the destination array at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array">array</paramref> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex">arrayIndex</paramref> is less than 0.</exception>
/// <exception cref="ArgumentException">The number of elements in the source <see cref="StringValues"></see> is greater than the available space from <paramref name="arrayIndex">arrayIndex</paramref> to the end of the destination <paramref name="array">array</paramref>.</exception>
void ICollection<string?>.CopyTo(string?[] array, int arrayIndex)
{
CopyTo(array, arrayIndex);
}
private void CopyTo(string?[] array, int arrayIndex)
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
Array.Copy(values, 0, array, arrayIndex, values.Length);
return;
}
if (value != null)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
if (array.Length - arrayIndex < 1)
{
throw new ArgumentException(
$"'{nameof(array)}' is not long enough to copy all the items in the collection. Check '{nameof(arrayIndex)}' and '{nameof(array)}' length.");
}
// value not array, can only be string
array[arrayIndex] = Unsafe.As<string>(value);
}
}
void ICollection<string?>.Add(string? item) => throw new NotSupportedException();
void IList<string?>.Insert(int index, string? item) => throw new NotSupportedException();
bool ICollection<string?>.Remove(string? item) => throw new NotSupportedException();
void IList<string?>.RemoveAt(int index) => throw new NotSupportedException();
void ICollection<string?>.Clear() => throw new NotSupportedException();
/// <summary>Retrieves an object that can iterate through the individual strings in this <see cref="StringValues" />.</summary>
/// <returns>An enumerator that can be used to iterate through the <see cref="StringValues" />.</returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_values);
}
/// <inheritdoc cref="GetEnumerator()" />
IEnumerator<string?> IEnumerable<string?>.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc cref="GetEnumerator()" />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Indicates whether the specified <see cref="StringValues"/> contains no string values.
/// </summary>
/// <param name="value">The <see cref="StringValues"/> to test.</param>
/// <returns>true if <paramref name="value">value</paramref> contains a single null or empty string or an empty array; otherwise, false.</returns>
public static bool IsNullOrEmpty(StringValues value)
{
object? data = value._values;
if (data is null)
{
return true;
}
if (data is string[] values)
{
return values.Length switch
{
0 => true,
1 => string.IsNullOrEmpty(values[0]),
_ => false,
};
}
else
{
// Not array, can only be string
return string.IsNullOrEmpty(Unsafe.As<string>(data));
}
}
/// <summary>
/// Concatenates two specified instances of <see cref="StringValues"/>.
/// </summary>
/// <param name="values1">The first <see cref="StringValues"/> to concatenate.</param>
/// <param name="values2">The second <see cref="StringValues"/> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values1"/> and <paramref name="values2"/>.</returns>
public static StringValues Concat(StringValues values1, StringValues values2)
{
int count1 = values1.Count;
int count2 = values2.Count;
if (count1 == 0)
{
return values2;
}
if (count2 == 0)
{
return values1;
}
var combined = new string[count1 + count2];
values1.CopyTo(combined, 0);
values2.CopyTo(combined, count1);
return new StringValues(combined);
}
/// <summary>
/// Concatenates specified instance of <see cref="StringValues"/> with specified <see cref="string"/>.
/// </summary>
/// <param name="values">The <see cref="StringValues"/> to concatenate.</param>
/// <param name="value">The <see cref="string" /> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values"/> and <paramref name="value"/>.</returns>
public static StringValues Concat(in StringValues values, string? value)
{
if (value == null)
{
return values;
}
int count = values.Count;
if (count == 0)
{
return new StringValues(value);
}
var combined = new string[count + 1];
values.CopyTo(combined, 0);
combined[count] = value;
return new StringValues(combined);
}
/// <summary>
/// Concatenates specified instance of <see cref="string"/> with specified <see cref="StringValues"/>.
/// </summary>
/// <param name="value">The <see cref="string" /> to concatenate.</param>
/// <param name="values">The <see cref="StringValues"/> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values"/> and <paramref name="values"/>.</returns>
public static StringValues Concat(string? value, in StringValues values)
{
if (value == null)
{
return values;
}
int count = values.Count;
if (count == 0)
{
return new StringValues(value);
}
var combined = new string[count + 1];
combined[0] = value;
values.CopyTo(combined, 1);
return new StringValues(combined);
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> objects have the same values in the same order.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(StringValues left, StringValues right)
{
int count = left.Count;
if (count != right.Count)
{
return false;
}
for (int i = 0; i < count; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> have the same values.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(StringValues left, StringValues right)
{
return Equals(left, right);
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> have different values.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, StringValues right)
{
return !Equals(left, right);
}
/// <summary>
/// Determines whether this instance and another specified <see cref="StringValues"/> object have the same values.
/// </summary>
/// <param name="other">The string to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as the value of this instance; otherwise, <c>false</c>.</returns>
public bool Equals(StringValues other) => Equals(this, other);
/// <summary>
/// Determines whether the specified <see cref="string"/> and <see cref="StringValues"/> objects have the same values.
/// </summary>
/// <param name="left">The <see cref="string"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>. If <paramref name="left"/> is <c>null</c>, the method returns <c>false</c>.</returns>
public static bool Equals(string? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="string"/> objects have the same values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="string"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>. If <paramref name="right"/> is <c>null</c>, the method returns <c>false</c>.</returns>
public static bool Equals(StringValues left, string? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether this instance and a specified <see cref="string"/>, have the same value.
/// </summary>
/// <param name="other">The <see cref="string"/> to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as this instance; otherwise, <c>false</c>. If <paramref name="other"/> is <c>null</c>, returns <c>false</c>.</returns>
public bool Equals(string? other) => Equals(this, new StringValues(other));
/// <summary>
/// Determines whether the specified string array and <see cref="StringValues"/> objects have the same values.
/// </summary>
/// <param name="left">The string array to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(string?[]? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and string array objects have the same values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The string array to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(StringValues left, string?[]? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether this instance and a specified string array have the same values.
/// </summary>
/// <param name="other">The string array to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as this instance; otherwise, <c>false</c>.</returns>
public bool Equals(string?[]? other) => Equals(this, new StringValues(other));
/// <inheritdoc cref="Equals(StringValues, string)" />
public static bool operator ==(StringValues left, string? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="string"/> objects have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="string"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, string? right) => !Equals(left, new StringValues(right));
/// <inheritdoc cref="Equals(string, StringValues)" />
public static bool operator ==(string? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="string"/> and <see cref="StringValues"/> objects have different values.
/// </summary>
/// <param name="left">The <see cref="string"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(string left, StringValues right) => !Equals(new StringValues(left), right);
/// <inheritdoc cref="Equals(StringValues, string[])" />
public static bool operator ==(StringValues left, string?[]? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and string array have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The string array to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, string?[]? right) => !Equals(left, new StringValues(right));
/// <inheritdoc cref="Equals(string[], StringValues)" />
public static bool operator ==(string?[]? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified string array and <see cref="StringValues"/> have different values.
/// </summary>
/// <param name="left">The string array to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(string?[]? left, StringValues right) => !Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, have the same value.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(StringValues left, object? right) => left.Equals(right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, object? right) => !left.Equals(right);
/// <summary>
/// Determines whether the specified <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, and specified <see cref="StringValues"/>, have the same value.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(object? left, StringValues right) => right.Equals(left);
/// <summary>
/// Determines whether the specified <see cref="object"/> and <see cref="StringValues"/> object have the same values.
/// </summary>
/// <param name="left">The <see cref="object"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(object? left, StringValues right) => !right.Equals(left);
/// <summary>
/// Determines whether this instance and a specified object have the same value.
/// </summary>
/// <param name="obj">An object to compare with this object.</param>
/// <returns><c>true</c> if the current object is equal to <paramref name="obj"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object? obj)
{
if (obj == null)
{
return Equals(this, StringValues.Empty);
}
if (obj is string str)
{
return Equals(this, str);
}
if (obj is string[] array)
{
return Equals(this, array);
}
if (obj is StringValues stringValues)
{
return Equals(this, stringValues);
}
return false;
}
/// <inheritdoc />
public override int GetHashCode()
{
object? value = _values;
if (value is string[] values)
{
if (Count == 1)
{
return Unsafe.As<string>(this[0])?.GetHashCode() ?? Count.GetHashCode();
}
int hashCode = 0;
for (int i = 0; i < values.Length; i++)
{
hashCode = HashHelpers.Combine(hashCode, values[i]?.GetHashCode() ?? 0);
}
return hashCode;
}
else
{
return Unsafe.As<string>(value)?.GetHashCode() ?? Count.GetHashCode();
}
}
/// <summary>
/// Enumerates the string values of a <see cref="StringValues" />.
/// </summary>
public struct Enumerator : IEnumerator<string?>
{
private readonly string?[]? _values;
private int _index;
private string? _current;
internal Enumerator(object? value)
{
if (value is string str)
{
_values = null;
_current = str;
}
else
{
_current = null;
_values = Unsafe.As<string?[]>(value);
}
_index = 0;
}
public Enumerator(ref StringValues values) : this(values._values)
{ }
public bool MoveNext()
{
int index = _index;
if (index < 0)
{
return false;
}
string?[]? values = _values;
if (values != null)
{
if ((uint)index < (uint)values.Length)
{
_index = index + 1;
_current = values[index];
return true;
}
_index = -1;
return false;
}
_index = -1; // sentinel value
return _current != null;
}
public string? Current => _current;
object? IEnumerator.Current => _current;
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
}
}
| // 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics.Hashing;
using System.Runtime.CompilerServices;
using System.Text;
namespace Microsoft.Extensions.Primitives
{
/// <summary>
/// Represents zero/null, one, or many strings in an efficient way.
/// </summary>
public readonly struct StringValues : IList<string?>, IReadOnlyList<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?>
{
/// <summary>
/// A readonly instance of the <see cref="StringValues"/> struct whose value is an empty string array.
/// </summary>
/// <remarks>
/// In application code, this field is most commonly used to safely represent a <see cref="StringValues"/> that has null string values.
/// </remarks>
public static readonly StringValues Empty = new StringValues(Array.Empty<string>());
private readonly object? _values;
/// <summary>
/// Initializes a new instance of the <see cref="StringValues"/> structure using the specified string.
/// </summary>
/// <param name="value">A string value or <c>null</c>.</param>
public StringValues(string? value)
{
_values = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="StringValues"/> structure using the specified array of strings.
/// </summary>
/// <param name="values">A string array.</param>
public StringValues(string?[]? values)
{
_values = values;
}
/// <summary>
/// Defines an implicit conversion of a given string to a <see cref="StringValues"/>.
/// </summary>
/// <param name="value">A string to implicitly convert.</param>
public static implicit operator StringValues(string? value)
{
return new StringValues(value);
}
/// <summary>
/// Defines an implicit conversion of a given string array to a <see cref="StringValues"/>.
/// </summary>
/// <param name="values">A string array to implicitly convert.</param>
public static implicit operator StringValues(string?[]? values)
{
return new StringValues(values);
}
/// <summary>
/// Defines an implicit conversion of a given <see cref="StringValues"/> to a string, with multiple values joined as a comma separated string.
/// </summary>
/// <remarks>
/// Returns <c>null</c> where <see cref="StringValues"/> has been initialized from an empty string array or is <see cref="StringValues.Empty"/>.
/// </remarks>
/// <param name="values">A <see cref="StringValues"/> to implicitly convert.</param>
public static implicit operator string? (StringValues values)
{
return values.GetStringValue();
}
/// <summary>
/// Defines an implicit conversion of a given <see cref="StringValues"/> to a string array.
/// </summary>
/// <param name="value">A <see cref="StringValues"/> to implicitly convert.</param>
public static implicit operator string?[]? (StringValues value)
{
return value.GetArrayValue();
}
/// <summary>
/// Gets the number of <see cref="string"/> elements contained in this <see cref="StringValues" />.
/// </summary>
public int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is null)
{
return 0;
}
if (value is string)
{
return 1;
}
else
{
// Not string, not null, can only be string[]
return Unsafe.As<string?[]>(value).Length;
}
}
}
bool ICollection<string?>.IsReadOnly => true;
/// <summary>
/// Gets the <see cref="string"/> at index.
/// </summary>
/// <value>The string at the specified index.</value>
/// <param name="index">The zero-based index of the element to get.</param>
/// <exception cref="NotSupportedException">Set operations are not supported on readonly <see cref="StringValues"/>.</exception>
string? IList<string?>.this[int index]
{
get => this[index];
set => throw new NotSupportedException();
}
/// <summary>
/// Gets the <see cref="string"/> at index.
/// </summary>
/// <value>The string at the specified index.</value>
/// <param name="index">The zero-based index of the element to get.</param>
public string? this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string str)
{
if (index == 0)
{
return str;
}
}
else if (value != null)
{
// Not string, not null, can only be string[]
return Unsafe.As<string?[]>(value)[index]; // may throw
}
return OutOfBounds(); // throws
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string OutOfBounds()
{
return Array.Empty<string>()[0]; // throws
}
/// <summary>
/// Converts the value of the current <see cref="StringValues"/> object to its equivalent string representation, with multiple values joined as a comma separated string.
/// </summary>
/// <returns>A string representation of the value of the current <see cref="StringValues"/> object.</returns>
public override string ToString()
{
return GetStringValue() ?? string.Empty;
}
private string? GetStringValue()
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string s)
{
return s;
}
else
{
return GetStringValueFromArray(value);
}
static string? GetStringValueFromArray(object? value)
{
if (value is null)
{
return null;
}
Debug.Assert(value is string[]);
// value is not null or string, array, can only be string[]
string?[] values = Unsafe.As<string?[]>(value);
return values.Length switch
{
0 => null,
1 => values[0],
_ => GetJoinedStringValueFromArray(values),
};
}
static string GetJoinedStringValueFromArray(string?[] values)
{
// Calculate final length
int length = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
// Skip null and empty values
if (value != null && value.Length > 0)
{
if (length > 0)
{
// Add separator
length++;
}
length += value.Length;
}
}
#if NETCOREAPP
// Create the new string
return string.Create(length, values, (span, strings) => {
int offset = 0;
// Skip null and empty values
for (int i = 0; i < strings.Length; i++)
{
string? value = strings[i];
if (value != null && value.Length > 0)
{
if (offset > 0)
{
// Add separator
span[offset] = ',';
offset++;
}
value.AsSpan().CopyTo(span.Slice(offset));
offset += value.Length;
}
}
});
#else
var sb = new ValueStringBuilder(length);
bool hasAdded = false;
// Skip null and empty values
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (value != null && value.Length > 0)
{
if (hasAdded)
{
// Add separator
sb.Append(',');
}
sb.Append(value);
hasAdded = true;
}
}
return sb.ToString();
#endif
}
}
/// <summary>
/// Creates a string array from the current <see cref="StringValues"/> object.
/// </summary>
/// <returns>A string array represented by this instance.</returns>
/// <remarks>
/// <para>If the <see cref="StringValues"/> contains a single string internally, it is copied to a new array.</para>
/// <para>If the <see cref="StringValues"/> contains an array internally it returns that array instance.</para>
/// </remarks>
public string?[] ToArray()
{
return GetArrayValue() ?? Array.Empty<string>();
}
private string?[]? GetArrayValue()
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
return values;
}
else if (value != null)
{
// value not array, can only be string
return new[] { Unsafe.As<string>(value) };
}
else
{
return null;
}
}
/// <summary>
/// Returns the zero-based index of the first occurrence of an item in the <see cref="StringValues" />.
/// </summary>
/// <param name="item">The string to locate in the <see cref="StringValues"></see>.</param>
/// <returns>the zero-based index of the first occurrence of <paramref name="item" /> within the <see cref="StringValues"></see>, if found; otherwise, -1.</returns>
int IList<string?>.IndexOf(string? item)
{
return IndexOf(item);
}
private int IndexOf(string? item)
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
for (int i = 0; i < values.Length; i++)
{
if (string.Equals(values[i], item, StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
if (value != null)
{
// value not array, can only be string
return string.Equals(Unsafe.As<string>(value), item, StringComparison.Ordinal) ? 0 : -1;
}
return -1;
}
/// <summary>Determines whether a string is in the <see cref="StringValues" />.</summary>
/// <param name="item">The <see cref="string"/> to locate in the <see cref="StringValues" />.</param>
/// <returns>true if <paramref name="item">item</paramref> is found in the <see cref="StringValues" />; otherwise, false.</returns>
bool ICollection<string?>.Contains(string? item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copies the entire <see cref="StringValues" />to a string array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array" /> that is the destination of the elements copied from. The <see cref="Array" /> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in the destination array at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array">array</paramref> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex">arrayIndex</paramref> is less than 0.</exception>
/// <exception cref="ArgumentException">The number of elements in the source <see cref="StringValues"></see> is greater than the available space from <paramref name="arrayIndex">arrayIndex</paramref> to the end of the destination <paramref name="array">array</paramref>.</exception>
void ICollection<string?>.CopyTo(string?[] array, int arrayIndex)
{
CopyTo(array, arrayIndex);
}
private void CopyTo(string?[] array, int arrayIndex)
{
// Take local copy of _values so type checks remain valid even if the StringValues is overwritten in memory
object? value = _values;
if (value is string[] values)
{
Array.Copy(values, 0, array, arrayIndex, values.Length);
return;
}
if (value != null)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
if (array.Length - arrayIndex < 1)
{
throw new ArgumentException(
$"'{nameof(array)}' is not long enough to copy all the items in the collection. Check '{nameof(arrayIndex)}' and '{nameof(array)}' length.");
}
// value not array, can only be string
array[arrayIndex] = Unsafe.As<string>(value);
}
}
void ICollection<string?>.Add(string? item) => throw new NotSupportedException();
void IList<string?>.Insert(int index, string? item) => throw new NotSupportedException();
bool ICollection<string?>.Remove(string? item) => throw new NotSupportedException();
void IList<string?>.RemoveAt(int index) => throw new NotSupportedException();
void ICollection<string?>.Clear() => throw new NotSupportedException();
/// <summary>Retrieves an object that can iterate through the individual strings in this <see cref="StringValues" />.</summary>
/// <returns>An enumerator that can be used to iterate through the <see cref="StringValues" />.</returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_values);
}
/// <inheritdoc cref="GetEnumerator()" />
IEnumerator<string?> IEnumerable<string?>.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc cref="GetEnumerator()" />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Indicates whether the specified <see cref="StringValues"/> contains no string values.
/// </summary>
/// <param name="value">The <see cref="StringValues"/> to test.</param>
/// <returns>true if <paramref name="value">value</paramref> contains a single null or empty string or an empty array; otherwise, false.</returns>
public static bool IsNullOrEmpty(StringValues value)
{
object? data = value._values;
if (data is null)
{
return true;
}
if (data is string[] values)
{
return values.Length switch
{
0 => true,
1 => string.IsNullOrEmpty(values[0]),
_ => false,
};
}
else
{
// Not array, can only be string
return string.IsNullOrEmpty(Unsafe.As<string>(data));
}
}
/// <summary>
/// Concatenates two specified instances of <see cref="StringValues"/>.
/// </summary>
/// <param name="values1">The first <see cref="StringValues"/> to concatenate.</param>
/// <param name="values2">The second <see cref="StringValues"/> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values1"/> and <paramref name="values2"/>.</returns>
public static StringValues Concat(StringValues values1, StringValues values2)
{
int count1 = values1.Count;
int count2 = values2.Count;
if (count1 == 0)
{
return values2;
}
if (count2 == 0)
{
return values1;
}
var combined = new string[count1 + count2];
values1.CopyTo(combined, 0);
values2.CopyTo(combined, count1);
return new StringValues(combined);
}
/// <summary>
/// Concatenates specified instance of <see cref="StringValues"/> with specified <see cref="string"/>.
/// </summary>
/// <param name="values">The <see cref="StringValues"/> to concatenate.</param>
/// <param name="value">The <see cref="string" /> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values"/> and <paramref name="value"/>.</returns>
public static StringValues Concat(in StringValues values, string? value)
{
if (value == null)
{
return values;
}
int count = values.Count;
if (count == 0)
{
return new StringValues(value);
}
var combined = new string[count + 1];
values.CopyTo(combined, 0);
combined[count] = value;
return new StringValues(combined);
}
/// <summary>
/// Concatenates specified instance of <see cref="string"/> with specified <see cref="StringValues"/>.
/// </summary>
/// <param name="value">The <see cref="string" /> to concatenate.</param>
/// <param name="values">The <see cref="StringValues"/> to concatenate.</param>
/// <returns>The concatenation of <paramref name="values"/> and <paramref name="values"/>.</returns>
public static StringValues Concat(string? value, in StringValues values)
{
if (value == null)
{
return values;
}
int count = values.Count;
if (count == 0)
{
return new StringValues(value);
}
var combined = new string[count + 1];
combined[0] = value;
values.CopyTo(combined, 1);
return new StringValues(combined);
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> objects have the same values in the same order.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(StringValues left, StringValues right)
{
int count = left.Count;
if (count != right.Count)
{
return false;
}
for (int i = 0; i < count; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> have the same values.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(StringValues left, StringValues right)
{
return Equals(left, right);
}
/// <summary>
/// Determines whether two specified <see cref="StringValues"/> have different values.
/// </summary>
/// <param name="left">The first <see cref="StringValues"/> to compare.</param>
/// <param name="right">The second <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, StringValues right)
{
return !Equals(left, right);
}
/// <summary>
/// Determines whether this instance and another specified <see cref="StringValues"/> object have the same values.
/// </summary>
/// <param name="other">The string to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as the value of this instance; otherwise, <c>false</c>.</returns>
public bool Equals(StringValues other) => Equals(this, other);
/// <summary>
/// Determines whether the specified <see cref="string"/> and <see cref="StringValues"/> objects have the same values.
/// </summary>
/// <param name="left">The <see cref="string"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>. If <paramref name="left"/> is <c>null</c>, the method returns <c>false</c>.</returns>
public static bool Equals(string? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="string"/> objects have the same values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="string"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>. If <paramref name="right"/> is <c>null</c>, the method returns <c>false</c>.</returns>
public static bool Equals(StringValues left, string? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether this instance and a specified <see cref="string"/>, have the same value.
/// </summary>
/// <param name="other">The <see cref="string"/> to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as this instance; otherwise, <c>false</c>. If <paramref name="other"/> is <c>null</c>, returns <c>false</c>.</returns>
public bool Equals(string? other) => Equals(this, new StringValues(other));
/// <summary>
/// Determines whether the specified string array and <see cref="StringValues"/> objects have the same values.
/// </summary>
/// <param name="left">The string array to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(string?[]? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and string array objects have the same values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The string array to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is the same as the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool Equals(StringValues left, string?[]? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether this instance and a specified string array have the same values.
/// </summary>
/// <param name="other">The string array to compare to this instance.</param>
/// <returns><c>true</c> if the value of <paramref name="other"/> is the same as this instance; otherwise, <c>false</c>.</returns>
public bool Equals(string?[]? other) => Equals(this, new StringValues(other));
/// <inheritdoc cref="Equals(StringValues, string)" />
public static bool operator ==(StringValues left, string? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="string"/> objects have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="string"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, string? right) => !Equals(left, new StringValues(right));
/// <inheritdoc cref="Equals(string, StringValues)" />
public static bool operator ==(string? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="string"/> and <see cref="StringValues"/> objects have different values.
/// </summary>
/// <param name="left">The <see cref="string"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(string? left, StringValues right) => !Equals(new StringValues(left), right);
/// <inheritdoc cref="Equals(StringValues, string[])" />
public static bool operator ==(StringValues left, string?[]? right) => Equals(left, new StringValues(right));
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and string array have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The string array to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, string?[]? right) => !Equals(left, new StringValues(right));
/// <inheritdoc cref="Equals(string[], StringValues)" />
public static bool operator ==(string?[]? left, StringValues right) => Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified string array and <see cref="StringValues"/> have different values.
/// </summary>
/// <param name="left">The string array to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the value of <paramref name="left"/> is different to the value of <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(string?[]? left, StringValues right) => !Equals(new StringValues(left), right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, have the same value.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(StringValues left, object? right) => left.Equals(right);
/// <summary>
/// Determines whether the specified <see cref="StringValues"/> and <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, have different values.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(StringValues left, object? right) => !left.Equals(right);
/// <summary>
/// Determines whether the specified <see cref="object"/>, which must be a
/// <see cref="StringValues"/>, <see cref="string"/>, or array of <see cref="string"/>, and specified <see cref="StringValues"/>, have the same value.
/// </summary>
/// <param name="left">The <see cref="StringValues"/> to compare.</param>
/// <param name="right">The <see cref="object"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator ==(object? left, StringValues right) => right.Equals(left);
/// <summary>
/// Determines whether the specified <see cref="object"/> and <see cref="StringValues"/> object have the same values.
/// </summary>
/// <param name="left">The <see cref="object"/> to compare.</param>
/// <param name="right">The <see cref="StringValues"/> to compare.</param>
/// <returns><c>true</c> if the <paramref name="left"/> object is equal to the <paramref name="right"/>; otherwise, <c>false</c>.</returns>
public static bool operator !=(object? left, StringValues right) => !right.Equals(left);
/// <summary>
/// Determines whether this instance and a specified object have the same value.
/// </summary>
/// <param name="obj">An object to compare with this object.</param>
/// <returns><c>true</c> if the current object is equal to <paramref name="obj"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object? obj)
{
if (obj == null)
{
return Equals(this, StringValues.Empty);
}
if (obj is string str)
{
return Equals(this, str);
}
if (obj is string[] array)
{
return Equals(this, array);
}
if (obj is StringValues stringValues)
{
return Equals(this, stringValues);
}
return false;
}
/// <inheritdoc />
public override int GetHashCode()
{
object? value = _values;
if (value is string[] values)
{
if (Count == 1)
{
return Unsafe.As<string>(this[0])?.GetHashCode() ?? Count.GetHashCode();
}
int hashCode = 0;
for (int i = 0; i < values.Length; i++)
{
hashCode = HashHelpers.Combine(hashCode, values[i]?.GetHashCode() ?? 0);
}
return hashCode;
}
else
{
return Unsafe.As<string>(value)?.GetHashCode() ?? Count.GetHashCode();
}
}
/// <summary>
/// Enumerates the string values of a <see cref="StringValues" />.
/// </summary>
public struct Enumerator : IEnumerator<string?>
{
private readonly string?[]? _values;
private int _index;
private string? _current;
internal Enumerator(object? value)
{
if (value is string str)
{
_values = null;
_current = str;
}
else
{
_current = null;
_values = Unsafe.As<string?[]>(value);
}
_index = 0;
}
public Enumerator(ref StringValues values) : this(values._values)
{ }
public bool MoveNext()
{
int index = _index;
if (index < 0)
{
return false;
}
string?[]? values = _values;
if (values != null)
{
if ((uint)index < (uint)values.Length)
{
_index = index + 1;
_current = values[index];
return true;
}
_index = -1;
return false;
}
_index = -1; // sentinel value
return _current != null;
}
public string? Current => _current;
object? IEnumerator.Current => _current;
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
}
}
| 1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/Loader/classloader/regressions/dev10_851479/dev10_851479.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;
/// <summary>
/// Regression test case for Dev10 851479 bug: Stackoverflow in .NET when using self referencing generics along with type constraints to another type parameter.
/// </summary>
class Program
{
static Int32 Main()
{
Program p = new Program();
if (p.Run())
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return -1;
}
}
public Boolean Run()
{
try
{
var B = new B();
System.Console.WriteLine(B);
}
catch (Exception ex)
{
Console.WriteLine("Got unexpected error: " + ex);
return false;
}
return true;
}
}
class A<T, U>
where T : U
where U : A<T, U> { }
class B : A<B, B>
{
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
/// <summary>
/// Regression test case for Dev10 851479 bug: Stackoverflow in .NET when using self referencing generics along with type constraints to another type parameter.
/// </summary>
class Program
{
static Int32 Main()
{
Program p = new Program();
if (p.Run())
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return -1;
}
}
public Boolean Run()
{
try
{
var B = new B();
System.Console.WriteLine(B);
}
catch (Exception ex)
{
Console.WriteLine("Got unexpected error: " + ex);
return false;
}
return true;
}
}
class A<T, U>
where T : U
where U : A<T, U> { }
class B : A<B, B>
{
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Net.Security/tests/FunctionalTests/TlsFrameHelperTests.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.Linq;
using System.Security.Authentication;
using Xunit;
namespace System.Net.Security.Tests
{
public class TlsFrameHelperTests
{
[Fact]
public void SniHelper_ValidData_Ok()
{
InvalidClientHello(s_validClientHello, -1, shouldPass: true);
}
[Theory]
[MemberData(nameof(InvalidClientHelloData))]
public void SniHelper_InvalidData_Fails(int id, byte[] clientHello)
{
InvalidClientHello(clientHello, id, shouldPass: false);
}
[Theory]
[MemberData(nameof(InvalidClientHelloDataTruncatedBytes))]
public void SniHelper_TruncatedData_Fails(int id, byte[] clientHello)
{
InvalidClientHello(clientHello, id, shouldPass: false);
}
private void InvalidClientHello(byte[] clientHello, int id, bool shouldPass)
{
string ret = TlsFrameHelper.GetServerName(clientHello);
if (shouldPass)
Assert.NotNull(ret);
else
Assert.Null(ret);
}
[Fact]
public void TlsFrameHelper_ValidData_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_validClientHello, ref info));
Assert.Equal(SslProtocols.Tls12, info.Header.Version);
Assert.Equal(203, info.Header.Length);
Assert.Equal(SslProtocols.Tls12, info.SupportedVersions);
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.None, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls12ClientHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls12ClientHello, ref info));
#pragma warning disable SYSLIB0039
Assert.Equal(SslProtocols.Tls, info.Header.Version);
Assert.Equal(SslProtocols.Tls | SslProtocols.Tls12, info.SupportedVersions);
#pragma warning restore SYSLIB0039
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Http11 | TlsFrameHelper.ApplicationProtocolInfo.Http2, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls13ClientHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls13ClientHello, ref info));
#pragma warning disable SYSLIB0039
Assert.Equal(SslProtocols.Tls, info.Header.Version);
Assert.Equal(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13, info.SupportedVersions);
#pragma warning restore SYSLIB0039
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Other, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls12ServerHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls12ServerHello, ref info));
Assert.Equal(SslProtocols.Tls12, info.Header.Version);
Assert.Equal(SslProtocols.Tls12, info.SupportedVersions);
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Http2, info.ApplicationProtocols);
}
public static IEnumerable<object[]> InvalidClientHelloData()
{
int id = 0;
foreach (byte[] invalidClientHello in InvalidClientHello())
{
id++;
yield return new object[] { id, invalidClientHello };
}
}
public static IEnumerable<object[]> InvalidClientHelloDataTruncatedBytes()
{
// converting to base64 first to remove duplicated test cases
var uniqueInvalidHellos = new HashSet<string>();
foreach (byte[] invalidClientHello in InvalidClientHello())
{
for (int i = 0; i < invalidClientHello.Length; i++)
{
uniqueInvalidHellos.Add(Convert.ToBase64String(invalidClientHello.Take(i).ToArray()));
}
}
for (int i = 0; i < s_validClientHello.Length; i++)
{
uniqueInvalidHellos.Add(Convert.ToBase64String(s_validClientHello.Take(i).ToArray()));
}
int id = 0;
foreach (string invalidClientHello in uniqueInvalidHellos)
{
id++;
yield return new object[] { id, Convert.FromBase64String(invalidClientHello) };
}
}
private static byte[] s_validClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
private static byte[] s_Tls12ClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x01,
// SslPlainText.length
0x00, 0xD1,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xCD,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites_length
0x00, 0x5C,
// ClientHello.cipher_suites
0xC0, 0x30, 0xC0, 0x2C, 0xC0, 0x28, 0xC0, 0x24,
0xC0, 0x14, 0xC0, 0x0A, 0x00, 0x9f, 0x00, 0x6B,
0x00, 0x39, 0xCC, 0xA9, 0xCC, 0xA8, 0xCC, 0xAA,
0xFF, 0x85, 0x00, 0xC4, 0x00, 0x88, 0x00, 0x81,
0x00, 0x9D, 0x00, 0x3D, 0x00, 0x35, 0x00, 0xC0,
0x00, 0x84, 0xC0, 0x2f, 0xC0, 0x2B, 0xC0, 0x27,
0xC0, 0x23, 0xC0, 0x13, 0xC0, 0x09, 0x00, 0x9E,
0x00, 0x67, 0x00, 0x33, 0x00, 0xBE, 0x00, 0x45,
0x00, 0x9C, 0x00, 0x3C, 0x00, 0x2F, 0x00, 0xBA,
0x00, 0x41, 0xC0, 0x11, 0xC0, 0x07, 0x00, 0x05,
0x00, 0x04, 0xC0, 0x12, 0xC0, 0x08, 0x00, 0x16,
0x00, 0x0a, 0x00, 0xff,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x48,
// Extension.extension_type (ec_point_formats)
0x00, 0x0b, 0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (supported_groups)
0x00, 0x0A, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1D,
0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (session_ticket)
0x00, 0x23, 0x00, 0x00,
// Extension.extension_type (signature_algorithms)
0x00, 0x0D, 0x00, 0x1C, 0x00, 0x1A, 0x06, 0x01,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
// Extension.extension_type (application_level_Protocol)
0x00, 0x10, 0x00, 0x0e, 0x00, 0x0C, 0x02, 0x68,
0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2F, 0x31,
0x2E, 0x31
};
private static byte[] s_Tls13ClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x01,
// SslPlainText.length
0x01, 0x08,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x01, 0x04,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ClientHello.SessionId_Length
0x20,
// ClientHello.SessionId
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ClientHello.cipher_suites_length
0x00, 0x0C,
// ClientHello.cipher_suites
0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0xC0, 0x14,
0xc0, 0x30, 0x00, 0xFF,
// ClientHello.compression_methods
0x01, 0x00,
// ClientHello.extension_list_length
0x00, 0xAF,
// Extension.extension_type (server_name) (10.211.55.2)
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00,
0x0B, 0x31, 0x30, 0x2E, 0x32, 0x31, 0x31, 0x2E,
0x35, 0x35, 0x2E, 0x32,
// Extension.extension_type (ec_point_formats)
0x00, 0x0B, 0x00, 0x04, 0x03, 0x00, 0x01, 0x02,
// Extension.extension_type (supported_groups)
0x00, 0x0A, 0x00, 0x0C, 0x00, 0x0A, 0x00, 0x1D,
0x00, 0x17, 0x00, 0x1E, 0x00, 0x19, 0x00, 0x18,
// Extension.extension_type (application_level_Protocol) (boo)
0x00, 0x10, 0x00, 0x06, 0x00, 0x04, 0x03, 0x62,
0x6f, 0x6f,
// Extension.extension_type (encrypt_then_mac)
0x00, 0x16, 0x00, 0x00,
// Extension.extension_type (extended_master_key_secret)
0x00, 0x17, 0x00, 0x00,
// Extension.extension_type (signature_algorithms)
0x00, 0x0D, 0x00, 0x30, 0x00, 0x2E,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01,
// Extension.extension_type (supported_versions)
0x00, 0x2B, 0x00, 0x09, 0x08, 0x03, 0x04, 0x03,
0x03, 0x03, 0x02, 0x03, 0x01,
// Extension.extension_type (psk_key_exchange_modes)
0x00, 0x2D, 0x00, 0x02, 0x01, 0x01,
// Extension.extension_type (key_share)
0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1D,
0x00, 0x20,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03
};
private static byte[] s_Tls12ServerHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0x64,
// Handshake.msg_type (srever hello)
0x02,
// Handshake.length
0x00, 0x00, 0x60,
// ServerHello.client_version
0x03, 0x03,
// ServerHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ServerHello.SessionId_Length
0x20,
// ServerHello.SessionId
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ServerHello.cipher_suite
0xC0, 0x2B,
// ServerHello.compression_method
0x00,
// ClientHello.extension_list_length
0x00, 0x18,
// Extension.extension_type (extended_master_secreet)
0x00, 0x17, 0x00, 0x00,
// Extension.extension_type (renegotiation_info)
0xFF, 0x01, 0x00, 0x01, 0x00,
// Extension.extension_type (ec_point_formats)
0x00, 0x0B, 0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (application_level_Protocol)
0x00, 0x10, 0x00, 0x05, 0x00, 0x03, 0x02, 0x68, 0x32,
};
private static IEnumerable<byte[]> InvalidClientHello()
{
// This test covers following test cases:
// - Length of structure off by 1 (search for "length off by 1")
// - Length of structure is max length (search for "max length")
// - Type is invalid or unknown (i.e. SslPlainText.ClientType is not 0x16 - search for "unknown")
// - Invalid utf-8 characters
// in each case sni will be null or will cause parsing error - we only expect some parsing errors,
// anything else is considered a bug
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01 - length off by 1
0x00, 0x02, 0x00
};
// #2
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01 - max length
0xFF, 0xFF, 0x00
};
// #3
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17 - length off by 1
0x00, 0x01,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #4
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17 - max length
0xFF, 0xFF,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #5
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23 - length off by 1
0x00, 0x01,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #6
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23 - max length
0xFF, 0xFF,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #7
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D - length off by 1
0x00, 0x15, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #8
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D - max length
0xFF, 0xFF, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #9
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B - length off by 1
0x00, 0x03, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #10
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B - max length
0xFF, 0xFF, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #11
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A - length off by 1
0x00, 0x09, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #10
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A - max length
0xFF, 0xFF, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #13
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length - length off by 1
0x00, 0x35,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #14
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length - max length
0xFF, 0xFF,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #15
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type - unknown
0x01,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #16
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length - length off by 1
0x00, 0x38,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #17
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length - max length
0xFF, 0xFF,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #18
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length - length off by 1
0x00, 0x3A,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #19
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length - max length
0xFF, 0xFF,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #20
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name) - unknown
0x01, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #21
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length - length off by 1
0x00, 0x75,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #22
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length - max length
0xFF, 0xFF,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #23
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods - length off by 1
0x02, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #24
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods - max length
0xFF, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #25
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites - length off by 1
0x00, 0x2B, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #26
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites - max length
0xFF, 0xFF, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #27
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId - length off by 1
0x01,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #28
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId - max length
0xFF,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #29
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length - length off by 1
0x00, 0x00, 0xC8,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #30
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length - max length
0xFF, 0xFF, 0xFF,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #31
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello) - unknown
0x00,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #32
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length - length off by 1
0x00, 0xCC,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #33
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length - max length
0xFF, 0xFF,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #34
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion) - unknown
0x01, 0x03, 0x04,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #35
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x80, 0x80, 0x80, 0x80, 0x61, // 0x80 0x80 0x80 0x80 is a forbidden utf-8 sequence
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
}
}
}
| // 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.Linq;
using System.Security.Authentication;
using Xunit;
namespace System.Net.Security.Tests
{
public class TlsFrameHelperTests
{
[Fact]
public void SniHelper_ValidData_Ok()
{
InvalidClientHello(s_validClientHello, -1, shouldPass: true);
}
[Theory]
[MemberData(nameof(InvalidClientHelloData))]
public void SniHelper_InvalidData_Fails(int id, byte[] clientHello)
{
InvalidClientHello(clientHello, id, shouldPass: false);
}
[Theory]
[MemberData(nameof(InvalidClientHelloDataTruncatedBytes))]
public void SniHelper_TruncatedData_Fails(int id, byte[] clientHello)
{
InvalidClientHello(clientHello, id, shouldPass: false);
}
private void InvalidClientHello(byte[] clientHello, int id, bool shouldPass)
{
string ret = TlsFrameHelper.GetServerName(clientHello);
if (shouldPass)
Assert.NotNull(ret);
else
Assert.Null(ret);
}
[Fact]
public void TlsFrameHelper_ValidData_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_validClientHello, ref info));
Assert.Equal(SslProtocols.Tls12, info.Header.Version);
Assert.Equal(203, info.Header.Length);
Assert.Equal(SslProtocols.Tls12, info.SupportedVersions);
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.None, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls12ClientHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls12ClientHello, ref info));
#pragma warning disable SYSLIB0039
Assert.Equal(SslProtocols.Tls, info.Header.Version);
Assert.Equal(SslProtocols.Tls | SslProtocols.Tls12, info.SupportedVersions);
#pragma warning restore SYSLIB0039
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Http11 | TlsFrameHelper.ApplicationProtocolInfo.Http2, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls13ClientHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls13ClientHello, ref info));
#pragma warning disable SYSLIB0039
Assert.Equal(SslProtocols.Tls, info.Header.Version);
Assert.Equal(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13, info.SupportedVersions);
#pragma warning restore SYSLIB0039
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Other, info.ApplicationProtocols);
}
[Fact]
public void TlsFrameHelper_Tls12ServerHello_Ok()
{
TlsFrameHelper.TlsFrameInfo info = default;
Assert.True(TlsFrameHelper.TryGetFrameInfo(s_Tls12ServerHello, ref info));
Assert.Equal(SslProtocols.Tls12, info.Header.Version);
Assert.Equal(SslProtocols.Tls12, info.SupportedVersions);
Assert.Equal(TlsFrameHelper.ApplicationProtocolInfo.Http2, info.ApplicationProtocols);
}
public static IEnumerable<object[]> InvalidClientHelloData()
{
int id = 0;
foreach (byte[] invalidClientHello in InvalidClientHello())
{
id++;
yield return new object[] { id, invalidClientHello };
}
}
public static IEnumerable<object[]> InvalidClientHelloDataTruncatedBytes()
{
// converting to base64 first to remove duplicated test cases
var uniqueInvalidHellos = new HashSet<string>();
foreach (byte[] invalidClientHello in InvalidClientHello())
{
for (int i = 0; i < invalidClientHello.Length; i++)
{
uniqueInvalidHellos.Add(Convert.ToBase64String(invalidClientHello.Take(i).ToArray()));
}
}
for (int i = 0; i < s_validClientHello.Length; i++)
{
uniqueInvalidHellos.Add(Convert.ToBase64String(s_validClientHello.Take(i).ToArray()));
}
int id = 0;
foreach (string invalidClientHello in uniqueInvalidHellos)
{
id++;
yield return new object[] { id, Convert.FromBase64String(invalidClientHello) };
}
}
private static byte[] s_validClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
private static byte[] s_Tls12ClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x01,
// SslPlainText.length
0x00, 0xD1,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xCD,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites_length
0x00, 0x5C,
// ClientHello.cipher_suites
0xC0, 0x30, 0xC0, 0x2C, 0xC0, 0x28, 0xC0, 0x24,
0xC0, 0x14, 0xC0, 0x0A, 0x00, 0x9f, 0x00, 0x6B,
0x00, 0x39, 0xCC, 0xA9, 0xCC, 0xA8, 0xCC, 0xAA,
0xFF, 0x85, 0x00, 0xC4, 0x00, 0x88, 0x00, 0x81,
0x00, 0x9D, 0x00, 0x3D, 0x00, 0x35, 0x00, 0xC0,
0x00, 0x84, 0xC0, 0x2f, 0xC0, 0x2B, 0xC0, 0x27,
0xC0, 0x23, 0xC0, 0x13, 0xC0, 0x09, 0x00, 0x9E,
0x00, 0x67, 0x00, 0x33, 0x00, 0xBE, 0x00, 0x45,
0x00, 0x9C, 0x00, 0x3C, 0x00, 0x2F, 0x00, 0xBA,
0x00, 0x41, 0xC0, 0x11, 0xC0, 0x07, 0x00, 0x05,
0x00, 0x04, 0xC0, 0x12, 0xC0, 0x08, 0x00, 0x16,
0x00, 0x0a, 0x00, 0xff,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x48,
// Extension.extension_type (ec_point_formats)
0x00, 0x0b, 0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (supported_groups)
0x00, 0x0A, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1D,
0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (session_ticket)
0x00, 0x23, 0x00, 0x00,
// Extension.extension_type (signature_algorithms)
0x00, 0x0D, 0x00, 0x1C, 0x00, 0x1A, 0x06, 0x01,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
// Extension.extension_type (application_level_Protocol)
0x00, 0x10, 0x00, 0x0e, 0x00, 0x0C, 0x02, 0x68,
0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2F, 0x31,
0x2E, 0x31
};
private static byte[] s_Tls13ClientHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x01,
// SslPlainText.length
0x01, 0x08,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x01, 0x04,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ClientHello.SessionId_Length
0x20,
// ClientHello.SessionId
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ClientHello.cipher_suites_length
0x00, 0x0C,
// ClientHello.cipher_suites
0x13, 0x02, 0x13, 0x03, 0x13, 0x01, 0xC0, 0x14,
0xc0, 0x30, 0x00, 0xFF,
// ClientHello.compression_methods
0x01, 0x00,
// ClientHello.extension_list_length
0x00, 0xAF,
// Extension.extension_type (server_name) (10.211.55.2)
0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00,
0x0B, 0x31, 0x30, 0x2E, 0x32, 0x31, 0x31, 0x2E,
0x35, 0x35, 0x2E, 0x32,
// Extension.extension_type (ec_point_formats)
0x00, 0x0B, 0x00, 0x04, 0x03, 0x00, 0x01, 0x02,
// Extension.extension_type (supported_groups)
0x00, 0x0A, 0x00, 0x0C, 0x00, 0x0A, 0x00, 0x1D,
0x00, 0x17, 0x00, 0x1E, 0x00, 0x19, 0x00, 0x18,
// Extension.extension_type (application_level_Protocol) (boo)
0x00, 0x10, 0x00, 0x06, 0x00, 0x04, 0x03, 0x62,
0x6f, 0x6f,
// Extension.extension_type (encrypt_then_mac)
0x00, 0x16, 0x00, 0x00,
// Extension.extension_type (extended_master_key_secret)
0x00, 0x17, 0x00, 0x00,
// Extension.extension_type (signature_algorithms)
0x00, 0x0D, 0x00, 0x30, 0x00, 0x2E,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x06, 0x03, 0xEF, 0xEF, 0x05, 0x01, 0x05, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01,
// Extension.extension_type (supported_versions)
0x00, 0x2B, 0x00, 0x09, 0x08, 0x03, 0x04, 0x03,
0x03, 0x03, 0x02, 0x03, 0x01,
// Extension.extension_type (psk_key_exchange_modes)
0x00, 0x2D, 0x00, 0x02, 0x01, 0x01,
// Extension.extension_type (key_share)
0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1D,
0x00, 0x20,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03,
0x04, 0x01, 0x04, 0x03, 0xEE, 0xEE, 0xED, 0xED,
0x03, 0x01, 0x03, 0x03, 0x02, 0x01, 0x02, 0x03
};
private static byte[] s_Tls12ServerHello = new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0x64,
// Handshake.msg_type (srever hello)
0x02,
// Handshake.length
0x00, 0x00, 0x60,
// ServerHello.client_version
0x03, 0x03,
// ServerHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ServerHello.SessionId_Length
0x20,
// ServerHello.SessionId
0x0C, 0x3C, 0x85, 0x78, 0xCA, 0x67, 0x70, 0xAA,
0x38, 0xCB, 0x28, 0xBC, 0xDC, 0x3E, 0x30, 0xBF,
0x11, 0x96, 0x95, 0x1A, 0xB9, 0xF0, 0x99, 0xA4,
0x91, 0x09, 0x13, 0xB4, 0x89, 0x94, 0x27, 0x2E,
// ServerHello.cipher_suite
0xC0, 0x2B,
// ServerHello.compression_method
0x00,
// ClientHello.extension_list_length
0x00, 0x18,
// Extension.extension_type (extended_master_secreet)
0x00, 0x17, 0x00, 0x00,
// Extension.extension_type (renegotiation_info)
0xFF, 0x01, 0x00, 0x01, 0x00,
// Extension.extension_type (ec_point_formats)
0x00, 0x0B, 0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (application_level_Protocol)
0x00, 0x10, 0x00, 0x05, 0x00, 0x03, 0x02, 0x68, 0x32,
};
private static IEnumerable<byte[]> InvalidClientHello()
{
// This test covers following test cases:
// - Length of structure off by 1 (search for "length off by 1")
// - Length of structure is max length (search for "max length")
// - Type is invalid or unknown (i.e. SslPlainText.ClientType is not 0x16 - search for "unknown")
// - Invalid utf-8 characters
// in each case sni will be null or will cause parsing error - we only expect some parsing errors,
// anything else is considered a bug
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01 - length off by 1
0x00, 0x02, 0x00
};
// #2
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01 - max length
0xFF, 0xFF, 0x00
};
// #3
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17 - length off by 1
0x00, 0x01,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #4
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17 - max length
0xFF, 0xFF,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #5
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23 - length off by 1
0x00, 0x01,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #6
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23 - max length
0xFF, 0xFF,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #7
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D - length off by 1
0x00, 0x15, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #8
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D - max length
0xFF, 0xFF, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #9
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B - length off by 1
0x00, 0x03, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #10
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B - max length
0xFF, 0xFF, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #11
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A - length off by 1
0x00, 0x09, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #10
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A - max length
0xFF, 0xFF, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #13
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length - length off by 1
0x00, 0x35,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #14
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length - max length
0xFF, 0xFF,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #15
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type - unknown
0x01,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #16
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length - length off by 1
0x00, 0x38,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #17
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length - max length
0xFF, 0xFF,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #18
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length - length off by 1
0x00, 0x3A,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #19
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length - max length
0xFF, 0xFF,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #20
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name) - unknown
0x01, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #21
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length - length off by 1
0x00, 0x75,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #22
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length - max length
0xFF, 0xFF,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #23
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods - length off by 1
0x02, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #24
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods - max length
0xFF, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #25
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites - length off by 1
0x00, 0x2B, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #26
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites - max length
0xFF, 0xFF, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #27
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId - length off by 1
0x01,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #28
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId - max length
0xFF,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #29
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length - length off by 1
0x00, 0x00, 0xC8,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #30
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length - max length
0xFF, 0xFF, 0xFF,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #31
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello) - unknown
0x00,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #32
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length - length off by 1
0x00, 0xCC,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #33
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length - max length
0xFF, 0xFF,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #34
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion) - unknown
0x01, 0x03, 0x04,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x58, 0xAA, 0x5F, 0xE7, 0x22,
0xCF, 0x9F, 0x59, 0x8A, 0xC5,
0x8B, 0x87, 0xC7, 0x62, 0x32,
0x98, 0xD4, 0xD8, 0xA2, 0xBE,
0x77, 0xCE, 0xA9, 0xCE, 0x42,
0x25, 0x5A, 0x8B, 0xEE, 0x16,
0x80, 0xF1,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
// #35
yield return new byte[] {
// SslPlainText.(ContentType+ProtocolVersion)
0x16, 0x03, 0x03,
// SslPlainText.length
0x00, 0xCB,
// Handshake.msg_type (client hello)
0x01,
// Handshake.length
0x00, 0x00, 0xC7,
// ClientHello.client_version
0x03, 0x03,
// ClientHello.random
0x0C, 0x3C, 0x85, 0x78, 0xCA,
0x67, 0x70, 0xAA, 0x38, 0xCB,
0x28, 0xBC, 0xDC, 0x3E, 0x30,
0xBF, 0x11, 0x96, 0x95, 0x1A,
0xB9, 0xF0, 0x99, 0xA4, 0x91,
0x09, 0x13, 0xB4, 0x89, 0x94,
0x27, 0x2E,
// ClientHello.SessionId
0x00,
// ClientHello.cipher_suites
0x00, 0x2A, 0xC0, 0x2C, 0xC0,
0x2B, 0xC0, 0x30, 0xC0, 0x2F,
0x00, 0x9F, 0x00, 0x9E, 0xC0,
0x24, 0xC0, 0x23, 0xC0, 0x28,
0xC0, 0x27, 0xC0, 0x0A, 0xC0,
0x09, 0xC0, 0x14, 0xC0, 0x13,
0x00, 0x9D, 0x00, 0x9C, 0x00,
0x3D, 0x00, 0x3C, 0x00, 0x35,
0x00, 0x2F, 0x00, 0x0A,
// ClientHello.compression_methods
0x01, 0x01,
// ClientHello.extension_list_length
0x00, 0x74,
// Extension.extension_type (server_name)
0x00, 0x00,
// ServerNameListExtension.length
0x00, 0x39,
// ServerName.length
0x00, 0x37,
// ServerName.type
0x00,
// HostName.length
0x00, 0x34,
// HostName.bytes
0x80, 0x80, 0x80, 0x80, 0x61, // 0x80 0x80 0x80 0x80 is a forbidden utf-8 sequence
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61, 0x61, 0x61, 0x61,
0x61, 0x61,
// Extension.extension_type (00 0A)
0x00, 0x0A,
// Extension 0A
0x00, 0x08, 0x00, 0x06, 0x00,
0x1D, 0x00, 0x17, 0x00, 0x18,
// Extension.extension_type (00 0B)
0x00, 0x0B,
// Extension 0B
0x00, 0x02, 0x01, 0x00,
// Extension.extension_type (00 0D)
0x00, 0x0D,
// Extension 0D
0x00, 0x14, 0x00, 0x12, 0x04,
0x01, 0x05, 0x01, 0x02, 0x01,
0x04, 0x03, 0x05, 0x03, 0x02,
0x03, 0x02, 0x02, 0x06, 0x01,
0x06, 0x03,
// Extension.extension_type (00 23)
0x00, 0x23,
// Extension 00 23
0x00, 0x00,
// Extension.extension_type (00 17)
0x00, 0x17,
// Extension 17
0x00, 0x00,
// Extension.extension_type (FF 01)
0xFF, 0x01,
// Extension FF01
0x00, 0x01, 0x00
};
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/coreclr/tools/Common/Internal/Runtime/CorConstants.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 Internal.CorConstants
{
/// <summary>
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/corcompile.h">src/inc/corcompile.h</a> CorCompileImportType
/// </summary>
public enum CorCompileImportType
{
CORCOMPILE_IMPORT_TYPE_UNKNOWN = 0,
CORCOMPILE_IMPORT_TYPE_EXTERNAL_METHOD = 1,
CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH = 2,
CORCOMPILE_IMPORT_TYPE_STRING_HANDLE = 3,
CORCOMPILE_IMPORT_TYPE_TYPE_HANDLE = 4,
CORCOMPILE_IMPORT_TYPE_METHOD_HANDLE = 5,
CORCOMPILE_IMPORT_TYPE_VIRTUAL_METHOD = 6,
};
/// <summary>
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/corcompile.h">src/inc/corcompile.h</a> CorCompileImportFlags
/// </summary>
public enum CorCompileImportFlags
{
CORCOMPILE_IMPORT_FLAGS_UNKNOWN = 0x0000,
CORCOMPILE_IMPORT_FLAGS_EAGER = 0x0001, // Section at module load time.
CORCOMPILE_IMPORT_FLAGS_CODE = 0x0002, // Section contains code.
CORCOMPILE_IMPORT_FLAGS_PCODE = 0x0004, // Section contains pointers to code.
};
public enum CorElementType : byte
{
Invalid = 0,
ELEMENT_TYPE_VOID = 1,
ELEMENT_TYPE_BOOLEAN = 2,
ELEMENT_TYPE_CHAR = 3,
ELEMENT_TYPE_I1 = 4,
ELEMENT_TYPE_U1 = 5,
ELEMENT_TYPE_I2 = 6,
ELEMENT_TYPE_U2 = 7,
ELEMENT_TYPE_I4 = 8,
ELEMENT_TYPE_U4 = 9,
ELEMENT_TYPE_I8 = 10,
ELEMENT_TYPE_U8 = 11,
ELEMENT_TYPE_R4 = 12,
ELEMENT_TYPE_R8 = 13,
ELEMENT_TYPE_STRING = 14,
ELEMENT_TYPE_PTR = 15,
ELEMENT_TYPE_BYREF = 16,
ELEMENT_TYPE_VALUETYPE = 17,
ELEMENT_TYPE_CLASS = 18,
ELEMENT_TYPE_VAR = 19,
ELEMENT_TYPE_ARRAY = 20,
ELEMENT_TYPE_GENERICINST = 21,
ELEMENT_TYPE_TYPEDBYREF = 22,
ELEMENT_TYPE_I = 24,
ELEMENT_TYPE_U = 25,
ELEMENT_TYPE_FNPTR = 27,
ELEMENT_TYPE_OBJECT = 28,
ELEMENT_TYPE_SZARRAY = 29,
ELEMENT_TYPE_MVAR = 30,
ELEMENT_TYPE_CMOD_REQD = 31,
ELEMENT_TYPE_CMOD_OPT = 32,
// ZapSig encoding for ELEMENT_TYPE_VAR and ELEMENT_TYPE_MVAR. It is always followed
// by the RID of a GenericParam token, encoded as a compressed integer.
ELEMENT_TYPE_VAR_ZAPSIG = 0x3b,
// UNUSED = 0x3c,
// ZapSig encoding for native value types in IL stubs. IL stub signatures may contain
// ELEMENT_TYPE_INTERNAL followed by ParamTypeDesc with ELEMENT_TYPE_VALUETYPE element
// type. It acts like a modifier to the underlying structure making it look like its
// unmanaged view (size determined by unmanaged layout, blittable, no GC pointers).
//
// ELEMENT_TYPE_NATIVE_VALUETYPE_ZAPSIG is used when encoding such types to NGEN images.
// The signature looks like this: ET_NATIVE_VALUETYPE_ZAPSIG ET_VALUETYPE <token>.
// See code:ZapSig.GetSignatureForTypeHandle and code:SigPointer.GetTypeHandleThrowing
// where the encoding/decoding takes place.
ELEMENT_TYPE_NATIVE_VALUETYPE_ZAPSIG = 0x3d,
ELEMENT_TYPE_CANON_ZAPSIG = 0x3e, // zapsig encoding for System.__Canon
ELEMENT_TYPE_MODULE_ZAPSIG = 0x3f, // zapsig encoding for external module id#
ELEMENT_TYPE_HANDLE = 64,
ELEMENT_TYPE_SENTINEL = 65,
ELEMENT_TYPE_PINNED = 69,
}
public enum CorTokenType
{
mdtModule = 0x00000000,
mdtTypeRef = 0x01000000,
mdtTypeDef = 0x02000000,
mdtFieldDef = 0x04000000,
mdtMethodDef = 0x06000000,
mdtParamDef = 0x08000000,
mdtInterfaceImpl = 0x09000000,
mdtMemberRef = 0x0a000000,
mdtCustomAttribute = 0x0c000000,
mdtPermission = 0x0e000000,
mdtSignature = 0x11000000,
mdtEvent = 0x14000000,
mdtProperty = 0x17000000,
mdtMethodImpl = 0x19000000,
mdtModuleRef = 0x1a000000,
mdtTypeSpec = 0x1b000000,
mdtAssembly = 0x20000000,
mdtAssemblyRef = 0x23000000,
mdtFile = 0x26000000,
mdtExportedType = 0x27000000,
mdtManifestResource = 0x28000000,
mdtGenericParam = 0x2a000000,
mdtMethodSpec = 0x2b000000,
mdtGenericParamConstraint = 0x2c000000,
mdtString = 0x70000000,
mdtName = 0x71000000,
mdtBaseType = 0x72000000,
}
}
| // 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 Internal.CorConstants
{
/// <summary>
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/corcompile.h">src/inc/corcompile.h</a> CorCompileImportType
/// </summary>
public enum CorCompileImportType
{
CORCOMPILE_IMPORT_TYPE_UNKNOWN = 0,
CORCOMPILE_IMPORT_TYPE_EXTERNAL_METHOD = 1,
CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH = 2,
CORCOMPILE_IMPORT_TYPE_STRING_HANDLE = 3,
CORCOMPILE_IMPORT_TYPE_TYPE_HANDLE = 4,
CORCOMPILE_IMPORT_TYPE_METHOD_HANDLE = 5,
CORCOMPILE_IMPORT_TYPE_VIRTUAL_METHOD = 6,
};
/// <summary>
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/corcompile.h">src/inc/corcompile.h</a> CorCompileImportFlags
/// </summary>
public enum CorCompileImportFlags
{
CORCOMPILE_IMPORT_FLAGS_UNKNOWN = 0x0000,
CORCOMPILE_IMPORT_FLAGS_EAGER = 0x0001, // Section at module load time.
CORCOMPILE_IMPORT_FLAGS_CODE = 0x0002, // Section contains code.
CORCOMPILE_IMPORT_FLAGS_PCODE = 0x0004, // Section contains pointers to code.
};
public enum CorElementType : byte
{
Invalid = 0,
ELEMENT_TYPE_VOID = 1,
ELEMENT_TYPE_BOOLEAN = 2,
ELEMENT_TYPE_CHAR = 3,
ELEMENT_TYPE_I1 = 4,
ELEMENT_TYPE_U1 = 5,
ELEMENT_TYPE_I2 = 6,
ELEMENT_TYPE_U2 = 7,
ELEMENT_TYPE_I4 = 8,
ELEMENT_TYPE_U4 = 9,
ELEMENT_TYPE_I8 = 10,
ELEMENT_TYPE_U8 = 11,
ELEMENT_TYPE_R4 = 12,
ELEMENT_TYPE_R8 = 13,
ELEMENT_TYPE_STRING = 14,
ELEMENT_TYPE_PTR = 15,
ELEMENT_TYPE_BYREF = 16,
ELEMENT_TYPE_VALUETYPE = 17,
ELEMENT_TYPE_CLASS = 18,
ELEMENT_TYPE_VAR = 19,
ELEMENT_TYPE_ARRAY = 20,
ELEMENT_TYPE_GENERICINST = 21,
ELEMENT_TYPE_TYPEDBYREF = 22,
ELEMENT_TYPE_I = 24,
ELEMENT_TYPE_U = 25,
ELEMENT_TYPE_FNPTR = 27,
ELEMENT_TYPE_OBJECT = 28,
ELEMENT_TYPE_SZARRAY = 29,
ELEMENT_TYPE_MVAR = 30,
ELEMENT_TYPE_CMOD_REQD = 31,
ELEMENT_TYPE_CMOD_OPT = 32,
// ZapSig encoding for ELEMENT_TYPE_VAR and ELEMENT_TYPE_MVAR. It is always followed
// by the RID of a GenericParam token, encoded as a compressed integer.
ELEMENT_TYPE_VAR_ZAPSIG = 0x3b,
// UNUSED = 0x3c,
// ZapSig encoding for native value types in IL stubs. IL stub signatures may contain
// ELEMENT_TYPE_INTERNAL followed by ParamTypeDesc with ELEMENT_TYPE_VALUETYPE element
// type. It acts like a modifier to the underlying structure making it look like its
// unmanaged view (size determined by unmanaged layout, blittable, no GC pointers).
//
// ELEMENT_TYPE_NATIVE_VALUETYPE_ZAPSIG is used when encoding such types to NGEN images.
// The signature looks like this: ET_NATIVE_VALUETYPE_ZAPSIG ET_VALUETYPE <token>.
// See code:ZapSig.GetSignatureForTypeHandle and code:SigPointer.GetTypeHandleThrowing
// where the encoding/decoding takes place.
ELEMENT_TYPE_NATIVE_VALUETYPE_ZAPSIG = 0x3d,
ELEMENT_TYPE_CANON_ZAPSIG = 0x3e, // zapsig encoding for System.__Canon
ELEMENT_TYPE_MODULE_ZAPSIG = 0x3f, // zapsig encoding for external module id#
ELEMENT_TYPE_HANDLE = 64,
ELEMENT_TYPE_SENTINEL = 65,
ELEMENT_TYPE_PINNED = 69,
}
public enum CorTokenType
{
mdtModule = 0x00000000,
mdtTypeRef = 0x01000000,
mdtTypeDef = 0x02000000,
mdtFieldDef = 0x04000000,
mdtMethodDef = 0x06000000,
mdtParamDef = 0x08000000,
mdtInterfaceImpl = 0x09000000,
mdtMemberRef = 0x0a000000,
mdtCustomAttribute = 0x0c000000,
mdtPermission = 0x0e000000,
mdtSignature = 0x11000000,
mdtEvent = 0x14000000,
mdtProperty = 0x17000000,
mdtMethodImpl = 0x19000000,
mdtModuleRef = 0x1a000000,
mdtTypeSpec = 0x1b000000,
mdtAssembly = 0x20000000,
mdtAssemblyRef = 0x23000000,
mdtFile = 0x26000000,
mdtExportedType = 0x27000000,
mdtManifestResource = 0x28000000,
mdtGenericParam = 0x2a000000,
mdtMethodSpec = 0x2b000000,
mdtGenericParamConstraint = 0x2c000000,
mdtString = 0x70000000,
mdtName = 0x71000000,
mdtBaseType = 0x72000000,
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/opt/Inline/tests/Inline_RecursiveMethod.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 TestStruct
{
public int icount;
}
public class ReturnStruct
{
public static TestStruct RecursiveMethod_Inline(TestStruct teststruct, int c)
{
if (0 != c)
{
--c;
teststruct.icount = c;
return RecursiveMethod_Inline(teststruct, c);
}
return teststruct;
}
public static int Main()
{
int iret = 100;
TestStruct ts;
ts.icount = 10;
TestStruct newts = RecursiveMethod_Inline(ts, 10);
if (newts.icount != 0)
{
Console.WriteLine("FAIL: wrong return values at count=10");
iret = 10;
}
ts.icount = 20;
newts = RecursiveMethod_Inline(ts, 20);
if (newts.icount != 0)
{
Console.WriteLine("FAIL: wrong return values at count=20");
iret = 20;
}
if (iret == 100)
Console.WriteLine("values ok");
return iret;
}
}
| // 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 TestStruct
{
public int icount;
}
public class ReturnStruct
{
public static TestStruct RecursiveMethod_Inline(TestStruct teststruct, int c)
{
if (0 != c)
{
--c;
teststruct.icount = c;
return RecursiveMethod_Inline(teststruct, c);
}
return teststruct;
}
public static int Main()
{
int iret = 100;
TestStruct ts;
ts.icount = 10;
TestStruct newts = RecursiveMethod_Inline(ts, 10);
if (newts.icount != 0)
{
Console.WriteLine("FAIL: wrong return values at count=10");
iret = 10;
}
ts.icount = 20;
newts = RecursiveMethod_Inline(ts, 20);
if (newts.icount != 0)
{
Console.WriteLine("FAIL: wrong return values at count=20");
iret = 20;
}
if (iret == 100)
Console.WriteLine("values ok");
return iret;
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/General/Vector64/Sqrt.SByte.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 SqrtSByte()
{
var test = new VectorUnaryOpTest__SqrtSByte();
// 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 VectorUnaryOpTest__SqrtSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && 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<SByte, 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 struct TestStruct
{
public Vector64<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__SqrtSByte testClass)
{
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector64<SByte> _clsVar1;
private Vector64<SByte> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__SqrtSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public VectorUnaryOpTest__SqrtSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Sqrt(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] {
typeof(Vector64<SByte>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Sqrt(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var result = Vector64.Sqrt(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__SqrtSByte();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (sbyte)(MathF.Sqrt(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (sbyte)(MathF.Sqrt(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<SByte>(Vector64<SByte>): {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\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 SqrtSByte()
{
var test = new VectorUnaryOpTest__SqrtSByte();
// 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 VectorUnaryOpTest__SqrtSByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
if ((alignment != 32 && 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<SByte, 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 struct TestStruct
{
public Vector64<SByte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__SqrtSByte testClass)
{
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static Vector64<SByte> _clsVar1;
private Vector64<SByte> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__SqrtSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public VectorUnaryOpTest__SqrtSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Sqrt(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] {
typeof(Vector64<SByte>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(SByte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Sqrt(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var result = Vector64.Sqrt(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__SqrtSByte();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<SByte> op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (sbyte)(MathF.Sqrt(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (sbyte)(MathF.Sqrt(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<SByte>(Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/Regression/JitBlue/Runtime_55131/Runtime_55131.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;
public class Runtime_55131
{
// When merging the assertion props for the finally block, we should consider the assertions
// out of the BBJ_CALLFINALLY block. Otherwise, we could propagate the wrong assertions inside
// the finally block.
//
// Althogh there can be several ways to reproduce this problem, an easier way is to turn off
// finally cloning for below example.
[MethodImpl(MethodImplOptions.NoInlining)]
static bool False() => false;
static ushort s_6;
static uint[] s_15 = new uint[] { 0 };
static bool s_19 = false;
private static int Main()
{
bool condition = False();
int result = 100;
if (condition)
{
result -= 1;
}
try
{
if (condition)
{
result -= 1;
}
}
finally
{
if (condition)
{
result -= 1;
}
}
return 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;
public class Runtime_55131
{
// When merging the assertion props for the finally block, we should consider the assertions
// out of the BBJ_CALLFINALLY block. Otherwise, we could propagate the wrong assertions inside
// the finally block.
//
// Althogh there can be several ways to reproduce this problem, an easier way is to turn off
// finally cloning for below example.
[MethodImpl(MethodImplOptions.NoInlining)]
static bool False() => false;
static ushort s_6;
static uint[] s_15 = new uint[] { 0 };
static bool s_19 = false;
private static int Main()
{
bool condition = False();
int result = 100;
if (condition)
{
result -= 1;
}
try
{
if (condition)
{
result -= 1;
}
}
finally
{
if (condition)
{
result -= 1;
}
}
return result;
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ZipHigh.Vector128.UInt32.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 ZipHigh_Vector128_UInt32()
{
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt32();
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 SimpleBinaryOpTest__ZipHigh_Vector128_UInt32
{
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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt32> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ZipHigh_Vector128_UInt32 testClass)
{
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipHigh_Vector128_UInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ZipHigh_Vector128_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleBinaryOpTest__ZipHigh_Vector128_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ZipHigh(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_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 = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ZipHigh(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt32();
var result = AdvSimd.Arm64.ZipHigh(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__ZipHigh_Vector128_UInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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 = AdvSimd.Arm64.ZipHigh(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 = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((UInt32*)(&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<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
int index = 0;
int half = RetElementCount / 2;
for (var i = 0; i < RetElementCount; i+=2, index++)
{
if (result[i] != left[index+half] || result[i+1] != right[index+half])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipHigh)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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.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 ZipHigh_Vector128_UInt32()
{
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt32();
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 SimpleBinaryOpTest__ZipHigh_Vector128_UInt32
{
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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt32> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ZipHigh_Vector128_UInt32 testClass)
{
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipHigh_Vector128_UInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ZipHigh_Vector128_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleBinaryOpTest__ZipHigh_Vector128_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ZipHigh(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_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 = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipHigh), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ZipHigh(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.ZipHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ZipHigh_Vector128_UInt32();
var result = AdvSimd.Arm64.ZipHigh(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__ZipHigh_Vector128_UInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ZipHigh(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((UInt32*)(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 = AdvSimd.Arm64.ZipHigh(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 = AdvSimd.Arm64.ZipHigh(
AdvSimd.LoadVector128((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((UInt32*)(&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<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
int index = 0;
int half = RetElementCount / 2;
for (var i = 0; i < RetElementCount; i+=2, index++)
{
if (result[i] != left[index+half] || result[i+1] != right[index+half])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipHigh)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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 | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLeftLogicalScalar.Vector64.UInt64.1.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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
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 ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray);
}
public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle.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<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1 testClass)
{
var result = AdvSimd.ShiftLeftLogicalScalar(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1 testClass)
{
fixed (Vector64<UInt64>* pFld = &_fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64);
private static readonly byte Imm = 1;
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector64<UInt64> _clsVar;
private Vector64<UInt64> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data, new UInt64[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.ShiftLeftLogicalScalar(
Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalScalar), new Type[] { typeof(Vector64<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalScalar), new Type[] { typeof(Vector64<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftLeftLogicalScalar(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt64>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pClsVar)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr);
var result = AdvSimd.ShiftLeftLogicalScalar(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr));
var result = AdvSimd.ShiftLeftLogicalScalar(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
var result = AdvSimd.ShiftLeftLogicalScalar(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
fixed (Vector64<UInt64>* pFld = &test._fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftLeftLogicalScalar(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt64>* pFld = &_fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLeftLogicalScalar(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(&test._fld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ShiftLeftLogical(firstOp[0], Imm) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalScalar)}<UInt64>(Vector64<UInt64>, 1): {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\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
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 ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray, UInt64[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt64, byte>(ref inArray[0]), (uint)sizeOfinArray);
}
public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle.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<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1 testClass)
{
var result = AdvSimd.ShiftLeftLogicalScalar(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1 testClass)
{
fixed (Vector64<UInt64>* pFld = &_fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64);
private static readonly byte Imm = 1;
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector64<UInt64> _clsVar;
private Vector64<UInt64> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data, new UInt64[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.ShiftLeftLogicalScalar(
Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalScalar), new Type[] { typeof(Vector64<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalScalar), new Type[] { typeof(Vector64<UInt64>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftLeftLogicalScalar(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt64>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pClsVar)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArrayPtr);
var result = AdvSimd.ShiftLeftLogicalScalar(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArrayPtr));
var result = AdvSimd.ShiftLeftLogicalScalar(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
var result = AdvSimd.ShiftLeftLogicalScalar(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmUnaryOpTest__ShiftLeftLogicalScalar_Vector64_UInt64_1();
fixed (Vector64<UInt64>* pFld = &test._fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftLeftLogicalScalar(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt64>* pFld = &_fld)
{
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(pFld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLeftLogicalScalar(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLeftLogicalScalar(
AdvSimd.LoadVector64((UInt64*)(&test._fld)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ShiftLeftLogical(firstOp[0], Imm) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalScalar)}<UInt64>(Vector64<UInt64>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/InsertSelectedScalar.Vector64.UInt32.1.Vector128.UInt32.3.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 InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
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 InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = 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.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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.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();
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<UInt32> _fld1;
public Vector128<UInt32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3 testClass)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3 testClass)
{
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly byte ElementIndex1 = 1;
private static readonly byte ElementIndex2 = 3;
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data3 = new UInt32[Op3ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar3;
private Vector64<UInt32> _fld1;
private Vector128<UInt32> _fld3;
private DataTable _dataTable;
static InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.InsertSelectedScalar(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
1,
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
1,
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(byte), typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
ElementIndex1,
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr),
ElementIndex2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(byte), typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
ElementIndex1,
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)),
ElementIndex2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.InsertSelectedScalar(
_clsVar1,
1,
_clsVar3,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(pClsVar1)),
1,
AdvSimd.LoadVector128((UInt32*)(pClsVar3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op3 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr));
var op3 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
fixed (Vector64<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(&test._fld1)),
1,
AdvSimd.LoadVector128((UInt32*)(&test._fld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, 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<UInt32> op1, Vector128<UInt32> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<UInt32>(Vector64<UInt32>, {1}, Vector128<UInt32>, {3}): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
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 InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
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 InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = 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.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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.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();
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<UInt32> _fld1;
public Vector128<UInt32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3 testClass)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3 testClass)
{
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly byte ElementIndex1 = 1;
private static readonly byte ElementIndex2 = 3;
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data3 = new UInt32[Op3ElementCount];
private static Vector64<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar3;
private Vector64<UInt32> _fld1;
private Vector128<UInt32> _fld3;
private DataTable _dataTable;
static InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.InsertSelectedScalar(
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
1,
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
1,
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(byte), typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr),
ElementIndex1,
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr),
ElementIndex2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<UInt32>), typeof(byte), typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr)),
ElementIndex1,
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr)),
ElementIndex2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.InsertSelectedScalar(
_clsVar1,
1,
_clsVar3,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(pClsVar1)),
1,
AdvSimd.LoadVector128((UInt32*)(pClsVar3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray1Ptr);
var op3 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray1Ptr));
var op3 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_UInt32_1_Vector128_UInt32_3();
fixed (Vector64<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld3)
{
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)pFld1),
1,
AdvSimd.LoadVector128((UInt32*)pFld2),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.InsertSelectedScalar(
AdvSimd.LoadVector64((UInt32*)(&test._fld1)),
1,
AdvSimd.LoadVector128((UInt32*)(&test._fld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, 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<UInt32> op1, Vector128<UInt32> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
ValidateResult(inArray1, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<UInt32>(Vector64<UInt32>, {1}, Vector128<UInt32>, {3}): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/baseservices/exceptions/simple/HardwareEh.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;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// DataMisalignment
// NullRef (generic, nullable, object)
// Divide by zero (integral)
// Overflow (integral)
// Stack overflow
// OOM
// Array out of bounds (single, multi, jagged)
// Array null ref (single, multi, jagged)
public class HardwareEh
{
public const long c_VALUE = 34252;
public delegate bool TestDelegate();
public static int Main()
{
HardwareEh e = new HardwareEh();
TestLibrary.TestFramework.BeginTestCase("Hardware exceptions: handled");
if (e.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Postive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
// The current stack overflow behavior is to rip the process
// retVal = PosTest10() && retVal;
// retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
retVal = PosTest17() && retVal;
retVal = PosTest18() && retVal;
retVal = PosTest19() && retVal;
retVal = PosTest20() && retVal;
return retVal;
}
public bool PosTest1() { return DataMisalign(1, false); }
public bool PosTest2() { return DataMisalign(2, true); }
public bool PosTest3() { return ExceptionTest(3, "NullReference", typeof(NullReferenceException),
delegate()
{
object o = null;
o.ToString();
return true;
} ); }
public bool PosTest4() { return ExceptionTest(4, "NullReference (generic)", typeof(NullReferenceException),
delegate()
{
List<int> l = null;
l.ToString();
return true;
} ); }
public bool PosTest5() { return ExceptionTest(5, "NullReference (nullable)", typeof(InvalidOperationException),
delegate()
{
int? i = null;
i.Value.ToString();
return true;
} ); }
public bool PosTest6() { return ExceptionTest(6, "DivideByZero (int64)", typeof(DivideByZeroException),
delegate()
{
Int64 i = 10;
Int64 j = 0;
Int64 k = i / j;
return true;
} ); }
public bool PosTest7() { return ExceptionTest(7, "DivideByZero (int32)", typeof(DivideByZeroException),
delegate()
{
Int32 i = 10;
Int32 j = 0;
Int32 k = i / j;
return true;
} ); }
public bool PosTest8() { return ExceptionTest(8, "OverflowException (int64)", typeof(OverflowException), new TestDelegate(ILHelper.Int64Overflow) ); }
public bool PosTest9() { return ExceptionTest(9, "OverflowException (int32)", typeof(OverflowException), new TestDelegate(ILHelper.Int32Overflow) ); }
// public bool PosTest10() { return ExceptionTest(10, "StackOverflow", typeof(StackOverflowException), new TestDelegate( GobbleStack )); }
/* public bool PosTest11() { return ExceptionTest(11, "OutOfMemory", typeof(OutOfMemoryException),
delegate()
{
List<object> list;
list = new List<object>();
while(true)
{
// allocate memory (86 meg chunks)
list.Add( new byte[8388608]);
}
} ); } */
public bool PosTest12() { return ExceptionTest(12, "IndexOutOfRange (single dim [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[] arr = new int[10];
int index = -1;
arr[index] = 0;
return true;
} ); }
public bool PosTest13() { return ExceptionTest(13, "IndexOutOfRange (single dim [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[] arr = new int[10];
int index = 11;
arr[index] = 0;
return true;
} ); }
public bool PosTest14() { return ExceptionTest(14, "IndexOutOfRange (multi dim [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[,] arr = new int[10,10];
int index = -1;
arr[0,index] = 0;
return true;
} ); }
public bool PosTest15() { return ExceptionTest(15, "IndexOutOfRange (multi dim [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[,] arr = new int[10,10];
int index = 11;
arr[index,0] = 0;
return true;
} ); }
public bool PosTest16() { return ExceptionTest(16, "IndexOutOfRange (jagged [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[][] arr = new int[10][];
int index = -1;
arr[0] = new int[10];
arr[0][index] = 0;
return true;
} ); }
public bool PosTest17() { return ExceptionTest(17, "IndexOutOfRange (jagged [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[][] arr = new int[10][];
int index = 11;
arr[index] = new int[10];
return true;
} ); }
public bool PosTest18() { return ExceptionTest(18, "NullReference (single dim)", typeof(NullReferenceException),
delegate()
{
int[] arr = null;
int index = 2;
arr[index] = 0;
return true;
} ); }
public bool PosTest19() { return ExceptionTest(19, "NullReference (multi dim)", typeof(NullReferenceException),
delegate()
{
int[,] arr = null;
int index = 2;
arr[index,0] = 0;
return true;
} ); }
public bool PosTest20() { return ExceptionTest(20, "NullReference (jagged)", typeof(NullReferenceException),
delegate()
{
int[][] arr = new int[10][];
int index = 2;
arr[index][0] = 0;
return true;
} ); }
public bool DataMisalign(int id, bool getter)
{
bool retVal = true;
long misAlignedField = 0;
MyStruct m;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": "+ (getter?"Get":"Set") +" misaligned field expect DataMisalignment Exception (IA64 only)");
try
{
m = new MyStruct();
if (getter)
{
misAlignedField = m.MisalignedField;
}
else
{
m.MisalignedField = c_VALUE;
}
if (IsIA64())
{
TestLibrary.TestFramework.LogError("002", "DataMisalignedException expected");
retVal = false;
}
// need to get it to validate that it is right
if (!getter) misAlignedField = m.MisalignedField;
if (c_VALUE != misAlignedField)
{
TestLibrary.TestFramework.LogError("001", "Incorrect value: Expected("+c_VALUE+") Actual("+misAlignedField+")");
retVal = false;
}
}
catch (DataMisalignedException e)
{
// expected on IA64
if (IsIA64())
{
TestLibrary.TestFramework.LogInformation("Catch DataMisalignedException as expected");
}
else
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool ExceptionTest(int id, string msg, Type ehType, TestDelegate d)
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": " + msg);
try
{
retVal = d();
TestLibrary.TestFramework.LogError("10" + id, "Function should have thrown: " + ehType);
retVal = false;
}
catch (Exception e)
{
if (ehType != e.GetType())
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
}
return retVal;
}
public bool IsIA64()
{
return false;
}
public volatile static int volatileReadWrite = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool GobbleStack()
{
#pragma warning disable 0168
MyStruct s1;
MyStruct s2;
#pragma warning restore 0168
return GobbleStack();
#pragma warning disable 0162
// avoid tail call optimizations
volatileReadWrite++;
#pragma warning restore 0162
}
}
[StructLayout(LayoutKind.Explicit)]
public class MyStruct
{
[FieldOffset(1)]
public long MisalignedField = HardwareEh.c_VALUE;
}
#pragma warning disable 0169
public struct MyLargeStruct
{
long l0,l1,l2,l3,l4,l5,l6,l7,l8,l9;
long l10,l11,l12,l13,l14,l15,l16,l17,l18,l19;
long l20,l21,l22,l23,l24,l25,l26,l27,l28,l29;
long l30,l31,l32,l33,l34,l35,l36,l37,l38,l39;
long l40,l41,l42,l43,l44,l45,l46,l47,l48,l49;
double d0,d1,d2,d3,d4,d5,d6,d7,d8,d9;
double d10,d11,d12,d13,d14,d15,d16,d17,d18,d19;
double d20,d21,d22,d23,d24,d25,d26,d27,d28,d29;
double d30,d31,d32,d33,d34,d35,d36,d37,d38,d39;
double d40,d41,d42,d43,d44,d45,d46,d47,d48,d49;
}
#pragma warning restore 0169
| // 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;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// DataMisalignment
// NullRef (generic, nullable, object)
// Divide by zero (integral)
// Overflow (integral)
// Stack overflow
// OOM
// Array out of bounds (single, multi, jagged)
// Array null ref (single, multi, jagged)
public class HardwareEh
{
public const long c_VALUE = 34252;
public delegate bool TestDelegate();
public static int Main()
{
HardwareEh e = new HardwareEh();
TestLibrary.TestFramework.BeginTestCase("Hardware exceptions: handled");
if (e.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Postive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
// The current stack overflow behavior is to rip the process
// retVal = PosTest10() && retVal;
// retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
retVal = PosTest17() && retVal;
retVal = PosTest18() && retVal;
retVal = PosTest19() && retVal;
retVal = PosTest20() && retVal;
return retVal;
}
public bool PosTest1() { return DataMisalign(1, false); }
public bool PosTest2() { return DataMisalign(2, true); }
public bool PosTest3() { return ExceptionTest(3, "NullReference", typeof(NullReferenceException),
delegate()
{
object o = null;
o.ToString();
return true;
} ); }
public bool PosTest4() { return ExceptionTest(4, "NullReference (generic)", typeof(NullReferenceException),
delegate()
{
List<int> l = null;
l.ToString();
return true;
} ); }
public bool PosTest5() { return ExceptionTest(5, "NullReference (nullable)", typeof(InvalidOperationException),
delegate()
{
int? i = null;
i.Value.ToString();
return true;
} ); }
public bool PosTest6() { return ExceptionTest(6, "DivideByZero (int64)", typeof(DivideByZeroException),
delegate()
{
Int64 i = 10;
Int64 j = 0;
Int64 k = i / j;
return true;
} ); }
public bool PosTest7() { return ExceptionTest(7, "DivideByZero (int32)", typeof(DivideByZeroException),
delegate()
{
Int32 i = 10;
Int32 j = 0;
Int32 k = i / j;
return true;
} ); }
public bool PosTest8() { return ExceptionTest(8, "OverflowException (int64)", typeof(OverflowException), new TestDelegate(ILHelper.Int64Overflow) ); }
public bool PosTest9() { return ExceptionTest(9, "OverflowException (int32)", typeof(OverflowException), new TestDelegate(ILHelper.Int32Overflow) ); }
// public bool PosTest10() { return ExceptionTest(10, "StackOverflow", typeof(StackOverflowException), new TestDelegate( GobbleStack )); }
/* public bool PosTest11() { return ExceptionTest(11, "OutOfMemory", typeof(OutOfMemoryException),
delegate()
{
List<object> list;
list = new List<object>();
while(true)
{
// allocate memory (86 meg chunks)
list.Add( new byte[8388608]);
}
} ); } */
public bool PosTest12() { return ExceptionTest(12, "IndexOutOfRange (single dim [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[] arr = new int[10];
int index = -1;
arr[index] = 0;
return true;
} ); }
public bool PosTest13() { return ExceptionTest(13, "IndexOutOfRange (single dim [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[] arr = new int[10];
int index = 11;
arr[index] = 0;
return true;
} ); }
public bool PosTest14() { return ExceptionTest(14, "IndexOutOfRange (multi dim [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[,] arr = new int[10,10];
int index = -1;
arr[0,index] = 0;
return true;
} ); }
public bool PosTest15() { return ExceptionTest(15, "IndexOutOfRange (multi dim [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[,] arr = new int[10,10];
int index = 11;
arr[index,0] = 0;
return true;
} ); }
public bool PosTest16() { return ExceptionTest(16, "IndexOutOfRange (jagged [less than])", typeof(IndexOutOfRangeException),
delegate()
{
int[][] arr = new int[10][];
int index = -1;
arr[0] = new int[10];
arr[0][index] = 0;
return true;
} ); }
public bool PosTest17() { return ExceptionTest(17, "IndexOutOfRange (jagged [greater than])", typeof(IndexOutOfRangeException),
delegate()
{
int[][] arr = new int[10][];
int index = 11;
arr[index] = new int[10];
return true;
} ); }
public bool PosTest18() { return ExceptionTest(18, "NullReference (single dim)", typeof(NullReferenceException),
delegate()
{
int[] arr = null;
int index = 2;
arr[index] = 0;
return true;
} ); }
public bool PosTest19() { return ExceptionTest(19, "NullReference (multi dim)", typeof(NullReferenceException),
delegate()
{
int[,] arr = null;
int index = 2;
arr[index,0] = 0;
return true;
} ); }
public bool PosTest20() { return ExceptionTest(20, "NullReference (jagged)", typeof(NullReferenceException),
delegate()
{
int[][] arr = new int[10][];
int index = 2;
arr[index][0] = 0;
return true;
} ); }
public bool DataMisalign(int id, bool getter)
{
bool retVal = true;
long misAlignedField = 0;
MyStruct m;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": "+ (getter?"Get":"Set") +" misaligned field expect DataMisalignment Exception (IA64 only)");
try
{
m = new MyStruct();
if (getter)
{
misAlignedField = m.MisalignedField;
}
else
{
m.MisalignedField = c_VALUE;
}
if (IsIA64())
{
TestLibrary.TestFramework.LogError("002", "DataMisalignedException expected");
retVal = false;
}
// need to get it to validate that it is right
if (!getter) misAlignedField = m.MisalignedField;
if (c_VALUE != misAlignedField)
{
TestLibrary.TestFramework.LogError("001", "Incorrect value: Expected("+c_VALUE+") Actual("+misAlignedField+")");
retVal = false;
}
}
catch (DataMisalignedException e)
{
// expected on IA64
if (IsIA64())
{
TestLibrary.TestFramework.LogInformation("Catch DataMisalignedException as expected");
}
else
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool ExceptionTest(int id, string msg, Type ehType, TestDelegate d)
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": " + msg);
try
{
retVal = d();
TestLibrary.TestFramework.LogError("10" + id, "Function should have thrown: " + ehType);
retVal = false;
}
catch (Exception e)
{
if (ehType != e.GetType())
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
}
return retVal;
}
public bool IsIA64()
{
return false;
}
public volatile static int volatileReadWrite = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool GobbleStack()
{
#pragma warning disable 0168
MyStruct s1;
MyStruct s2;
#pragma warning restore 0168
return GobbleStack();
#pragma warning disable 0162
// avoid tail call optimizations
volatileReadWrite++;
#pragma warning restore 0162
}
}
[StructLayout(LayoutKind.Explicit)]
public class MyStruct
{
[FieldOffset(1)]
public long MisalignedField = HardwareEh.c_VALUE;
}
#pragma warning disable 0169
public struct MyLargeStruct
{
long l0,l1,l2,l3,l4,l5,l6,l7,l8,l9;
long l10,l11,l12,l13,l14,l15,l16,l17,l18,l19;
long l20,l21,l22,l23,l24,l25,l26,l27,l28,l29;
long l30,l31,l32,l33,l34,l35,l36,l37,l38,l39;
long l40,l41,l42,l43,l44,l45,l46,l47,l48,l49;
double d0,d1,d2,d3,d4,d5,d6,d7,d8,d9;
double d10,d11,d12,d13,d14,d15,d16,d17,d18,d19;
double d20,d21,d22,d23,d24,d25,d26,d27,d28,d29;
double d30,d31,d32,d33,d34,d35,d36,d37,d38,d39;
double d40,d41,d42,d43,d44,d45,d46,d47,d48,d49;
}
#pragma warning restore 0169
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunGenericHelperNode.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 ILCompiler.DependencyAnalysis.ARM;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
partial class ReadyToRunGenericHelperNode
{
protected Register GetContextRegister(ref /* readonly */ ARMEmitter encoder)
{
if (_id == ReadyToRunHelperId.DelegateCtor)
return encoder.TargetRegister.Arg2;
else
return encoder.TargetRegister.Arg0;
}
protected void EmitDictionaryLookup(NodeFactory factory, ref ARMEmitter encoder, Register context, Register result, GenericLookupResult lookup, bool relocsOnly)
{
// INVARIANT: must not trash context register
// Find the generic dictionary slot
int dictionarySlot = 0;
if (!relocsOnly)
{
// The concrete slot won't be known until we're emitting data - don't ask for it in relocsOnly.
dictionarySlot = factory.GenericDictionaryLayout(_dictionaryOwner).GetSlotForEntry(lookup);
}
// Load the generic dictionary cell
encoder.EmitLDR(result, context, dictionarySlot * factory.Target.PointerSize);
switch (lookup.LookupResultReferenceType(factory))
{
case GenericLookupResultReferenceType.Indirect:
// Do another indirection
encoder.EmitLDR(result, result);
break;
case GenericLookupResultReferenceType.ConditionalIndirect:
// Test result, 0x1
// JEQ L1
// mov result, [result-1]
// L1:
throw new NotImplementedException();
default:
break;
}
}
protected sealed override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// First load the generic context into the context register.
EmitLoadGenericContext(factory, ref encoder, relocsOnly);
Register contextRegister = GetContextRegister(ref encoder);
switch (_id)
{
case ReadyToRunHelperId.GetNonGCStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
MetadataType target = (MetadataType)_target;
if (!factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitLDR(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0, ((short)(factory.Target.PointerSize - cctorContextSize)));
encoder.EmitCMP(encoder.TargetRegister.Arg1, ((byte)1));
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitSUB(encoder.TargetRegister.Arg0, ((byte)(cctorContextSize)));
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetGCStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result);
MetadataType target = (MetadataType)_target;
if (!factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg2, nonGcRegionLookup, relocsOnly);
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitLDR(encoder.TargetRegister.Arg3, encoder.TargetRegister.Arg2, ((short)(factory.Target.PointerSize - cctorContextSize)));
encoder.EmitCMP(encoder.TargetRegister.Arg3, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitMOV(encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2);
encoder.EmitSUB(encoder.TargetRegister.Arg0, cctorContextSize);
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetThreadStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
MetadataType target = (MetadataType)_target;
// Look up the index cell
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg1, _lookupSignature, relocsOnly);
ISymbolNode helperEntrypoint;
if (factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
// There is a lazy class constructor. We need the non-GC static base because that's where the
// class constructor context lives.
GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2, nonGcRegionLookup, relocsOnly);
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitSUB(encoder.TargetRegister.Arg2, cctorContextSize);
helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase);
}
else
{
helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType);
}
// First arg: address of the TypeManager slot that provides the helper with
// information about module index and the type manager instance (which is used
// for initialization on first access).
encoder.EmitLDR(encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg1);
// Second arg: index of the type in the ThreadStatic section of the modules
encoder.EmitLDR(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg1, factory.Target.PointerSize);
encoder.EmitJMP(helperEntrypoint);
}
break;
case ReadyToRunHelperId.DelegateCtor:
{
// This is a weird helper. Codegen populated Arg0 and Arg1 with the values that the constructor
// method expects. Codegen also passed us the generic context in Arg2.
// We now need to load the delegate target method into Arg2 (using a dictionary lookup)
// and the optional 4th parameter, and call the ctor.
Debug.Assert(contextRegister == encoder.TargetRegister.Arg2);
var target = (DelegateCreationInfo)_target;
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg2, _lookupSignature, relocsOnly);
if (target.Thunk != null)
{
Debug.Assert(target.Constructor.Method.Signature.Length == 3);
encoder.EmitMOV(encoder.TargetRegister.Arg3, target.Thunk);
}
else
{
Debug.Assert(target.Constructor.Method.Signature.Length == 2);
}
encoder.EmitJMP(target.Constructor);
}
break;
// These are all simple: just get the thing from the dictionary and we're done
case ReadyToRunHelperId.TypeHandle:
case ReadyToRunHelperId.MethodHandle:
case ReadyToRunHelperId.FieldHandle:
case ReadyToRunHelperId.MethodDictionary:
case ReadyToRunHelperId.MethodEntry:
case ReadyToRunHelperId.VirtualDispatchCell:
case ReadyToRunHelperId.DefaultConstructor:
case ReadyToRunHelperId.ObjectAllocator:
case ReadyToRunHelperId.TypeHandleForCasting:
case ReadyToRunHelperId.ConstrainedDirectCall:
{
EmitDictionaryLookup(factory, ref encoder, contextRegister, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
encoder.EmitRET();
}
break;
default:
throw new NotImplementedException();
}
}
protected virtual void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// Assume generic context is already loaded in the context register.
}
}
partial class ReadyToRunGenericLookupFromTypeNode
{
protected override void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// We start with context register pointing to the MethodTable
Register contextRegister = GetContextRegister(ref encoder);
// Locate the VTable slot that points to the dictionary
int vtableSlot = 0;
if (!relocsOnly)
{
// The concrete slot won't be known until we're emitting data - don't ask for it in relocsOnly.
vtableSlot = VirtualMethodSlotHelper.GetGenericDictionarySlot(factory, (TypeDesc)_dictionaryOwner);
}
int pointerSize = factory.Target.PointerSize;
int slotOffset = EETypeNode.GetVTableOffset(pointerSize) + (vtableSlot * pointerSize);
// Load the dictionary pointer from the VTable
encoder.EmitLDR(contextRegister, contextRegister, slotOffset);
}
}
}
| // 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 ILCompiler.DependencyAnalysis.ARM;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
partial class ReadyToRunGenericHelperNode
{
protected Register GetContextRegister(ref /* readonly */ ARMEmitter encoder)
{
if (_id == ReadyToRunHelperId.DelegateCtor)
return encoder.TargetRegister.Arg2;
else
return encoder.TargetRegister.Arg0;
}
protected void EmitDictionaryLookup(NodeFactory factory, ref ARMEmitter encoder, Register context, Register result, GenericLookupResult lookup, bool relocsOnly)
{
// INVARIANT: must not trash context register
// Find the generic dictionary slot
int dictionarySlot = 0;
if (!relocsOnly)
{
// The concrete slot won't be known until we're emitting data - don't ask for it in relocsOnly.
dictionarySlot = factory.GenericDictionaryLayout(_dictionaryOwner).GetSlotForEntry(lookup);
}
// Load the generic dictionary cell
encoder.EmitLDR(result, context, dictionarySlot * factory.Target.PointerSize);
switch (lookup.LookupResultReferenceType(factory))
{
case GenericLookupResultReferenceType.Indirect:
// Do another indirection
encoder.EmitLDR(result, result);
break;
case GenericLookupResultReferenceType.ConditionalIndirect:
// Test result, 0x1
// JEQ L1
// mov result, [result-1]
// L1:
throw new NotImplementedException();
default:
break;
}
}
protected sealed override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// First load the generic context into the context register.
EmitLoadGenericContext(factory, ref encoder, relocsOnly);
Register contextRegister = GetContextRegister(ref encoder);
switch (_id)
{
case ReadyToRunHelperId.GetNonGCStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
MetadataType target = (MetadataType)_target;
if (!factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitLDR(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0, ((short)(factory.Target.PointerSize - cctorContextSize)));
encoder.EmitCMP(encoder.TargetRegister.Arg1, ((byte)1));
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitSUB(encoder.TargetRegister.Arg0, ((byte)(cctorContextSize)));
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetGCStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
encoder.EmitLDR(encoder.TargetRegister.Result, encoder.TargetRegister.Result);
MetadataType target = (MetadataType)_target;
if (!factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
encoder.EmitRET();
}
else
{
// We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region.
GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg2, nonGcRegionLookup, relocsOnly);
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitLDR(encoder.TargetRegister.Arg3, encoder.TargetRegister.Arg2, ((short)(factory.Target.PointerSize - cctorContextSize)));
encoder.EmitCMP(encoder.TargetRegister.Arg3, 1);
encoder.EmitRETIfEqual();
encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result);
encoder.EmitMOV(encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2);
encoder.EmitSUB(encoder.TargetRegister.Arg0, cctorContextSize);
encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase));
}
}
break;
case ReadyToRunHelperId.GetThreadStaticBase:
{
Debug.Assert(contextRegister == encoder.TargetRegister.Arg0);
MetadataType target = (MetadataType)_target;
// Look up the index cell
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg1, _lookupSignature, relocsOnly);
ISymbolNode helperEntrypoint;
if (factory.PreinitializationManager.HasLazyStaticConstructor(target))
{
// There is a lazy class constructor. We need the non-GC static base because that's where the
// class constructor context lives.
GenericLookupResult nonGcRegionLookup = factory.GenericLookup.TypeNonGCStaticBase(target);
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg2, nonGcRegionLookup, relocsOnly);
int cctorContextSize = NonGCStaticsNode.GetClassConstructorContextSize(factory.Target);
encoder.EmitSUB(encoder.TargetRegister.Arg2, cctorContextSize);
helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase);
}
else
{
helperEntrypoint = factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType);
}
// First arg: address of the TypeManager slot that provides the helper with
// information about module index and the type manager instance (which is used
// for initialization on first access).
encoder.EmitLDR(encoder.TargetRegister.Arg0, encoder.TargetRegister.Arg1);
// Second arg: index of the type in the ThreadStatic section of the modules
encoder.EmitLDR(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg1, factory.Target.PointerSize);
encoder.EmitJMP(helperEntrypoint);
}
break;
case ReadyToRunHelperId.DelegateCtor:
{
// This is a weird helper. Codegen populated Arg0 and Arg1 with the values that the constructor
// method expects. Codegen also passed us the generic context in Arg2.
// We now need to load the delegate target method into Arg2 (using a dictionary lookup)
// and the optional 4th parameter, and call the ctor.
Debug.Assert(contextRegister == encoder.TargetRegister.Arg2);
var target = (DelegateCreationInfo)_target;
EmitDictionaryLookup(factory, ref encoder, encoder.TargetRegister.Arg2, encoder.TargetRegister.Arg2, _lookupSignature, relocsOnly);
if (target.Thunk != null)
{
Debug.Assert(target.Constructor.Method.Signature.Length == 3);
encoder.EmitMOV(encoder.TargetRegister.Arg3, target.Thunk);
}
else
{
Debug.Assert(target.Constructor.Method.Signature.Length == 2);
}
encoder.EmitJMP(target.Constructor);
}
break;
// These are all simple: just get the thing from the dictionary and we're done
case ReadyToRunHelperId.TypeHandle:
case ReadyToRunHelperId.MethodHandle:
case ReadyToRunHelperId.FieldHandle:
case ReadyToRunHelperId.MethodDictionary:
case ReadyToRunHelperId.MethodEntry:
case ReadyToRunHelperId.VirtualDispatchCell:
case ReadyToRunHelperId.DefaultConstructor:
case ReadyToRunHelperId.ObjectAllocator:
case ReadyToRunHelperId.TypeHandleForCasting:
case ReadyToRunHelperId.ConstrainedDirectCall:
{
EmitDictionaryLookup(factory, ref encoder, contextRegister, encoder.TargetRegister.Result, _lookupSignature, relocsOnly);
encoder.EmitRET();
}
break;
default:
throw new NotImplementedException();
}
}
protected virtual void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// Assume generic context is already loaded in the context register.
}
}
partial class ReadyToRunGenericLookupFromTypeNode
{
protected override void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly)
{
// We start with context register pointing to the MethodTable
Register contextRegister = GetContextRegister(ref encoder);
// Locate the VTable slot that points to the dictionary
int vtableSlot = 0;
if (!relocsOnly)
{
// The concrete slot won't be known until we're emitting data - don't ask for it in relocsOnly.
vtableSlot = VirtualMethodSlotHelper.GetGenericDictionarySlot(factory, (TypeDesc)_dictionaryOwner);
}
int pointerSize = factory.Target.PointerSize;
int slotOffset = EETypeNode.GetVTableOffset(pointerSize) + (vtableSlot * pointerSize);
// Load the dictionary pointer from the VTable
encoder.EmitLDR(contextRegister, contextRegister, slotOffset);
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.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;
namespace System.Xml.Xsl.XPath
{
using XPathNodeType = System.Xml.XPath.XPathNodeType;
internal sealed class XPathParser<Node>
{
private XPathScanner? _scanner;
private IXPathBuilder<Node>? _builder;
private readonly Stack<int> _posInfo = new Stack<int>();
// Six possible causes of exceptions in the builder:
// 1. Undefined prefix in a node test.
// 2. Undefined prefix in a variable reference, or unknown variable.
// 3. Undefined prefix in a function call, or unknown function, or wrong number/types of arguments.
// 4. Argument of Union operator is not a node-set.
// 5. First argument of Predicate is not a node-set.
// 6. Argument of Axis is not a node-set.
public Node Parse(XPathScanner scanner, IXPathBuilder<Node> builder, LexKind endLex)
{
Debug.Assert(_scanner == null && _builder == null);
Debug.Assert(scanner != null && builder != null);
Node? result = default(Node);
_scanner = scanner;
_builder = builder;
_posInfo.Clear();
try
{
builder.StartBuild();
result = ParseExpr();
scanner.CheckToken(endLex);
}
catch (XPathCompileException e)
{
if (e.queryString == null)
{
e.queryString = scanner.Source;
PopPosInfo(out e.startChar, out e.endChar);
}
throw;
}
finally
{
result = builder.EndBuild(result);
#if DEBUG
_builder = null;
_scanner = null;
#endif
}
Debug.Assert(_posInfo.Count == 0, "PushPosInfo() and PopPosInfo() calls have been unbalanced");
return result!;
}
#region Location paths and node tests
/**************************************************************************************************/
/* Location paths and node tests */
/**************************************************************************************************/
internal static bool IsStep(LexKind lexKind)
{
return (
lexKind == LexKind.Dot ||
lexKind == LexKind.DotDot ||
lexKind == LexKind.At ||
lexKind == LexKind.Axis ||
lexKind == LexKind.Star ||
lexKind == LexKind.Name // NodeTest is also Name
);
}
/*
* LocationPath ::= RelativeLocationPath | '/' RelativeLocationPath? | '//' RelativeLocationPath
*/
private Node ParseLocationPath()
{
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
Node opnd = _builder!.Axis(XPathAxis.Root, XPathNodeType.All, null, null);
if (IsStep(_scanner.Kind))
{
opnd = _builder.JoinStep(opnd, ParseRelativeLocationPath());
}
return opnd;
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
return _builder!.JoinStep(
_builder.Axis(XPathAxis.Root, XPathNodeType.All, null, null),
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
else
{
return ParseRelativeLocationPath();
}
}
/*
* RelativeLocationPath ::= Step (('/' | '//') Step)*
*/
//Max depth to avoid StackOverflow
private const int MaxParseRelativePathDepth = 1024;
private int _parseRelativePath;
private Node ParseRelativeLocationPath()
{
if (++_parseRelativePath > MaxParseRelativePathDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
Node opnd = ParseStep();
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
--_parseRelativePath;
return opnd;
}
/*
* Step ::= '.' | '..' | (AxisName '::' | '@')? NodeTest Predicate*
*/
private Node ParseStep()
{
Node opnd;
if (LexKind.Dot == _scanner!.Kind)
{ // '.'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Self, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDot);
}
}
else if (LexKind.DotDot == _scanner.Kind)
{ // '..'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Parent, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDotDot);
}
}
else
{ // (AxisName '::' | '@')? NodeTest Predicate*
XPathAxis axis;
switch (_scanner.Kind)
{
case LexKind.Axis: // AxisName '::'
axis = _scanner.Axis;
_scanner.NextLex();
_scanner.NextLex();
break;
case LexKind.At: // '@'
axis = XPathAxis.Attribute;
_scanner.NextLex();
break;
case LexKind.Name:
case LexKind.Star:
// NodeTest must start with Name or '*'
axis = XPathAxis.Child;
break;
default:
throw _scanner.CreateException(SR.XPath_UnexpectedToken, _scanner.RawValue);
}
opnd = ParseNodeTest(axis);
while (LexKind.LBracket == _scanner.Kind)
{
opnd = _builder!.Predicate(opnd, ParsePredicate(), IsReverseAxis(axis));
}
}
return opnd;
}
private static bool IsReverseAxis(XPathAxis axis)
{
return (
axis == XPathAxis.Ancestor || axis == XPathAxis.Preceding ||
axis == XPathAxis.AncestorOrSelf || axis == XPathAxis.PrecedingSibling
);
}
/*
* NodeTest ::= NameTest | ('comment' | 'text' | 'node') '(' ')' | 'processing-instruction' '(' Literal? ')'
* NameTest ::= '*' | NCName ':' '*' | QName
*/
private Node ParseNodeTest(XPathAxis axis)
{
XPathNodeType nodeType;
string? nodePrefix, nodeName;
int startChar = _scanner!.LexStart;
InternalParseNodeTest(_scanner, axis, out nodeType, out nodePrefix, out nodeName);
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Axis(axis, nodeType, nodePrefix, nodeName);
PopPosInfo();
return result;
}
private static bool IsNodeType(XPathScanner scanner)
{
return scanner.Prefix.Length == 0 && (
scanner.Name == "node" ||
scanner.Name == "text" ||
scanner.Name == "processing-instruction" ||
scanner.Name == "comment"
);
}
private static XPathNodeType PrincipalNodeType(XPathAxis axis)
{
return (
axis == XPathAxis.Attribute ? XPathNodeType.Attribute :
axis == XPathAxis.Namespace ? XPathNodeType.Namespace :
/*else*/ XPathNodeType.Element
);
}
internal static void InternalParseNodeTest(XPathScanner scanner, XPathAxis axis, out XPathNodeType nodeType, out string? nodePrefix, out string? nodeName)
{
switch (scanner.Kind)
{
case LexKind.Name:
if (scanner.CanBeFunction && IsNodeType(scanner))
{
nodePrefix = null;
nodeName = null;
switch (scanner.Name)
{
case "comment": nodeType = XPathNodeType.Comment; break;
case "text": nodeType = XPathNodeType.Text; break;
case "node": nodeType = XPathNodeType.All; break;
default:
Debug.Assert(scanner.Name == "processing-instruction");
nodeType = XPathNodeType.ProcessingInstruction;
break;
}
scanner.NextLex();
scanner.PassToken(LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (scanner.Kind != LexKind.RParens)
{ // 'processing-instruction' '(' Literal ')'
scanner.CheckToken(LexKind.String);
// It is not needed to set nodePrefix here, but for our current implementation
// comparing whole QNames is faster than comparing just local names
nodePrefix = string.Empty;
nodeName = scanner.StringValue;
scanner.NextLex();
}
}
scanner.PassToken(LexKind.RParens);
}
else
{
nodePrefix = scanner.Prefix;
nodeName = scanner.Name;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
if (nodeName == "*")
{
nodeName = null;
}
}
break;
case LexKind.Star:
nodePrefix = null;
nodeName = null;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
break;
default:
throw scanner.CreateException(SR.XPath_NodeTestExpected, scanner.RawValue);
}
}
/*
* Predicate ::= '[' Expr ']'
*/
private Node ParsePredicate()
{
_scanner!.PassToken(LexKind.LBracket);
Node opnd = ParseExpr();
_scanner.PassToken(LexKind.RBracket);
return opnd;
}
#endregion
#region Expressions
/**************************************************************************************************/
/* Expressions */
/**************************************************************************************************/
/*
* Expr ::= OrExpr
* OrExpr ::= AndExpr ('or' AndExpr)*
* AndExpr ::= EqualityExpr ('and' EqualityExpr)*
* EqualityExpr ::= RelationalExpr (('=' | '!=') RelationalExpr)*
* RelationalExpr ::= AdditiveExpr (('<' | '>' | '<=' | '>=') AdditiveExpr)*
* AdditiveExpr ::= MultiplicativeExpr (('+' | '-') MultiplicativeExpr)*
* MultiplicativeExpr ::= UnaryExpr (('*' | 'div' | 'mod') UnaryExpr)*
* UnaryExpr ::= ('-')* UnionExpr
*/
private Node ParseExpr()
{
return ParseSubExpr(/*callerPrec:*/0);
}
//Max depth to avoid StackOverflow
//limit the recursive call from ParseSubExpr -> ParseSubExpr
//and also ParseSubExpr->ParseUnionExpr->ParsePathExpr->...->ParseExpr->ParseSubExpr
private const int MaxParseSubExprDepth = 1024;
private int _parseSubExprDepth;
private Node ParseSubExpr(int callerPrec)
{
if (++_parseSubExprDepth > MaxParseSubExprDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
XPathOperator op;
Node opnd;
// Check for unary operators
if (_scanner!.Kind == LexKind.Minus)
{
op = XPathOperator.UnaryMinus;
int opPrec = s_XPathOperatorPrecedence[(int)op];
_scanner.NextLex();
opnd = _builder!.Operator(op, ParseSubExpr(opPrec), default(Node));
}
else
{
opnd = ParseUnionExpr();
}
// Process binary operators
while (true)
{
op = (_scanner.Kind <= LexKind.LastOperator) ? (XPathOperator)_scanner.Kind : XPathOperator.Unknown;
int opPrec = s_XPathOperatorPrecedence[(int)op];
if (opPrec <= callerPrec)
{
break;
}
// Operator's precedence is greater than the one of our caller, so process it here
_scanner.NextLex();
opnd = _builder!.Operator(op, opnd, ParseSubExpr(/*callerPrec:*/opPrec));
}
--_parseSubExprDepth;
return opnd;
}
private static readonly int[] s_XPathOperatorPrecedence = {
/*Unknown */ 0,
/*Or */ 1,
/*And */ 2,
/*Eq */ 3,
/*Ne */ 3,
/*Lt */ 4,
/*Le */ 4,
/*Gt */ 4,
/*Ge */ 4,
/*Plus */ 5,
/*Minus */ 5,
/*Multiply */ 6,
/*Divide */ 6,
/*Modulo */ 6,
/*UnaryMinus */ 7,
/*Union */ 8, // Not used
};
/*
* UnionExpr ::= PathExpr ('|' PathExpr)*
*/
private Node ParseUnionExpr()
{
int startChar = _scanner!.LexStart;
Node opnd1 = ParsePathExpr();
if (_scanner.Kind == LexKind.Union)
{
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder!.Operator(XPathOperator.Union, default(Node), opnd1);
PopPosInfo();
while (_scanner.Kind == LexKind.Union)
{
_scanner.NextLex();
startChar = _scanner.LexStart;
Node opnd2 = ParsePathExpr();
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder.Operator(XPathOperator.Union, opnd1, opnd2);
PopPosInfo();
}
}
return opnd1;
}
/*
* PathExpr ::= LocationPath | FilterExpr (('/' | '//') RelativeLocationPath )?
*/
private Node ParsePathExpr()
{
// Here we distinguish FilterExpr from LocationPath - the former starts with PrimaryExpr
if (IsPrimaryExpr())
{
int startChar = _scanner!.LexStart;
Node opnd = ParseFilterExpr();
int endChar = _scanner.PrevLexEnd;
if (_scanner.Kind == LexKind.Slash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
PopPosInfo();
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
PopPosInfo();
}
return opnd;
}
else
{
return ParseLocationPath();
}
}
/*
* FilterExpr ::= PrimaryExpr Predicate*
*/
private Node ParseFilterExpr()
{
int startChar = _scanner!.LexStart;
Node opnd = ParsePrimaryExpr();
int endChar = _scanner.PrevLexEnd;
while (_scanner.Kind == LexKind.LBracket)
{
PushPosInfo(startChar, endChar);
opnd = _builder!.Predicate(opnd, ParsePredicate(), /*reverseStep:*/false);
PopPosInfo();
}
return opnd;
}
private bool IsPrimaryExpr()
{
return (
_scanner!.Kind == LexKind.String ||
_scanner.Kind == LexKind.Number ||
_scanner.Kind == LexKind.Dollar ||
_scanner.Kind == LexKind.LParens ||
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner)
);
}
/*
* PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
*/
private Node ParsePrimaryExpr()
{
Debug.Assert(IsPrimaryExpr());
Node opnd;
switch (_scanner!.Kind)
{
case LexKind.String:
opnd = _builder!.String(_scanner.StringValue);
_scanner.NextLex();
break;
case LexKind.Number:
opnd = _builder!.Number(XPathConvert.StringToDouble(_scanner.RawValue));
_scanner.NextLex();
break;
case LexKind.Dollar:
int startChar = _scanner.LexStart;
_scanner.NextLex();
_scanner.CheckToken(LexKind.Name);
PushPosInfo(startChar, _scanner.LexStart + _scanner.LexSize);
opnd = _builder!.Variable(_scanner.Prefix, _scanner.Name);
PopPosInfo();
_scanner.NextLex();
break;
case LexKind.LParens:
_scanner.NextLex();
opnd = ParseExpr();
_scanner.PassToken(LexKind.RParens);
break;
default:
Debug.Assert(
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner),
"IsPrimaryExpr() returned true, but the lexeme is not recognized"
);
opnd = ParseFunctionCall();
break;
}
return opnd;
}
/*
* FunctionCall ::= FunctionName '(' (Expr (',' Expr)* )? ')'
*/
private Node ParseFunctionCall()
{
List<Node> argList = new List<Node>();
string name = _scanner!.Name;
string prefix = _scanner.Prefix;
int startChar = _scanner.LexStart;
_scanner.PassToken(LexKind.Name);
_scanner.PassToken(LexKind.LParens);
if (_scanner.Kind != LexKind.RParens)
{
while (true)
{
argList.Add(ParseExpr());
if (_scanner.Kind != LexKind.Comma)
{
_scanner.CheckToken(LexKind.RParens);
break;
}
_scanner.NextLex(); // move off the ','
}
}
_scanner.NextLex(); // move off the ')'
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Function(prefix, name, argList);
PopPosInfo();
return result;
}
#endregion
/**************************************************************************************************/
/* Helper methods */
/**************************************************************************************************/
private void PushPosInfo(int startChar, int endChar)
{
_posInfo.Push(startChar);
_posInfo.Push(endChar);
}
private void PopPosInfo()
{
_posInfo.Pop();
_posInfo.Pop();
}
private void PopPosInfo(out int startChar, out int endChar)
{
endChar = _posInfo.Pop();
startChar = _posInfo.Pop();
}
}
}
| // 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;
namespace System.Xml.Xsl.XPath
{
using XPathNodeType = System.Xml.XPath.XPathNodeType;
internal sealed class XPathParser<Node>
{
private XPathScanner? _scanner;
private IXPathBuilder<Node>? _builder;
private readonly Stack<int> _posInfo = new Stack<int>();
// Six possible causes of exceptions in the builder:
// 1. Undefined prefix in a node test.
// 2. Undefined prefix in a variable reference, or unknown variable.
// 3. Undefined prefix in a function call, or unknown function, or wrong number/types of arguments.
// 4. Argument of Union operator is not a node-set.
// 5. First argument of Predicate is not a node-set.
// 6. Argument of Axis is not a node-set.
public Node Parse(XPathScanner scanner, IXPathBuilder<Node> builder, LexKind endLex)
{
Debug.Assert(_scanner == null && _builder == null);
Debug.Assert(scanner != null && builder != null);
Node? result = default(Node);
_scanner = scanner;
_builder = builder;
_posInfo.Clear();
try
{
builder.StartBuild();
result = ParseExpr();
scanner.CheckToken(endLex);
}
catch (XPathCompileException e)
{
if (e.queryString == null)
{
e.queryString = scanner.Source;
PopPosInfo(out e.startChar, out e.endChar);
}
throw;
}
finally
{
result = builder.EndBuild(result);
#if DEBUG
_builder = null;
_scanner = null;
#endif
}
Debug.Assert(_posInfo.Count == 0, "PushPosInfo() and PopPosInfo() calls have been unbalanced");
return result!;
}
#region Location paths and node tests
/**************************************************************************************************/
/* Location paths and node tests */
/**************************************************************************************************/
internal static bool IsStep(LexKind lexKind)
{
return (
lexKind == LexKind.Dot ||
lexKind == LexKind.DotDot ||
lexKind == LexKind.At ||
lexKind == LexKind.Axis ||
lexKind == LexKind.Star ||
lexKind == LexKind.Name // NodeTest is also Name
);
}
/*
* LocationPath ::= RelativeLocationPath | '/' RelativeLocationPath? | '//' RelativeLocationPath
*/
private Node ParseLocationPath()
{
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
Node opnd = _builder!.Axis(XPathAxis.Root, XPathNodeType.All, null, null);
if (IsStep(_scanner.Kind))
{
opnd = _builder.JoinStep(opnd, ParseRelativeLocationPath());
}
return opnd;
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
return _builder!.JoinStep(
_builder.Axis(XPathAxis.Root, XPathNodeType.All, null, null),
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
else
{
return ParseRelativeLocationPath();
}
}
/*
* RelativeLocationPath ::= Step (('/' | '//') Step)*
*/
//Max depth to avoid StackOverflow
private const int MaxParseRelativePathDepth = 1024;
private int _parseRelativePath;
private Node ParseRelativeLocationPath()
{
if (++_parseRelativePath > MaxParseRelativePathDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
Node opnd = ParseStep();
if (_scanner!.Kind == LexKind.Slash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
}
--_parseRelativePath;
return opnd;
}
/*
* Step ::= '.' | '..' | (AxisName '::' | '@')? NodeTest Predicate*
*/
private Node ParseStep()
{
Node opnd;
if (LexKind.Dot == _scanner!.Kind)
{ // '.'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Self, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDot);
}
}
else if (LexKind.DotDot == _scanner.Kind)
{ // '..'
_scanner.NextLex();
opnd = _builder!.Axis(XPathAxis.Parent, XPathNodeType.All, null, null);
if (LexKind.LBracket == _scanner.Kind)
{
throw _scanner.CreateException(SR.XPath_PredicateAfterDotDot);
}
}
else
{ // (AxisName '::' | '@')? NodeTest Predicate*
XPathAxis axis;
switch (_scanner.Kind)
{
case LexKind.Axis: // AxisName '::'
axis = _scanner.Axis;
_scanner.NextLex();
_scanner.NextLex();
break;
case LexKind.At: // '@'
axis = XPathAxis.Attribute;
_scanner.NextLex();
break;
case LexKind.Name:
case LexKind.Star:
// NodeTest must start with Name or '*'
axis = XPathAxis.Child;
break;
default:
throw _scanner.CreateException(SR.XPath_UnexpectedToken, _scanner.RawValue);
}
opnd = ParseNodeTest(axis);
while (LexKind.LBracket == _scanner.Kind)
{
opnd = _builder!.Predicate(opnd, ParsePredicate(), IsReverseAxis(axis));
}
}
return opnd;
}
private static bool IsReverseAxis(XPathAxis axis)
{
return (
axis == XPathAxis.Ancestor || axis == XPathAxis.Preceding ||
axis == XPathAxis.AncestorOrSelf || axis == XPathAxis.PrecedingSibling
);
}
/*
* NodeTest ::= NameTest | ('comment' | 'text' | 'node') '(' ')' | 'processing-instruction' '(' Literal? ')'
* NameTest ::= '*' | NCName ':' '*' | QName
*/
private Node ParseNodeTest(XPathAxis axis)
{
XPathNodeType nodeType;
string? nodePrefix, nodeName;
int startChar = _scanner!.LexStart;
InternalParseNodeTest(_scanner, axis, out nodeType, out nodePrefix, out nodeName);
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Axis(axis, nodeType, nodePrefix, nodeName);
PopPosInfo();
return result;
}
private static bool IsNodeType(XPathScanner scanner)
{
return scanner.Prefix.Length == 0 && (
scanner.Name == "node" ||
scanner.Name == "text" ||
scanner.Name == "processing-instruction" ||
scanner.Name == "comment"
);
}
private static XPathNodeType PrincipalNodeType(XPathAxis axis)
{
return (
axis == XPathAxis.Attribute ? XPathNodeType.Attribute :
axis == XPathAxis.Namespace ? XPathNodeType.Namespace :
/*else*/ XPathNodeType.Element
);
}
internal static void InternalParseNodeTest(XPathScanner scanner, XPathAxis axis, out XPathNodeType nodeType, out string? nodePrefix, out string? nodeName)
{
switch (scanner.Kind)
{
case LexKind.Name:
if (scanner.CanBeFunction && IsNodeType(scanner))
{
nodePrefix = null;
nodeName = null;
switch (scanner.Name)
{
case "comment": nodeType = XPathNodeType.Comment; break;
case "text": nodeType = XPathNodeType.Text; break;
case "node": nodeType = XPathNodeType.All; break;
default:
Debug.Assert(scanner.Name == "processing-instruction");
nodeType = XPathNodeType.ProcessingInstruction;
break;
}
scanner.NextLex();
scanner.PassToken(LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (scanner.Kind != LexKind.RParens)
{ // 'processing-instruction' '(' Literal ')'
scanner.CheckToken(LexKind.String);
// It is not needed to set nodePrefix here, but for our current implementation
// comparing whole QNames is faster than comparing just local names
nodePrefix = string.Empty;
nodeName = scanner.StringValue;
scanner.NextLex();
}
}
scanner.PassToken(LexKind.RParens);
}
else
{
nodePrefix = scanner.Prefix;
nodeName = scanner.Name;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
if (nodeName == "*")
{
nodeName = null;
}
}
break;
case LexKind.Star:
nodePrefix = null;
nodeName = null;
nodeType = PrincipalNodeType(axis);
scanner.NextLex();
break;
default:
throw scanner.CreateException(SR.XPath_NodeTestExpected, scanner.RawValue);
}
}
/*
* Predicate ::= '[' Expr ']'
*/
private Node ParsePredicate()
{
_scanner!.PassToken(LexKind.LBracket);
Node opnd = ParseExpr();
_scanner.PassToken(LexKind.RBracket);
return opnd;
}
#endregion
#region Expressions
/**************************************************************************************************/
/* Expressions */
/**************************************************************************************************/
/*
* Expr ::= OrExpr
* OrExpr ::= AndExpr ('or' AndExpr)*
* AndExpr ::= EqualityExpr ('and' EqualityExpr)*
* EqualityExpr ::= RelationalExpr (('=' | '!=') RelationalExpr)*
* RelationalExpr ::= AdditiveExpr (('<' | '>' | '<=' | '>=') AdditiveExpr)*
* AdditiveExpr ::= MultiplicativeExpr (('+' | '-') MultiplicativeExpr)*
* MultiplicativeExpr ::= UnaryExpr (('*' | 'div' | 'mod') UnaryExpr)*
* UnaryExpr ::= ('-')* UnionExpr
*/
private Node ParseExpr()
{
return ParseSubExpr(/*callerPrec:*/0);
}
//Max depth to avoid StackOverflow
//limit the recursive call from ParseSubExpr -> ParseSubExpr
//and also ParseSubExpr->ParseUnionExpr->ParsePathExpr->...->ParseExpr->ParseSubExpr
private const int MaxParseSubExprDepth = 1024;
private int _parseSubExprDepth;
private Node ParseSubExpr(int callerPrec)
{
if (++_parseSubExprDepth > MaxParseSubExprDepth)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
throw _scanner!.CreateException(SR.Xslt_InputTooComplex);
}
}
XPathOperator op;
Node opnd;
// Check for unary operators
if (_scanner!.Kind == LexKind.Minus)
{
op = XPathOperator.UnaryMinus;
int opPrec = s_XPathOperatorPrecedence[(int)op];
_scanner.NextLex();
opnd = _builder!.Operator(op, ParseSubExpr(opPrec), default(Node));
}
else
{
opnd = ParseUnionExpr();
}
// Process binary operators
while (true)
{
op = (_scanner.Kind <= LexKind.LastOperator) ? (XPathOperator)_scanner.Kind : XPathOperator.Unknown;
int opPrec = s_XPathOperatorPrecedence[(int)op];
if (opPrec <= callerPrec)
{
break;
}
// Operator's precedence is greater than the one of our caller, so process it here
_scanner.NextLex();
opnd = _builder!.Operator(op, opnd, ParseSubExpr(/*callerPrec:*/opPrec));
}
--_parseSubExprDepth;
return opnd;
}
private static readonly int[] s_XPathOperatorPrecedence = {
/*Unknown */ 0,
/*Or */ 1,
/*And */ 2,
/*Eq */ 3,
/*Ne */ 3,
/*Lt */ 4,
/*Le */ 4,
/*Gt */ 4,
/*Ge */ 4,
/*Plus */ 5,
/*Minus */ 5,
/*Multiply */ 6,
/*Divide */ 6,
/*Modulo */ 6,
/*UnaryMinus */ 7,
/*Union */ 8, // Not used
};
/*
* UnionExpr ::= PathExpr ('|' PathExpr)*
*/
private Node ParseUnionExpr()
{
int startChar = _scanner!.LexStart;
Node opnd1 = ParsePathExpr();
if (_scanner.Kind == LexKind.Union)
{
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder!.Operator(XPathOperator.Union, default(Node), opnd1);
PopPosInfo();
while (_scanner.Kind == LexKind.Union)
{
_scanner.NextLex();
startChar = _scanner.LexStart;
Node opnd2 = ParsePathExpr();
PushPosInfo(startChar, _scanner.PrevLexEnd);
opnd1 = _builder.Operator(XPathOperator.Union, opnd1, opnd2);
PopPosInfo();
}
}
return opnd1;
}
/*
* PathExpr ::= LocationPath | FilterExpr (('/' | '//') RelativeLocationPath )?
*/
private Node ParsePathExpr()
{
// Here we distinguish FilterExpr from LocationPath - the former starts with PrimaryExpr
if (IsPrimaryExpr())
{
int startChar = _scanner!.LexStart;
Node opnd = ParseFilterExpr();
int endChar = _scanner.PrevLexEnd;
if (_scanner.Kind == LexKind.Slash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd, ParseRelativeLocationPath());
PopPosInfo();
}
else if (_scanner.Kind == LexKind.SlashSlash)
{
_scanner.NextLex();
PushPosInfo(startChar, endChar);
opnd = _builder!.JoinStep(opnd,
_builder.JoinStep(
_builder.Axis(XPathAxis.DescendantOrSelf, XPathNodeType.All, null, null),
ParseRelativeLocationPath()
)
);
PopPosInfo();
}
return opnd;
}
else
{
return ParseLocationPath();
}
}
/*
* FilterExpr ::= PrimaryExpr Predicate*
*/
private Node ParseFilterExpr()
{
int startChar = _scanner!.LexStart;
Node opnd = ParsePrimaryExpr();
int endChar = _scanner.PrevLexEnd;
while (_scanner.Kind == LexKind.LBracket)
{
PushPosInfo(startChar, endChar);
opnd = _builder!.Predicate(opnd, ParsePredicate(), /*reverseStep:*/false);
PopPosInfo();
}
return opnd;
}
private bool IsPrimaryExpr()
{
return (
_scanner!.Kind == LexKind.String ||
_scanner.Kind == LexKind.Number ||
_scanner.Kind == LexKind.Dollar ||
_scanner.Kind == LexKind.LParens ||
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner)
);
}
/*
* PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
*/
private Node ParsePrimaryExpr()
{
Debug.Assert(IsPrimaryExpr());
Node opnd;
switch (_scanner!.Kind)
{
case LexKind.String:
opnd = _builder!.String(_scanner.StringValue);
_scanner.NextLex();
break;
case LexKind.Number:
opnd = _builder!.Number(XPathConvert.StringToDouble(_scanner.RawValue));
_scanner.NextLex();
break;
case LexKind.Dollar:
int startChar = _scanner.LexStart;
_scanner.NextLex();
_scanner.CheckToken(LexKind.Name);
PushPosInfo(startChar, _scanner.LexStart + _scanner.LexSize);
opnd = _builder!.Variable(_scanner.Prefix, _scanner.Name);
PopPosInfo();
_scanner.NextLex();
break;
case LexKind.LParens:
_scanner.NextLex();
opnd = ParseExpr();
_scanner.PassToken(LexKind.RParens);
break;
default:
Debug.Assert(
_scanner.Kind == LexKind.Name && _scanner.CanBeFunction && !IsNodeType(_scanner),
"IsPrimaryExpr() returned true, but the lexeme is not recognized"
);
opnd = ParseFunctionCall();
break;
}
return opnd;
}
/*
* FunctionCall ::= FunctionName '(' (Expr (',' Expr)* )? ')'
*/
private Node ParseFunctionCall()
{
List<Node> argList = new List<Node>();
string name = _scanner!.Name;
string prefix = _scanner.Prefix;
int startChar = _scanner.LexStart;
_scanner.PassToken(LexKind.Name);
_scanner.PassToken(LexKind.LParens);
if (_scanner.Kind != LexKind.RParens)
{
while (true)
{
argList.Add(ParseExpr());
if (_scanner.Kind != LexKind.Comma)
{
_scanner.CheckToken(LexKind.RParens);
break;
}
_scanner.NextLex(); // move off the ','
}
}
_scanner.NextLex(); // move off the ')'
PushPosInfo(startChar, _scanner.PrevLexEnd);
Node result = _builder!.Function(prefix, name, argList);
PopPosInfo();
return result;
}
#endregion
/**************************************************************************************************/
/* Helper methods */
/**************************************************************************************************/
private void PushPosInfo(int startChar, int endChar)
{
_posInfo.Push(startChar);
_posInfo.Push(endChar);
}
private void PopPosInfo()
{
_posInfo.Pop();
_posInfo.Pop();
}
private void PopPosInfo(out int startChar, out int endChar)
{
endChar = _posInfo.Pop();
startChar = _posInfo.Pop();
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/MenuCommand.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.Specialized;
using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Design
{
/// <summary>
/// Represents a Windows menu or toolbar item.
/// </summary>
public class MenuCommand
{
// Events that we suface or call on
private readonly EventHandler? _execHandler;
private int _status;
private IDictionary? _properties;
/// <summary>
/// Indicates that the given command is enabled. An enabled command may
/// be selected by the user (it's not greyed out).
/// </summary>
private const int ENABLED = 0x02; //tagOLECMDF.OLECMDF_ENABLED;
/// <summary>
/// Indicates that the given command is not visible on the command bar.
/// </summary>
private const int INVISIBLE = 0x10;
/// <summary>
/// Indicates that the given command is checked in the "on" state.
/// </summary>
private const int CHECKED = 0x04; // tagOLECMDF.OLECMDF_LATCHED;
/// <summary>
/// Indicates that the given command is supported. Marking a command
/// as supported indicates that the shell will not look any further up
/// the command target chain.
/// </summary>
private const int SUPPORTED = 0x01; // tagOLECMDF.OLECMDF_SUPPORTED
/// <summary>
/// Initializes a new instance of <see cref='System.ComponentModel.Design.MenuCommand'/>.
/// </summary>
public MenuCommand(EventHandler? handler, CommandID? command)
{
_execHandler = handler;
CommandID = command;
_status = SUPPORTED | ENABLED;
}
/// <summary>
/// Gets or sets a value indicating whether this menu item is checked.
/// </summary>
public virtual bool Checked
{
get => (_status & CHECKED) != 0;
set => SetStatus(CHECKED, value);
}
/// <summary>
/// Gets or sets a value indicating whether this menu item is available.
/// </summary>
public virtual bool Enabled
{
get => (_status & ENABLED) != 0;
set => SetStatus(ENABLED, value);
}
private void SetStatus(int mask, bool value)
{
int newStatus = _status;
if (value)
{
newStatus |= mask;
}
else
{
newStatus &= ~mask;
}
if (newStatus != _status)
{
_status = newStatus;
OnCommandChanged(EventArgs.Empty);
}
}
public virtual IDictionary Properties => _properties ?? (_properties = new HybridDictionary());
/// <summary>
/// Gets or sets a value indicating whether this menu item is supported.
/// </summary>
public virtual bool Supported
{
get => (_status & SUPPORTED) != 0;
set => SetStatus(SUPPORTED, value);
}
/// <summary>
/// Gets or sets a value indicating if this menu item is visible.
/// </summary>
public virtual bool Visible
{
get => (_status & INVISIBLE) == 0;
set => SetStatus(INVISIBLE, !value);
}
/// <summary>
/// Occurs when the menu command changes.
/// </summary>
public event EventHandler? CommandChanged;
/// <summary>
/// Gets the <see cref='System.ComponentModel.Design.CommandID'/> associated with this menu command.
/// </summary>
public virtual CommandID? CommandID { get; }
/// <summary>
/// Invokes a menu item.
/// </summary>
public virtual void Invoke()
{
if (_execHandler != null)
{
try
{
_execHandler(this, EventArgs.Empty);
}
catch (CheckoutException cxe)
{
if (cxe == CheckoutException.Canceled)
return;
throw;
}
}
}
/// <summary>
/// Invokes a menu item. The default implementation of this method ignores
/// the argument, but deriving classes may override this method.
/// </summary>
public virtual void Invoke(object arg) => Invoke();
/// <summary>
/// Gets the OLE command status code for this menu item.
/// </summary>
public virtual int OleStatus => _status;
/// <summary>
/// Provides notification and is called in response to
/// a <see cref='System.ComponentModel.Design.MenuCommand.CommandChanged'/> event.
/// </summary>
protected virtual void OnCommandChanged(EventArgs e) => CommandChanged?.Invoke(this, e);
/// <summary>
/// Overrides object's ToString().
/// </summary>
public override string ToString()
{
string str = (CommandID?.ToString() ?? "") + " : ";
if ((_status & SUPPORTED) != 0)
{
str += "Supported";
}
if ((_status & ENABLED) != 0)
{
str += "|Enabled";
}
if ((_status & INVISIBLE) == 0)
{
str += "|Visible";
}
if ((_status & CHECKED) != 0)
{
str += "|Checked";
}
return str;
}
}
}
| // 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.Specialized;
using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.Design
{
/// <summary>
/// Represents a Windows menu or toolbar item.
/// </summary>
public class MenuCommand
{
// Events that we suface or call on
private readonly EventHandler? _execHandler;
private int _status;
private IDictionary? _properties;
/// <summary>
/// Indicates that the given command is enabled. An enabled command may
/// be selected by the user (it's not greyed out).
/// </summary>
private const int ENABLED = 0x02; //tagOLECMDF.OLECMDF_ENABLED;
/// <summary>
/// Indicates that the given command is not visible on the command bar.
/// </summary>
private const int INVISIBLE = 0x10;
/// <summary>
/// Indicates that the given command is checked in the "on" state.
/// </summary>
private const int CHECKED = 0x04; // tagOLECMDF.OLECMDF_LATCHED;
/// <summary>
/// Indicates that the given command is supported. Marking a command
/// as supported indicates that the shell will not look any further up
/// the command target chain.
/// </summary>
private const int SUPPORTED = 0x01; // tagOLECMDF.OLECMDF_SUPPORTED
/// <summary>
/// Initializes a new instance of <see cref='System.ComponentModel.Design.MenuCommand'/>.
/// </summary>
public MenuCommand(EventHandler? handler, CommandID? command)
{
_execHandler = handler;
CommandID = command;
_status = SUPPORTED | ENABLED;
}
/// <summary>
/// Gets or sets a value indicating whether this menu item is checked.
/// </summary>
public virtual bool Checked
{
get => (_status & CHECKED) != 0;
set => SetStatus(CHECKED, value);
}
/// <summary>
/// Gets or sets a value indicating whether this menu item is available.
/// </summary>
public virtual bool Enabled
{
get => (_status & ENABLED) != 0;
set => SetStatus(ENABLED, value);
}
private void SetStatus(int mask, bool value)
{
int newStatus = _status;
if (value)
{
newStatus |= mask;
}
else
{
newStatus &= ~mask;
}
if (newStatus != _status)
{
_status = newStatus;
OnCommandChanged(EventArgs.Empty);
}
}
public virtual IDictionary Properties => _properties ?? (_properties = new HybridDictionary());
/// <summary>
/// Gets or sets a value indicating whether this menu item is supported.
/// </summary>
public virtual bool Supported
{
get => (_status & SUPPORTED) != 0;
set => SetStatus(SUPPORTED, value);
}
/// <summary>
/// Gets or sets a value indicating if this menu item is visible.
/// </summary>
public virtual bool Visible
{
get => (_status & INVISIBLE) == 0;
set => SetStatus(INVISIBLE, !value);
}
/// <summary>
/// Occurs when the menu command changes.
/// </summary>
public event EventHandler? CommandChanged;
/// <summary>
/// Gets the <see cref='System.ComponentModel.Design.CommandID'/> associated with this menu command.
/// </summary>
public virtual CommandID? CommandID { get; }
/// <summary>
/// Invokes a menu item.
/// </summary>
public virtual void Invoke()
{
if (_execHandler != null)
{
try
{
_execHandler(this, EventArgs.Empty);
}
catch (CheckoutException cxe)
{
if (cxe == CheckoutException.Canceled)
return;
throw;
}
}
}
/// <summary>
/// Invokes a menu item. The default implementation of this method ignores
/// the argument, but deriving classes may override this method.
/// </summary>
public virtual void Invoke(object arg) => Invoke();
/// <summary>
/// Gets the OLE command status code for this menu item.
/// </summary>
public virtual int OleStatus => _status;
/// <summary>
/// Provides notification and is called in response to
/// a <see cref='System.ComponentModel.Design.MenuCommand.CommandChanged'/> event.
/// </summary>
protected virtual void OnCommandChanged(EventArgs e) => CommandChanged?.Invoke(this, e);
/// <summary>
/// Overrides object's ToString().
/// </summary>
public override string ToString()
{
string str = (CommandID?.ToString() ?? "") + " : ";
if ((_status & SUPPORTED) != 0)
{
str += "Supported";
}
if ((_status & ENABLED) != 0)
{
str += "|Enabled";
}
if ((_status & INVISIBLE) == 0)
{
str += "|Visible";
}
if ((_status & CHECKED) != 0)
{
str += "|Checked";
}
return str;
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/Performance/CodeQuality/HWIntrinsic/X86/PacketTracer/VectorPacket.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using static System.Runtime.Intrinsics.X86.Avx;
using static System.Runtime.Intrinsics.X86.Sse;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
using System.Runtime.CompilerServices;
using System;
internal struct VectorPacket256
{
public Vector256<float> Xs;
public Vector256<float> Ys;
public Vector256<float> Zs;
public Vector256<float> Lengths
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return Sqrt(DotProduct(this, this));
}
}
public readonly static int Packet256Size = 8;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(Vector256<float> init)
{
Xs = init;
Ys = init;
Zs = init;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(float xs, float ys, float zs)
{
Xs = Vector256.Create(xs);
Ys = Vector256.Create(ys);
Zs = Vector256.Create(zs);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(Vector256<float> _Xs, Vector256<float> _ys, Vector256<float> _Zs)
{
Xs = _Xs;
Ys = _ys;
Zs = _Zs;
}
// Convert AoS vectors to SoA Packet256
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe VectorPacket256(float* vectors)
{
Vector256<float> m03 = LoadVector128(&vectors[0]).ToVector256(); // load lower halves
Vector256<float> m14 = LoadVector128(&vectors[4]).ToVector256();
Vector256<float> m25 = LoadVector128(&vectors[8]).ToVector256();
m03 = InsertVector128(m03, LoadVector128(&vectors[12]), 1); // load higher halves
m14 = InsertVector128(m14, LoadVector128(&vectors[16]), 1);
m25 = InsertVector128(m25, LoadVector128(&vectors[20]), 1);
var xy = Shuffle(m14, m25, 2 << 6 | 1 << 4 | 3 << 2 | 2);
var yz = Shuffle(m03, m14, 1 << 6 | 0 << 4 | 2 << 2 | 1);
var _Xs = Shuffle(m03, xy, 2 << 6 | 0 << 4 | 3 << 2 | 0);
var _ys = Shuffle(yz, xy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var _Zs = Shuffle(yz, m25, 3 << 6 | 0 << 4 | 3 << 2 | 1);
Xs = _Xs;
Ys = _ys;
Zs = _Zs;
}
// Convert SoA VectorPacket256 to AoS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 Transpose()
{
var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var m0 = r03.GetLower();
var m1 = r14.GetLower();
var m2 = r25.GetLower();
var m3 = ExtractVector128(r03, 1);
var m4 = ExtractVector128(r14, 1);
var m5 = ExtractVector128(r25, 1);
var _Xs = Vector256.Create(m0, m1);
var _ys = Vector256.Create(m2, m3);
var _Zs = Vector256.Create(m4, m5);
return new VectorPacket256(_Xs, _ys, _Zs);
}
// Convert SoA VectorPacket256 to an incomplete AoS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 FastTranspose()
{
var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);
return new VectorPacket256(r03, r14, r25);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator +(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Add(left.Xs, right.Xs), Add(left.Ys, right.Ys), Add(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator -(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Subtract(left.Xs, right.Xs), Subtract(left.Ys, right.Ys), Subtract(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator /(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Divide(left.Xs, right.Xs), Divide(left.Ys, right.Ys), Divide(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector256<float> DotProduct(VectorPacket256 left, VectorPacket256 right)
{
var x2 = Multiply(left.Xs, right.Xs);
var y2 = Multiply(left.Ys, right.Ys);
var z2 = Multiply(left.Zs, right.Zs);
return Add(Add(x2, y2), z2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 CrossProduct(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Subtract(Multiply(left.Ys, right.Zs), Multiply(left.Zs, right.Ys)),
Subtract(Multiply(left.Zs, right.Xs), Multiply(left.Xs, right.Zs)),
Subtract(Multiply(left.Xs, right.Ys), Multiply(left.Ys, right.Xs)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator *(Vector256<float> left, VectorPacket256 right)
{
return new VectorPacket256(Multiply(left, right.Xs), Multiply(left, right.Ys), Multiply(left, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 Normalize()
{
var length = this.Lengths;
return new VectorPacket256(Divide(Xs, length), Divide(Ys, length), Divide(Zs, length));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using static System.Runtime.Intrinsics.X86.Avx;
using static System.Runtime.Intrinsics.X86.Sse;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
using System.Runtime.CompilerServices;
using System;
internal struct VectorPacket256
{
public Vector256<float> Xs;
public Vector256<float> Ys;
public Vector256<float> Zs;
public Vector256<float> Lengths
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return Sqrt(DotProduct(this, this));
}
}
public readonly static int Packet256Size = 8;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(Vector256<float> init)
{
Xs = init;
Ys = init;
Zs = init;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(float xs, float ys, float zs)
{
Xs = Vector256.Create(xs);
Ys = Vector256.Create(ys);
Zs = Vector256.Create(zs);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256(Vector256<float> _Xs, Vector256<float> _ys, Vector256<float> _Zs)
{
Xs = _Xs;
Ys = _ys;
Zs = _Zs;
}
// Convert AoS vectors to SoA Packet256
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe VectorPacket256(float* vectors)
{
Vector256<float> m03 = LoadVector128(&vectors[0]).ToVector256(); // load lower halves
Vector256<float> m14 = LoadVector128(&vectors[4]).ToVector256();
Vector256<float> m25 = LoadVector128(&vectors[8]).ToVector256();
m03 = InsertVector128(m03, LoadVector128(&vectors[12]), 1); // load higher halves
m14 = InsertVector128(m14, LoadVector128(&vectors[16]), 1);
m25 = InsertVector128(m25, LoadVector128(&vectors[20]), 1);
var xy = Shuffle(m14, m25, 2 << 6 | 1 << 4 | 3 << 2 | 2);
var yz = Shuffle(m03, m14, 1 << 6 | 0 << 4 | 2 << 2 | 1);
var _Xs = Shuffle(m03, xy, 2 << 6 | 0 << 4 | 3 << 2 | 0);
var _ys = Shuffle(yz, xy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var _Zs = Shuffle(yz, m25, 3 << 6 | 0 << 4 | 3 << 2 | 1);
Xs = _Xs;
Ys = _ys;
Zs = _Zs;
}
// Convert SoA VectorPacket256 to AoS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 Transpose()
{
var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var m0 = r03.GetLower();
var m1 = r14.GetLower();
var m2 = r25.GetLower();
var m3 = ExtractVector128(r03, 1);
var m4 = ExtractVector128(r14, 1);
var m5 = ExtractVector128(r25, 1);
var _Xs = Vector256.Create(m0, m1);
var _ys = Vector256.Create(m2, m3);
var _Zs = Vector256.Create(m4, m5);
return new VectorPacket256(_Xs, _ys, _Zs);
}
// Convert SoA VectorPacket256 to an incomplete AoS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 FastTranspose()
{
var rxy = Shuffle(Xs, Ys, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var ryz = Shuffle(Ys, Zs, 3 << 6 | 1 << 4 | 3 << 2 | 1);
var rzx = Shuffle(Zs, Xs, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r03 = Shuffle(rxy, rzx, 2 << 6 | 0 << 4 | 2 << 2 | 0);
var r14 = Shuffle(ryz, rxy, 3 << 6 | 1 << 4 | 2 << 2 | 0);
var r25 = Shuffle(rzx, ryz, 3 << 6 | 1 << 4 | 3 << 2 | 1);
return new VectorPacket256(r03, r14, r25);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator +(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Add(left.Xs, right.Xs), Add(left.Ys, right.Ys), Add(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator -(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Subtract(left.Xs, right.Xs), Subtract(left.Ys, right.Ys), Subtract(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator /(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Divide(left.Xs, right.Xs), Divide(left.Ys, right.Ys), Divide(left.Zs, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector256<float> DotProduct(VectorPacket256 left, VectorPacket256 right)
{
var x2 = Multiply(left.Xs, right.Xs);
var y2 = Multiply(left.Ys, right.Ys);
var z2 = Multiply(left.Zs, right.Zs);
return Add(Add(x2, y2), z2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 CrossProduct(VectorPacket256 left, VectorPacket256 right)
{
return new VectorPacket256(Subtract(Multiply(left.Ys, right.Zs), Multiply(left.Zs, right.Ys)),
Subtract(Multiply(left.Zs, right.Xs), Multiply(left.Xs, right.Zs)),
Subtract(Multiply(left.Xs, right.Ys), Multiply(left.Ys, right.Xs)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VectorPacket256 operator *(Vector256<float> left, VectorPacket256 right)
{
return new VectorPacket256(Multiply(left, right.Xs), Multiply(left, right.Ys), Multiply(left, right.Zs));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public VectorPacket256 Normalize()
{
var length = this.Lengths;
return new VectorPacket256(Divide(Xs, length), Divide(Ys, length), Divide(Zs, length));
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Linq/tests/LifecycleTests.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;
using System.Threading;
using Xunit;
namespace System.Linq.Tests
{
public class LifecycleTests : EnumerableTests
{
[Fact]
public void UnaryOperations_SourceEnumeratorDisposed()
{
// Using Assert.All instead of a Theory to avoid overloading the system with hundreds of thousands of distinct test cases.
IEnumerable<(Source source, Unary unary1, Unary unary2, Sink sink)> inputs =
from source in Sources()
from unary1 in UnaryOperations()
from unary2 in UnaryOperations()
from sink in Sinks()
select (source, unary1, unary2, sink);
Assert.All(inputs, input =>
{
var (source, unary1, unary2, sink) = input;
var e = new LifecycleTrackingEnumerable<int>(source.Work);
// source -> unary1 -> unary2 -> sink
bool argError = false;
try
{
sink.Work(unary2.Work(unary1.Work(e)));
}
catch (Exception exc) when (exc is ArgumentException || exc is InvalidOperationException)
{
argError = true;
}
// We expect the source's enumerator should have been constructed 0 or 1 times,
// once if there's no short-circuiting involved. Then the enumerator's Dispose
// should have been invoked the same number of times.
bool shortCircuits = argError || ShortCircuits(source, unary1, unary2, sink);
Assert.InRange(e.EnumeratorCtorCalls, shortCircuits ? 0 : 1, 1);
Assert.Equal(e.EnumeratorCtorCalls, e.EnumeratorDisposeCalls);
});
}
[Fact]
public void BinaryOperations_SourceEnumeratorsDisposed()
{
// Using Assert.All instead of a Theory to avoid overloading the system with hundreds of thousands of distinct test cases.
IEnumerable<(Source source, Unary unary, Binary binary, Sink sink)> inputs =
from source in Sources()
from unary in UnaryOperations()
from binary in BinaryOperations()
from sink in Sinks()
select (source, unary, binary, sink);
Assert.All(inputs, input =>
{
var (source, unary, binary, sink) = input;
var es = new[] { new LifecycleTrackingEnumerable<int>(source.Work), new LifecycleTrackingEnumerable<int>(source.Work) };
// ((source -> unary), (source -> unary)) -> binary -> sink
bool argError = false;
try
{
sink.Work(binary.Work(unary.Work(es[0]), unary.Work(es[1])));
}
catch (Exception exc) when (exc is ArgumentException || exc is InvalidOperationException)
{
argError = true;
}
// We expect the source's enumerator should have been constructed 0 or 1 times,
// once if there's no short-circuiting involved. Then the enumerator's Dispose
// should have been invoked the same number of times.
bool shortCircuits = argError || ShortCircuits(source, binary, unary, sink);
Assert.All(es, e =>
{
Assert.InRange(e.EnumeratorCtorCalls, shortCircuits ? 0 : 1, 1);
Assert.Equal(e.EnumeratorCtorCalls, e.EnumeratorDisposeCalls);
});
});
}
private static bool ShortCircuits(params Operation[] ops) => ops.Any(o => o.ShortCircuits);
private static IEnumerable<Source> Sources()
{
foreach (int size in new[] { 0, 1, 2 })
{
yield return new Source($"Enumerable{size}", NumberRangeGuaranteedNotCollectionType(0, size));
}
}
private static int s_nextValue = 42;
private static IEnumerable<Unary> UnaryOperations()
{
yield return new Unary(nameof(Enumerable.Append), e => e.Append(Interlocked.Increment(ref s_nextValue)));
yield return new Unary(nameof(Enumerable.AsEnumerable), e => e.AsEnumerable());
yield return new Unary(nameof(Enumerable.Cast), e => e.Cast<int>());
yield return new Unary(nameof(Enumerable.Distinct), e => e.Distinct());
yield return new Unary(nameof(Enumerable.DefaultIfEmpty), e => e.DefaultIfEmpty());
yield return new Unary(nameof(Enumerable.GroupBy), e => e.GroupBy(i => i).Select(g => g.Key));
yield return new Unary(nameof(Enumerable.GroupBy), e => e.GroupBy(i => i, i => i).Select(g => g.Key));
yield return new Unary(nameof(Enumerable.OfType), e => e.OfType<int>());
yield return new Unary(nameof(Enumerable.OrderBy), e => e.OrderBy(i => i));
yield return new Unary(nameof(Enumerable.OrderByDescending), e => e.OrderByDescending(i => i));
yield return new Unary(nameof(Enumerable.Prepend), e => e.Prepend(Interlocked.Increment(ref s_nextValue)));
yield return new Unary(nameof(Enumerable.Reverse), e => e.Reverse());
yield return new Unary(nameof(Enumerable.Select), e => e.Select(i => i));
yield return new Unary(nameof(Enumerable.Select), e => e.Select((i, index) => i));
yield return new Unary(nameof(Enumerable.SelectMany), e => e.SelectMany(i => new[] { i }));
yield return new Unary(nameof(Enumerable.SelectMany), e => e.SelectMany((i, index) => new[] { i }));
yield return new Unary(nameof(Enumerable.Skip), e => e.Skip(1));
yield return new Unary(nameof(Enumerable.SkipWhile), e => e.SkipWhile(i => true));
yield return new Unary(nameof(Enumerable.SkipWhile), e => e.SkipWhile(i => false));
yield return new Unary(nameof(Enumerable.SkipLast), e => e.SkipLast(1));
yield return new Unary(nameof(Enumerable.Take), e => e.Take(int.MaxValue - 1));
yield return new Unary(nameof(Enumerable.TakeLast), e => e.TakeLast(int.MaxValue - 1));
yield return new Unary(nameof(Enumerable.TakeWhile), e => e.TakeWhile(i => true));
yield return new Unary(nameof(Enumerable.TakeWhile), e => e.TakeWhile(i => false), shortCircuits: true);
yield return new Unary(nameof(Enumerable.ThenBy), e => e.OrderBy(i => i).ThenBy(i => i));
yield return new Unary(nameof(Enumerable.ThenByDescending), e => e.OrderByDescending(i => i).ThenByDescending(i => i));
yield return new Unary(nameof(Enumerable.Where), e => e.Where(i => true));
yield return new Unary(nameof(Enumerable.Where), e => e.Where((i, index) => false));
yield return new Unary("identity", e => e);
}
private static IEnumerable<Binary> BinaryOperations()
{
yield return new Binary(nameof(Enumerable.Concat), (e1, e2) => e1.Concat(e2));
yield return new Binary(nameof(Enumerable.Except), (e1, e2) => e1.Except(e2));
yield return new Binary(nameof(Enumerable.GroupJoin), (e1, e2) => e1.GroupJoin(e2, i => i, i => i, (i, e3) => i), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Intersect), (e1, e2) => e1.Intersect(e2));
yield return new Binary(nameof(Enumerable.Join), (e1, e2) => e1.Join(e2, i => i, i => i, (i1, i2) => i1), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Union), (e1, e2) => e1.Union(e2));
yield return new Binary(nameof(Enumerable.Zip), (e1, e2) => e1.Zip(e2).Select(i => i.First), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Zip), (e1, e2) => e1.Zip(e2, (i, j) => i), shortCircuits: true);
}
private static IEnumerable<Sink> Sinks()
{
yield return new Sink(nameof(Enumerable.All), e => e.All(i => true));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate(0, (i, j) => i + j));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate(0, (i, j) => i + j, i => i));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate((i, j) => i + j));
yield return new Sink(nameof(Enumerable.Average), e => e.Average());
yield return new Sink(nameof(Enumerable.Average), e => e.Average(i => i));
yield return new Sink(nameof(Enumerable.Any), e => e.Any(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Any), e => e.Any(i => false));
yield return new Sink(nameof(Enumerable.Contains), e => e.Contains(-1));
yield return new Sink(nameof(Enumerable.Contains), e => e.Contains(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Count), e => e.Count());
yield return new Sink(nameof(Enumerable.Count), e => e.Count(i => true));
yield return new Sink(nameof(Enumerable.ElementAt), e => e.ElementAt(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.ElementAtOrDefault), e => e.ElementAtOrDefault(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.First), e => e.First(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.First), e => e.First(i => false));
yield return new Sink(nameof(Enumerable.FirstOrDefault), e => e.FirstOrDefault(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.FirstOrDefault), e => e.FirstOrDefault(i => false));
yield return new Sink(nameof(Enumerable.Last), e => e.Last());
yield return new Sink(nameof(Enumerable.Last), e => e.Last(i => true));
yield return new Sink(nameof(Enumerable.LastOrDefault), e => e.LastOrDefault());
yield return new Sink(nameof(Enumerable.LastOrDefault), e => e.LastOrDefault(i => true));
yield return new Sink(nameof(Enumerable.LongCount), e => e.LongCount());
yield return new Sink(nameof(Enumerable.LongCount), e => e.LongCount(i => true));
yield return new Sink(nameof(Enumerable.Max), e => e.Max());
yield return new Sink(nameof(Enumerable.Max), e => e.Max(i => i));
yield return new Sink(nameof(Enumerable.Min), e => e.Min());
yield return new Sink(nameof(Enumerable.Min), e => e.Min(i => i));
yield return new Sink(nameof(Enumerable.SequenceEqual), e => e.SequenceEqual(Enumerable.Range(0, 1)), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Single), e => e.Single(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Single), e => e.Single(i => false));
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault());
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault(i => true));
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault(i => false));
yield return new Sink(nameof(Enumerable.Sum), e => e.Sum());
yield return new Sink(nameof(Enumerable.Sum), e => e.Sum(i => i));
yield return new Sink(nameof(Enumerable.ToArray), e => e.ToArray());
yield return new Sink(nameof(Enumerable.ToDictionary), e => e.ToDictionary(i => i));
yield return new Sink(nameof(Enumerable.ToDictionary), e => e.ToDictionary(i => i, i => i));
yield return new Sink(nameof(Enumerable.ToHashSet), e => e.ToHashSet());
yield return new Sink(nameof(Enumerable.ToList), e => e.ToList());
yield return new Sink(nameof(Enumerable.ToLookup), e => e.ToLookup(i => i));
yield return new Sink(nameof(Enumerable.ToLookup), e => e.ToLookup(i => i, i => i));
yield return new Sink("foreach", e => { foreach (int item in e) { } });
yield return new Sink("nop", e => { }, shortCircuits: true);
}
private sealed class LifecycleTrackingEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _source;
private int _enumeratorCtorCalls;
private int _enumeratorDisposeCalls;
public LifecycleTrackingEnumerable(IEnumerable<T> source) => _source = source;
public int EnumeratorCtorCalls => _enumeratorCtorCalls;
public int EnumeratorDisposeCalls => _enumeratorDisposeCalls;
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private sealed class Enumerator : IEnumerator<T>
{
private readonly LifecycleTrackingEnumerable<T> _enumerable;
private readonly IEnumerator<T> _enumerator;
public Enumerator(LifecycleTrackingEnumerable<T> enumerable)
{
_enumerable = enumerable;
Interlocked.Increment(ref _enumerable._enumeratorCtorCalls);
_enumerator = enumerable._source.GetEnumerator();
}
public void Dispose()
{
Interlocked.Increment(ref _enumerable._enumeratorDisposeCalls);
_enumerator.Dispose();
}
public T Current => _enumerator.Current;
object IEnumerator.Current => ((IEnumerator)_enumerator).Current;
public bool MoveNext() => _enumerator.MoveNext();
public void Reset() => throw new NotSupportedException($"LINQ operators should not invoke {nameof(Reset)}.");
}
}
private abstract class Operation
{
public Operation(string name, bool shortCircuits)
{
Name = name;
ShortCircuits = shortCircuits;
}
public string Name { get; }
public bool ShortCircuits { get; }
public override string ToString() => Name;
}
private abstract class Operation<TWork> : Operation
{
public Operation(string name, TWork operation, bool shortCircuits) : base(name, shortCircuits) => Work = operation;
public TWork Work { get; }
}
private sealed class Source : Operation<IEnumerable<int>>
{
public Source(string name, IEnumerable<int> enumerable, bool shortCircuits = false) : base(name, enumerable, shortCircuits) { }
}
private sealed class Unary : Operation<Func<IEnumerable<int>, IEnumerable<int>>>
{
public Unary(string name, Func<IEnumerable<int>, IEnumerable<int>> unary, bool shortCircuits = false) : base(name, unary, shortCircuits) { }
}
private sealed class Binary : Operation<Func<IEnumerable<int>, IEnumerable<int>, IEnumerable<int>>>
{
public Binary(string name, Func<IEnumerable<int>, IEnumerable<int>, IEnumerable<int>> binary, bool shortCircuits = false) : base(name, binary, shortCircuits) { }
}
private sealed class Sink : Operation<Action<IEnumerable<int>>>
{
public Sink(string name, Action<IEnumerable<int>> sink, bool shortCircuits = false) : base(name, sink, shortCircuits) { }
}
}
}
| // 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;
using System.Threading;
using Xunit;
namespace System.Linq.Tests
{
public class LifecycleTests : EnumerableTests
{
[Fact]
public void UnaryOperations_SourceEnumeratorDisposed()
{
// Using Assert.All instead of a Theory to avoid overloading the system with hundreds of thousands of distinct test cases.
IEnumerable<(Source source, Unary unary1, Unary unary2, Sink sink)> inputs =
from source in Sources()
from unary1 in UnaryOperations()
from unary2 in UnaryOperations()
from sink in Sinks()
select (source, unary1, unary2, sink);
Assert.All(inputs, input =>
{
var (source, unary1, unary2, sink) = input;
var e = new LifecycleTrackingEnumerable<int>(source.Work);
// source -> unary1 -> unary2 -> sink
bool argError = false;
try
{
sink.Work(unary2.Work(unary1.Work(e)));
}
catch (Exception exc) when (exc is ArgumentException || exc is InvalidOperationException)
{
argError = true;
}
// We expect the source's enumerator should have been constructed 0 or 1 times,
// once if there's no short-circuiting involved. Then the enumerator's Dispose
// should have been invoked the same number of times.
bool shortCircuits = argError || ShortCircuits(source, unary1, unary2, sink);
Assert.InRange(e.EnumeratorCtorCalls, shortCircuits ? 0 : 1, 1);
Assert.Equal(e.EnumeratorCtorCalls, e.EnumeratorDisposeCalls);
});
}
[Fact]
public void BinaryOperations_SourceEnumeratorsDisposed()
{
// Using Assert.All instead of a Theory to avoid overloading the system with hundreds of thousands of distinct test cases.
IEnumerable<(Source source, Unary unary, Binary binary, Sink sink)> inputs =
from source in Sources()
from unary in UnaryOperations()
from binary in BinaryOperations()
from sink in Sinks()
select (source, unary, binary, sink);
Assert.All(inputs, input =>
{
var (source, unary, binary, sink) = input;
var es = new[] { new LifecycleTrackingEnumerable<int>(source.Work), new LifecycleTrackingEnumerable<int>(source.Work) };
// ((source -> unary), (source -> unary)) -> binary -> sink
bool argError = false;
try
{
sink.Work(binary.Work(unary.Work(es[0]), unary.Work(es[1])));
}
catch (Exception exc) when (exc is ArgumentException || exc is InvalidOperationException)
{
argError = true;
}
// We expect the source's enumerator should have been constructed 0 or 1 times,
// once if there's no short-circuiting involved. Then the enumerator's Dispose
// should have been invoked the same number of times.
bool shortCircuits = argError || ShortCircuits(source, binary, unary, sink);
Assert.All(es, e =>
{
Assert.InRange(e.EnumeratorCtorCalls, shortCircuits ? 0 : 1, 1);
Assert.Equal(e.EnumeratorCtorCalls, e.EnumeratorDisposeCalls);
});
});
}
private static bool ShortCircuits(params Operation[] ops) => ops.Any(o => o.ShortCircuits);
private static IEnumerable<Source> Sources()
{
foreach (int size in new[] { 0, 1, 2 })
{
yield return new Source($"Enumerable{size}", NumberRangeGuaranteedNotCollectionType(0, size));
}
}
private static int s_nextValue = 42;
private static IEnumerable<Unary> UnaryOperations()
{
yield return new Unary(nameof(Enumerable.Append), e => e.Append(Interlocked.Increment(ref s_nextValue)));
yield return new Unary(nameof(Enumerable.AsEnumerable), e => e.AsEnumerable());
yield return new Unary(nameof(Enumerable.Cast), e => e.Cast<int>());
yield return new Unary(nameof(Enumerable.Distinct), e => e.Distinct());
yield return new Unary(nameof(Enumerable.DefaultIfEmpty), e => e.DefaultIfEmpty());
yield return new Unary(nameof(Enumerable.GroupBy), e => e.GroupBy(i => i).Select(g => g.Key));
yield return new Unary(nameof(Enumerable.GroupBy), e => e.GroupBy(i => i, i => i).Select(g => g.Key));
yield return new Unary(nameof(Enumerable.OfType), e => e.OfType<int>());
yield return new Unary(nameof(Enumerable.OrderBy), e => e.OrderBy(i => i));
yield return new Unary(nameof(Enumerable.OrderByDescending), e => e.OrderByDescending(i => i));
yield return new Unary(nameof(Enumerable.Prepend), e => e.Prepend(Interlocked.Increment(ref s_nextValue)));
yield return new Unary(nameof(Enumerable.Reverse), e => e.Reverse());
yield return new Unary(nameof(Enumerable.Select), e => e.Select(i => i));
yield return new Unary(nameof(Enumerable.Select), e => e.Select((i, index) => i));
yield return new Unary(nameof(Enumerable.SelectMany), e => e.SelectMany(i => new[] { i }));
yield return new Unary(nameof(Enumerable.SelectMany), e => e.SelectMany((i, index) => new[] { i }));
yield return new Unary(nameof(Enumerable.Skip), e => e.Skip(1));
yield return new Unary(nameof(Enumerable.SkipWhile), e => e.SkipWhile(i => true));
yield return new Unary(nameof(Enumerable.SkipWhile), e => e.SkipWhile(i => false));
yield return new Unary(nameof(Enumerable.SkipLast), e => e.SkipLast(1));
yield return new Unary(nameof(Enumerable.Take), e => e.Take(int.MaxValue - 1));
yield return new Unary(nameof(Enumerable.TakeLast), e => e.TakeLast(int.MaxValue - 1));
yield return new Unary(nameof(Enumerable.TakeWhile), e => e.TakeWhile(i => true));
yield return new Unary(nameof(Enumerable.TakeWhile), e => e.TakeWhile(i => false), shortCircuits: true);
yield return new Unary(nameof(Enumerable.ThenBy), e => e.OrderBy(i => i).ThenBy(i => i));
yield return new Unary(nameof(Enumerable.ThenByDescending), e => e.OrderByDescending(i => i).ThenByDescending(i => i));
yield return new Unary(nameof(Enumerable.Where), e => e.Where(i => true));
yield return new Unary(nameof(Enumerable.Where), e => e.Where((i, index) => false));
yield return new Unary("identity", e => e);
}
private static IEnumerable<Binary> BinaryOperations()
{
yield return new Binary(nameof(Enumerable.Concat), (e1, e2) => e1.Concat(e2));
yield return new Binary(nameof(Enumerable.Except), (e1, e2) => e1.Except(e2));
yield return new Binary(nameof(Enumerable.GroupJoin), (e1, e2) => e1.GroupJoin(e2, i => i, i => i, (i, e3) => i), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Intersect), (e1, e2) => e1.Intersect(e2));
yield return new Binary(nameof(Enumerable.Join), (e1, e2) => e1.Join(e2, i => i, i => i, (i1, i2) => i1), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Union), (e1, e2) => e1.Union(e2));
yield return new Binary(nameof(Enumerable.Zip), (e1, e2) => e1.Zip(e2).Select(i => i.First), shortCircuits: true);
yield return new Binary(nameof(Enumerable.Zip), (e1, e2) => e1.Zip(e2, (i, j) => i), shortCircuits: true);
}
private static IEnumerable<Sink> Sinks()
{
yield return new Sink(nameof(Enumerable.All), e => e.All(i => true));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate(0, (i, j) => i + j));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate(0, (i, j) => i + j, i => i));
yield return new Sink(nameof(Enumerable.Aggregate), e => e.Aggregate((i, j) => i + j));
yield return new Sink(nameof(Enumerable.Average), e => e.Average());
yield return new Sink(nameof(Enumerable.Average), e => e.Average(i => i));
yield return new Sink(nameof(Enumerable.Any), e => e.Any(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Any), e => e.Any(i => false));
yield return new Sink(nameof(Enumerable.Contains), e => e.Contains(-1));
yield return new Sink(nameof(Enumerable.Contains), e => e.Contains(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Count), e => e.Count());
yield return new Sink(nameof(Enumerable.Count), e => e.Count(i => true));
yield return new Sink(nameof(Enumerable.ElementAt), e => e.ElementAt(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.ElementAtOrDefault), e => e.ElementAtOrDefault(0), shortCircuits: true);
yield return new Sink(nameof(Enumerable.First), e => e.First(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.First), e => e.First(i => false));
yield return new Sink(nameof(Enumerable.FirstOrDefault), e => e.FirstOrDefault(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.FirstOrDefault), e => e.FirstOrDefault(i => false));
yield return new Sink(nameof(Enumerable.Last), e => e.Last());
yield return new Sink(nameof(Enumerable.Last), e => e.Last(i => true));
yield return new Sink(nameof(Enumerable.LastOrDefault), e => e.LastOrDefault());
yield return new Sink(nameof(Enumerable.LastOrDefault), e => e.LastOrDefault(i => true));
yield return new Sink(nameof(Enumerable.LongCount), e => e.LongCount());
yield return new Sink(nameof(Enumerable.LongCount), e => e.LongCount(i => true));
yield return new Sink(nameof(Enumerable.Max), e => e.Max());
yield return new Sink(nameof(Enumerable.Max), e => e.Max(i => i));
yield return new Sink(nameof(Enumerable.Min), e => e.Min());
yield return new Sink(nameof(Enumerable.Min), e => e.Min(i => i));
yield return new Sink(nameof(Enumerable.SequenceEqual), e => e.SequenceEqual(Enumerable.Range(0, 1)), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Single), e => e.Single(), shortCircuits: true);
yield return new Sink(nameof(Enumerable.Single), e => e.Single(i => false));
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault());
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault(i => true));
yield return new Sink(nameof(Enumerable.SingleOrDefault), e => e.SingleOrDefault(i => false));
yield return new Sink(nameof(Enumerable.Sum), e => e.Sum());
yield return new Sink(nameof(Enumerable.Sum), e => e.Sum(i => i));
yield return new Sink(nameof(Enumerable.ToArray), e => e.ToArray());
yield return new Sink(nameof(Enumerable.ToDictionary), e => e.ToDictionary(i => i));
yield return new Sink(nameof(Enumerable.ToDictionary), e => e.ToDictionary(i => i, i => i));
yield return new Sink(nameof(Enumerable.ToHashSet), e => e.ToHashSet());
yield return new Sink(nameof(Enumerable.ToList), e => e.ToList());
yield return new Sink(nameof(Enumerable.ToLookup), e => e.ToLookup(i => i));
yield return new Sink(nameof(Enumerable.ToLookup), e => e.ToLookup(i => i, i => i));
yield return new Sink("foreach", e => { foreach (int item in e) { } });
yield return new Sink("nop", e => { }, shortCircuits: true);
}
private sealed class LifecycleTrackingEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _source;
private int _enumeratorCtorCalls;
private int _enumeratorDisposeCalls;
public LifecycleTrackingEnumerable(IEnumerable<T> source) => _source = source;
public int EnumeratorCtorCalls => _enumeratorCtorCalls;
public int EnumeratorDisposeCalls => _enumeratorDisposeCalls;
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private sealed class Enumerator : IEnumerator<T>
{
private readonly LifecycleTrackingEnumerable<T> _enumerable;
private readonly IEnumerator<T> _enumerator;
public Enumerator(LifecycleTrackingEnumerable<T> enumerable)
{
_enumerable = enumerable;
Interlocked.Increment(ref _enumerable._enumeratorCtorCalls);
_enumerator = enumerable._source.GetEnumerator();
}
public void Dispose()
{
Interlocked.Increment(ref _enumerable._enumeratorDisposeCalls);
_enumerator.Dispose();
}
public T Current => _enumerator.Current;
object IEnumerator.Current => ((IEnumerator)_enumerator).Current;
public bool MoveNext() => _enumerator.MoveNext();
public void Reset() => throw new NotSupportedException($"LINQ operators should not invoke {nameof(Reset)}.");
}
}
private abstract class Operation
{
public Operation(string name, bool shortCircuits)
{
Name = name;
ShortCircuits = shortCircuits;
}
public string Name { get; }
public bool ShortCircuits { get; }
public override string ToString() => Name;
}
private abstract class Operation<TWork> : Operation
{
public Operation(string name, TWork operation, bool shortCircuits) : base(name, shortCircuits) => Work = operation;
public TWork Work { get; }
}
private sealed class Source : Operation<IEnumerable<int>>
{
public Source(string name, IEnumerable<int> enumerable, bool shortCircuits = false) : base(name, enumerable, shortCircuits) { }
}
private sealed class Unary : Operation<Func<IEnumerable<int>, IEnumerable<int>>>
{
public Unary(string name, Func<IEnumerable<int>, IEnumerable<int>> unary, bool shortCircuits = false) : base(name, unary, shortCircuits) { }
}
private sealed class Binary : Operation<Func<IEnumerable<int>, IEnumerable<int>, IEnumerable<int>>>
{
public Binary(string name, Func<IEnumerable<int>, IEnumerable<int>, IEnumerable<int>> binary, bool shortCircuits = false) : base(name, binary, shortCircuits) { }
}
private sealed class Sink : Operation<Action<IEnumerable<int>>>
{
public Sink(string name, Action<IEnumerable<int>> sink, bool shortCircuits = false) : base(name, sink, shortCircuits) { }
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/Loader/classloader/generics/regressions/123712/repro123712.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This is regression test for VSW 123712.
// Loading the type resulted in TypeLoadException.
using System;
public class Base<T>{}
public class Foo : Base<Bar>{}
public class Bar : Foo{}
public class CMain
{
public static void Indirect()
{
Bar b = new Bar();
}
public static int Main()
{
try
{
Indirect();
Console.WriteLine("PASS");
return 100;
}
catch(Exception e)
{
Console.WriteLine("FAIL: Caught unexpected exception: " + e);
return 101;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This is regression test for VSW 123712.
// Loading the type resulted in TypeLoadException.
using System;
public class Base<T>{}
public class Foo : Base<Bar>{}
public class Bar : Foo{}
public class CMain
{
public static void Indirect()
{
Bar b = new Bar();
}
public static int Main()
{
try
{
Indirect();
Console.WriteLine("PASS");
return 100;
}
catch(Exception e)
{
Console.WriteLine("FAIL: Caught unexpected exception: " + e);
return 101;
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.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.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypto
{
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjTxt2Obj", StringMarshalling = StringMarshalling.Utf8)]
internal static partial SafeAsn1ObjectHandle ObjTxt2Obj(string s);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjObj2Txt")]
private static unsafe partial int ObjObj2Txt(byte* buf, int buf_len, IntPtr a);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetObjectDefinitionByName", StringMarshalling = StringMarshalling.Utf8)]
private static partial IntPtr CryptoNative_GetObjectDefinitionByName(string friendlyName);
internal static IntPtr GetObjectDefinitionByName(string friendlyName)
{
IntPtr ret = CryptoNative_GetObjectDefinitionByName(friendlyName);
if (ret == IntPtr.Zero)
{
ErrClearError();
}
return ret;
}
// Returns shared pointers, should not be tracked as a SafeHandle.
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjNid2Obj")]
internal static partial IntPtr ObjNid2Obj(int nid);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1ObjectFree")]
internal static partial void Asn1ObjectFree(IntPtr o);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeAsn1BitString")]
internal static partial SafeAsn1BitStringHandle DecodeAsn1BitString(byte[] buf, int len);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1BitStringFree")]
internal static partial void Asn1BitStringFree(IntPtr o);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringNew")]
internal static partial SafeAsn1OctetStringHandle Asn1OctetStringNew();
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringSet")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool Asn1OctetStringSet(SafeAsn1OctetStringHandle o, byte[] d, int len);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringFree")]
internal static partial void Asn1OctetStringFree(IntPtr o);
internal static unsafe string GetOidValue(IntPtr asn1ObjectPtr)
{
// OBJ_obj2txt returns the number of bytes that should have been in the answer, but it does not accept
// a NULL buffer. The documentation says "A buffer length of 80 should be more than enough to handle
// any OID encountered in practice", so start with a buffer of size 80, and try again if required.
const int StackCapacity = 80;
byte* bufStack = stackalloc byte[StackCapacity];
int bytesNeeded = ObjObj2Txt(bufStack, StackCapacity, asn1ObjectPtr);
if (bytesNeeded < 0)
{
throw CreateOpenSslCryptographicException();
}
Debug.Assert(bytesNeeded != 0, "OBJ_obj2txt reported a zero-length response");
if (bytesNeeded < StackCapacity)
{
return Marshal.PtrToStringAnsi((IntPtr)bufStack, bytesNeeded);
}
// bytesNeeded does not count the \0 which will be written on the end (based on OpenSSL 1.0.1f),
// so make sure to leave room for it.
int initialBytesNeeded = bytesNeeded;
byte[] bufHeap = new byte[bytesNeeded + 1];
fixed (byte* buf = &bufHeap[0])
{
bytesNeeded = ObjObj2Txt(buf, bufHeap.Length, asn1ObjectPtr);
if (bytesNeeded < 0)
{
throw CreateOpenSslCryptographicException();
}
Debug.Assert(
bytesNeeded == initialBytesNeeded,
"OBJ_obj2txt changed the required number of bytes for the realloc call");
if (bytesNeeded > initialBytesNeeded)
{
// OBJ_obj2txt is demanding yet more memory
throw new CryptographicException();
}
return Marshal.PtrToStringAnsi((IntPtr)buf, bytesNeeded);
}
}
}
}
| // 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypto
{
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjTxt2Obj", StringMarshalling = StringMarshalling.Utf8)]
internal static partial SafeAsn1ObjectHandle ObjTxt2Obj(string s);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjObj2Txt")]
private static unsafe partial int ObjObj2Txt(byte* buf, int buf_len, IntPtr a);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetObjectDefinitionByName", StringMarshalling = StringMarshalling.Utf8)]
private static partial IntPtr CryptoNative_GetObjectDefinitionByName(string friendlyName);
internal static IntPtr GetObjectDefinitionByName(string friendlyName)
{
IntPtr ret = CryptoNative_GetObjectDefinitionByName(friendlyName);
if (ret == IntPtr.Zero)
{
ErrClearError();
}
return ret;
}
// Returns shared pointers, should not be tracked as a SafeHandle.
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjNid2Obj")]
internal static partial IntPtr ObjNid2Obj(int nid);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1ObjectFree")]
internal static partial void Asn1ObjectFree(IntPtr o);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeAsn1BitString")]
internal static partial SafeAsn1BitStringHandle DecodeAsn1BitString(byte[] buf, int len);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1BitStringFree")]
internal static partial void Asn1BitStringFree(IntPtr o);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringNew")]
internal static partial SafeAsn1OctetStringHandle Asn1OctetStringNew();
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringSet")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool Asn1OctetStringSet(SafeAsn1OctetStringHandle o, byte[] d, int len);
[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringFree")]
internal static partial void Asn1OctetStringFree(IntPtr o);
internal static unsafe string GetOidValue(IntPtr asn1ObjectPtr)
{
// OBJ_obj2txt returns the number of bytes that should have been in the answer, but it does not accept
// a NULL buffer. The documentation says "A buffer length of 80 should be more than enough to handle
// any OID encountered in practice", so start with a buffer of size 80, and try again if required.
const int StackCapacity = 80;
byte* bufStack = stackalloc byte[StackCapacity];
int bytesNeeded = ObjObj2Txt(bufStack, StackCapacity, asn1ObjectPtr);
if (bytesNeeded < 0)
{
throw CreateOpenSslCryptographicException();
}
Debug.Assert(bytesNeeded != 0, "OBJ_obj2txt reported a zero-length response");
if (bytesNeeded < StackCapacity)
{
return Marshal.PtrToStringAnsi((IntPtr)bufStack, bytesNeeded);
}
// bytesNeeded does not count the \0 which will be written on the end (based on OpenSSL 1.0.1f),
// so make sure to leave room for it.
int initialBytesNeeded = bytesNeeded;
byte[] bufHeap = new byte[bytesNeeded + 1];
fixed (byte* buf = &bufHeap[0])
{
bytesNeeded = ObjObj2Txt(buf, bufHeap.Length, asn1ObjectPtr);
if (bytesNeeded < 0)
{
throw CreateOpenSslCryptographicException();
}
Debug.Assert(
bytesNeeded == initialBytesNeeded,
"OBJ_obj2txt changed the required number of bytes for the realloc call");
if (bytesNeeded > initialBytesNeeded)
{
// OBJ_obj2txt is demanding yet more memory
throw new CryptographicException();
}
return Marshal.PtrToStringAnsi((IntPtr)buf, bytesNeeded);
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/X86/Avx2/GatherMaskVector256.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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
using System.Collections.Generic;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
const int N = 128;
static byte Four;
static byte Eight;
static byte invalid;
static readonly float[] floatSourceTable = new float[N];
static readonly double[] doubleSourceTable = new double[N];
static readonly int[] intSourceTable = new int[N];
static readonly long[] longSourceTable = new long[N];
static readonly int[] intIndexTable = new int[8] {1, 2, 4, 8, 16, 32, 40, 63};
static readonly long[] longIndexTable = new long[4] {2, 8, 16, 32};
static readonly int[] vector128intIndexTable = new int[4] {8, 16, 32, 63};
static readonly int[] intMaskTable = new int[8] {-1, 0, -1, 0, -1, 0, -1, 0};
static readonly long[] longMaskTable = new long[4] {-1, 0, -1, 0};
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
Four = 4;
Eight = 8;
invalid = 15;
for (int i = 0; i < N; i++)
{
floatSourceTable[i] = (float)i * 10.0f;
doubleSourceTable[i] = (double)i * 10.0;
intSourceTable[i] = i * 10;
longSourceTable[i] = i * 10;
}
Vector256<int> indexi;
Vector256<long> indexl;
Vector128<int> indexi128;
fixed (int* iptr = intIndexTable)
fixed (long* lptr = longIndexTable)
fixed (int* i128ptr = vector128intIndexTable)
{
indexi = Avx.LoadVector256(iptr);
indexl = Avx.LoadVector256(lptr);
indexi128 = Sse2.LoadVector128(i128ptr);
}
Vector256<int> maski;
Vector256<uint> maskui;
Vector256<long> maskl;
Vector256<ulong> maskul;
Vector256<float> maskf;
Vector256<double> maskd;
fixed (int* iptr = intMaskTable)
fixed (long* lptr = longMaskTable)
{
maski = Avx.LoadVector256(iptr);
maskl = Avx.LoadVector256(lptr);
maskui = maski.AsUInt32();
maskul = maskl.AsUInt64();
maskf = maski.AsSingle();
maskd = maskl.AsDouble();
}
Vector256<int> sourcei = Vector256<int>.Zero;
Vector256<uint> sourceui = Vector256<uint>.Zero;
Vector256<long> sourcel = Vector256<long>.Zero;
Vector256<ulong> sourceul = Vector256<ulong>.Zero;
Vector256<float> sourcef = Vector256<float>.Zero;
Vector256<double> sourced = Vector256<double>.Zero;
// public static unsafe Vector256<float> GatherMaskVector256(Vector256<float> source, float* baseAddress, Vector256<int> index, Vector256<float> mask, byte scale)
using (TestTable<float, int> floatTable = new TestTable<float, int>(floatSourceTable, new float[8]))
{
var vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, 4);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<float>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<float>), typeof(float*), typeof(Vector256<int>), typeof(Vector256<float>), typeof(byte)}).
Invoke(null, new object[] { sourcef, Pointer.Box(floatTable.inArrayPtr, typeof(float*)), indexi, maskf, (byte)4 });
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, Four);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with non-const scale (IMM):");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector128<int> index, Vector256<double> mask, byte scale)
using (TestTable<double, int> doubletTable = new TestTable<double, int>(doubleSourceTable, new double[4]))
{
var vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector256<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<double>), typeof(double*), typeof(Vector128<int>), typeof(Vector256<double>), typeof(byte)}).
Invoke(null, new object[] { sourced, Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexi128, maskd, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with non-const scale (IMM):");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<int> GatherMaskVector256(Vector256<int> source, int* baseAddress, Vector256<int> index, Vector256<int> mask, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[8]))
{
var vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<int>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<int>), typeof(int*), typeof(Vector256<int>), typeof(Vector256<int>), typeof(byte)}).
Invoke(null, new object[] { sourcei, Pointer.Box(intTable.inArrayPtr, typeof(int*)), indexi, maski, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<uint> GatherMaskVector256(Vector256<uint> source, uint* baseAddress, Vector256<int> index, Vector256<uint> mask, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[8]))
{
var vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<uint>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<uint>), typeof(uint*), typeof(Vector256<int>), typeof(Vector256<uint>), typeof(byte)}).
Invoke(null, new object[] { sourceui, Pointer.Box(intTable.inArrayPtr, typeof(uint*)), indexi, maskui, (byte)4 });
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector128<int> index, Vector256<long> mask, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<long>), typeof(long*), typeof(Vector128<int>), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { sourcel, Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexi128, maskl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector128<int> index, Vector256<ulong> mask, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<ulong>), typeof(ulong*), typeof(Vector128<int>), typeof(Vector256<ulong>), typeof(byte)}).
Invoke(null, new object[] { sourceul, Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexi128, maskul, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on ulong:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector256<long> index, Vector256<long> mask, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<long>), typeof(long*), typeof(Vector256<long>), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { sourcel, Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexl, maskl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on long with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with non-const scale (IMM) and Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector256<long> index, Vector256<ulong> mask, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<ulong>), typeof(ulong*), typeof(Vector256<long>), typeof(Vector256<ulong>), typeof(byte)}).
Invoke(null, new object[] { sourceul, Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexl, maskul, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on ulong with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with non-const scale (IMM) and Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector256<long> index, Vector256<double> mask, byte scale)
using (TestTable<double, long> doubletTable = new TestTable<double, long>(doubleSourceTable, new double[4]))
{
var vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector256<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<double>), typeof(double*), typeof(Vector256<long>), typeof(Vector256<double>), typeof(byte)}).
Invoke(null, new object[] { sourced, Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexl, maskd, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on double with Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with non-const scale (IMM) and Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
}
return testResult;
}
public unsafe struct TestTable<T, U> : IDisposable where T : struct where U : struct
{
public T[] inArray;
public T[] outArray;
public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle;
GCHandle outHandle;
public TestTable(T[] a, T[] b)
{
this.inArray = a;
this.outArray = b;
inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, bool> check, U[] indexArray)
{
int length = Math.Min(indexArray.Length, outArray.Length);
for (int i = 0; i < length; i++)
{
bool take = i % 2 == 0;
if ((take && !check(inArray[Convert.ToInt32(indexArray[i])], outArray[i])) ||
(!take && !EqualityComparer<T>.Default.Equals(outArray[i], default(T))))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
}
}
}
| // 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
using System.Collections.Generic;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
const int N = 128;
static byte Four;
static byte Eight;
static byte invalid;
static readonly float[] floatSourceTable = new float[N];
static readonly double[] doubleSourceTable = new double[N];
static readonly int[] intSourceTable = new int[N];
static readonly long[] longSourceTable = new long[N];
static readonly int[] intIndexTable = new int[8] {1, 2, 4, 8, 16, 32, 40, 63};
static readonly long[] longIndexTable = new long[4] {2, 8, 16, 32};
static readonly int[] vector128intIndexTable = new int[4] {8, 16, 32, 63};
static readonly int[] intMaskTable = new int[8] {-1, 0, -1, 0, -1, 0, -1, 0};
static readonly long[] longMaskTable = new long[4] {-1, 0, -1, 0};
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
Four = 4;
Eight = 8;
invalid = 15;
for (int i = 0; i < N; i++)
{
floatSourceTable[i] = (float)i * 10.0f;
doubleSourceTable[i] = (double)i * 10.0;
intSourceTable[i] = i * 10;
longSourceTable[i] = i * 10;
}
Vector256<int> indexi;
Vector256<long> indexl;
Vector128<int> indexi128;
fixed (int* iptr = intIndexTable)
fixed (long* lptr = longIndexTable)
fixed (int* i128ptr = vector128intIndexTable)
{
indexi = Avx.LoadVector256(iptr);
indexl = Avx.LoadVector256(lptr);
indexi128 = Sse2.LoadVector128(i128ptr);
}
Vector256<int> maski;
Vector256<uint> maskui;
Vector256<long> maskl;
Vector256<ulong> maskul;
Vector256<float> maskf;
Vector256<double> maskd;
fixed (int* iptr = intMaskTable)
fixed (long* lptr = longMaskTable)
{
maski = Avx.LoadVector256(iptr);
maskl = Avx.LoadVector256(lptr);
maskui = maski.AsUInt32();
maskul = maskl.AsUInt64();
maskf = maski.AsSingle();
maskd = maskl.AsDouble();
}
Vector256<int> sourcei = Vector256<int>.Zero;
Vector256<uint> sourceui = Vector256<uint>.Zero;
Vector256<long> sourcel = Vector256<long>.Zero;
Vector256<ulong> sourceul = Vector256<ulong>.Zero;
Vector256<float> sourcef = Vector256<float>.Zero;
Vector256<double> sourced = Vector256<double>.Zero;
// public static unsafe Vector256<float> GatherMaskVector256(Vector256<float> source, float* baseAddress, Vector256<int> index, Vector256<float> mask, byte scale)
using (TestTable<float, int> floatTable = new TestTable<float, int>(floatSourceTable, new float[8]))
{
var vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, 4);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<float>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<float>), typeof(float*), typeof(Vector256<int>), typeof(Vector256<float>), typeof(byte)}).
Invoke(null, new object[] { sourcef, Pointer.Box(floatTable.inArrayPtr, typeof(float*)), indexi, maskf, (byte)4 });
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, Four);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with non-const scale (IMM):");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcef, (float*)(floatTable.inArrayPtr), indexi, maskf, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on float with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector128<int> index, Vector256<double> mask, byte scale)
using (TestTable<double, int> doubletTable = new TestTable<double, int>(doubleSourceTable, new double[4]))
{
var vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector256<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<double>), typeof(double*), typeof(Vector128<int>), typeof(Vector256<double>), typeof(byte)}).
Invoke(null, new object[] { sourced, Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexi128, maskd, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with non-const scale (IMM):");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexi128, maskd, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<int> GatherMaskVector256(Vector256<int> source, int* baseAddress, Vector256<int> index, Vector256<int> mask, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[8]))
{
var vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<int>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<int>), typeof(int*), typeof(Vector256<int>), typeof(Vector256<int>), typeof(byte)}).
Invoke(null, new object[] { sourcei, Pointer.Box(intTable.inArrayPtr, typeof(int*)), indexi, maski, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcei, (int*)(intTable.inArrayPtr), indexi, maski, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on int with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<uint> GatherMaskVector256(Vector256<uint> source, uint* baseAddress, Vector256<int> index, Vector256<uint> mask, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[8]))
{
var vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<uint>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<uint>), typeof(uint*), typeof(Vector256<int>), typeof(Vector256<uint>), typeof(byte)}).
Invoke(null, new object[] { sourceui, Pointer.Box(intTable.inArrayPtr, typeof(uint*)), indexi, maskui, (byte)4 });
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceui, (uint*)(intTable.inArrayPtr), indexi, maskui, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on uint with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector128<int> index, Vector256<long> mask, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<long>), typeof(long*), typeof(Vector128<int>), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { sourcel, Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexi128, maskl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexi128, maskl, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector128<int> index, Vector256<ulong> mask, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<ulong>), typeof(ulong*), typeof(Vector128<int>), typeof(Vector256<ulong>), typeof(byte)}).
Invoke(null, new object[] { sourceul, Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexi128, maskul, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on ulong:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, vector128intIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexi128, maskul, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector256<long> index, Vector256<long> mask, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<long>), typeof(long*), typeof(Vector256<long>), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { sourcel, Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexl, maskl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on long with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with non-const scale (IMM) and Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourcel, (long*)(longTable.inArrayPtr), indexl, maskl, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector256<long> index, Vector256<ulong> mask, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[4]))
{
var vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector256<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<ulong>), typeof(ulong*), typeof(Vector256<long>), typeof(Vector256<ulong>), typeof(byte)}).
Invoke(null, new object[] { sourceul, Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexl, maskul, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on ulong with Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on ulong with non-const scale (IMM) and Vector256 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherMaskVector256(sourceul, (ulong*)(longTable.inArrayPtr), indexl, maskul, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on long with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector256<long> index, Vector256<double> mask, byte scale)
using (TestTable<double, long> doubletTable = new TestTable<double, long>(doubleSourceTable, new double[4]))
{
var vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector256<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherMaskVector256), new Type[] {typeof(Vector256<double>), typeof(double*), typeof(Vector256<long>), typeof(Vector256<double>), typeof(byte)}).
Invoke(null, new object[] { sourced, Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexl, maskd, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed with reflection on double with Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, 3);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with non-const scale (IMM) and Vector256 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherMaskVector256(sourced, (double*)(doubletTable.inArrayPtr), indexl, maskd, invalid);
Console.WriteLine("AVX2 GatherMaskVector256 failed on double with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
}
return testResult;
}
public unsafe struct TestTable<T, U> : IDisposable where T : struct where U : struct
{
public T[] inArray;
public T[] outArray;
public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle;
GCHandle outHandle;
public TestTable(T[] a, T[] b)
{
this.inArray = a;
this.outArray = b;
inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, bool> check, U[] indexArray)
{
int length = Math.Min(indexArray.Length, outArray.Length);
for (int i = 0; i < length; i++)
{
bool take = i % 2 == 0;
if ((take && !check(inArray[Convert.ToInt32(indexArray[i])], outArray[i])) ||
(!take && !EqualityComparer<T>.Default.Equals(outArray[i], default(T))))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/coreclr/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/X86Base.CoreCLR.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;
namespace System.Runtime.Intrinsics.X86
{
public abstract partial class X86Base
{
[GeneratedDllImport(RuntimeHelpers.QCall, EntryPoint = "X86BaseCpuId")]
private static unsafe partial void __cpuidex(int* cpuInfo, int functionId, int subFunctionId);
}
}
| // 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;
namespace System.Runtime.Intrinsics.X86
{
public abstract partial class X86Base
{
[GeneratedDllImport(RuntimeHelpers.QCall, EntryPoint = "X86BaseCpuId")]
private static unsafe partial void __cpuidex(int* cpuInfo, int functionId, int subFunctionId);
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/Interop/PInvoke/Generics/GenericsTest.ReadOnlySpanD.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;
unsafe partial class GenericsNative
{
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanD")]
public static extern ReadOnlySpan<double> GetReadOnlySpanD(double e00);
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanDOut")]
public static extern void GetReadOnlySpanDOut(double e00, out ReadOnlySpan<double> value);
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanDPtr")]
public static extern ref readonly ReadOnlySpan<double> GetReadOnlySpanDRef(double e00);
[DllImport(nameof(GenericsNative), EntryPoint = "AddSpanD")]
public static extern ReadOnlySpan<double> AddReadOnlySpanD(ReadOnlySpan<double> lhs, ReadOnlySpan<double> rhs);
[DllImport(nameof(GenericsNative), EntryPoint = "AddSpanDs")]
public static extern ReadOnlySpan<double> AddReadOnlySpanDs(in ReadOnlySpan<double> pValues, int count);
}
unsafe partial class GenericsTest
{
private static void TestReadOnlySpanD()
{
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanD(1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanDOut(1.0, out ReadOnlySpan<double> value3));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanDRef(1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddReadOnlySpanD(default, default));
Assert.Throws<MarshalDirectiveException>(() => {
ReadOnlySpan<double> value = default;
GenericsNative.AddReadOnlySpanDs(in value, 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.InteropServices;
using Xunit;
unsafe partial class GenericsNative
{
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanD")]
public static extern ReadOnlySpan<double> GetReadOnlySpanD(double e00);
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanDOut")]
public static extern void GetReadOnlySpanDOut(double e00, out ReadOnlySpan<double> value);
[DllImport(nameof(GenericsNative), EntryPoint = "GetSpanDPtr")]
public static extern ref readonly ReadOnlySpan<double> GetReadOnlySpanDRef(double e00);
[DllImport(nameof(GenericsNative), EntryPoint = "AddSpanD")]
public static extern ReadOnlySpan<double> AddReadOnlySpanD(ReadOnlySpan<double> lhs, ReadOnlySpan<double> rhs);
[DllImport(nameof(GenericsNative), EntryPoint = "AddSpanDs")]
public static extern ReadOnlySpan<double> AddReadOnlySpanDs(in ReadOnlySpan<double> pValues, int count);
}
unsafe partial class GenericsTest
{
private static void TestReadOnlySpanD()
{
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanD(1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanDOut(1.0, out ReadOnlySpan<double> value3));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetReadOnlySpanDRef(1.0));
Assert.Throws<MarshalDirectiveException>(() => GenericsNative.AddReadOnlySpanD(default, default));
Assert.Throws<MarshalDirectiveException>(() => {
ReadOnlySpan<double> value = default;
GenericsNative.AddReadOnlySpanDs(in value, 1);
});
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/Fakes/CircularReferences/DirectCircularDependencyB.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.DependencyInjection.Tests.Fakes
{
public class DirectCircularDependencyB
{
public DirectCircularDependencyB(DirectCircularDependencyA a)
{
}
}
}
| // 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.DependencyInjection.Tests.Fakes
{
public class DirectCircularDependencyB
{
public DirectCircularDependencyB(DirectCircularDependencyA a)
{
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Runtime/tests/System/String.SplitTests.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.Tests
{
public static class StringSplitTests
{
[Fact]
public static void SplitInvalidCount()
{
const string value = "a,b";
const int count = -1;
const StringSplitOptions options = StringSplitOptions.None;
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitInvalidOptions()
{
const string value = "a,b";
const int count = int.MaxValue;
const StringSplitOptions optionsTooLow = StringSplitOptions.None - 1;
const StringSplitOptions optionsTooHigh = (StringSplitOptions)0x04;
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, count, optionsTooHigh));
}
[Fact]
public static void SplitZeroCountEmptyResult()
{
const string value = "a,b";
const int count = 0;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitEmptyValueWithRemoveEmptyEntriesOptionEmptyResult()
{
string value = string.Empty;
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitOneCountSingleResult()
{
const string value = "a,b";
const int count = 1;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitNoMatchSingleResult()
{
const string value = "a b";
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(','));
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(","));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
private const int M = int.MaxValue;
[Theory]
[InlineData("", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 2, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 3, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 4, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', M, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.None, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 3, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 4, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', M, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.None, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.None, new[] { "", ",", })]
[InlineData(",,", ',', 3, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 4, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', M, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.None, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.None, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 3, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 4, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', M, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData(",b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.None, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', M, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.None, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.None, new[] { "", "a,b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', M, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.None, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.None, new[] { "a", "b,", })]
[InlineData("a,b,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', M, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b," })]
[InlineData("a,b,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.None, new[] { "a", "b,c" })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.None, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.None, new[] { "a", ",c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.None, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c" })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.None, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.None, new[] { "a", "b,c," })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c,", })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c,", })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.None, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c," })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c", "" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.None, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.None, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 3, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 4, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', M, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData(",second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.None, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', M, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.None, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.None, new[] { "", "first,second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', M, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.None, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.None, new[] { "first", "second,", })]
[InlineData("first,second,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', M, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second," })]
[InlineData("first,second,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.None, new[] { "first", "second,third" })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.None, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.None, new[] { "first", ",third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.None, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third" })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.None, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.None, new[] { "first", "second,third," })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third,", })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third,", })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.None, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third," })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third", "" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("Foo Bar Baz", ' ', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "Foo", "Bar Baz" })]
[InlineData("Foo Bar Baz", ' ', M, StringSplitOptions.None, new[] { "Foo", "Bar", "Baz" })]
[InlineData("a", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.TrimEntries, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData("a", ',', 1, StringSplitOptions.None, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.TrimEntries, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a" })]
[InlineData(" ", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" ", ',', 1, StringSplitOptions.None, new string[] { " " })]
[InlineData(" ", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[] { " " })]
[InlineData(" ", ',', 1, StringSplitOptions.TrimEntries, new string[] { "" })]
[InlineData(" ", ',', 1, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.None, new string[] { " a", ", b, c " })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[] { " a", " b, c " })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.TrimEntries, new string[] { "a", ", b, c" })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a", "b, c" })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.None, new string[] { " a", "", " b, c " })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[] { " a", " b", " c " })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.TrimEntries, new string[] { "a", "", "b, c" })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a", "b", "c" })]
public static void SplitCharSeparator(string value, char separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
Assert.Equal(expected, value.Split(separator.ToString(), count, options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, count, options));
if (count == int.MaxValue)
{
Assert.Equal(expected, value.Split(separator, options));
Assert.Equal(expected, value.Split(new[] { separator }, options));
Assert.Equal(expected, value.Split(separator.ToString(), options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, options));
}
if (options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator, count));
Assert.Equal(expected, value.Split(new[] { separator }, count));
Assert.Equal(expected, value.Split(separator.ToString(), count));
}
if (count == int.MaxValue && options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator));
Assert.Equal(expected, value.Split(new[] { separator }));
Assert.Equal(expected, value.Split(separator.ToString()));
}
}
[Theory]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", "", M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.None, new[] { "", "ab", "ab", "a" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab", "ab", "a" })]
[InlineData("this, is, a, string, with some spaces", ", ", M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with some spaces" })]
[InlineData("Monday, Tuesday, Wednesday, Thursday, Friday", ",", M, StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "", "Wednesday", "", "Thursday", "Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.RemoveEmptyEntries, new[] { "Monday", " Tuesday", "\r", " Wednesday", "\n", " Thursday", " Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" })]
public static void SplitStringSeparator(string value, string separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
if (count == int.MaxValue)
{
Assert.Equal(expected, value.Split(separator, options));
Assert.Equal(expected, value.Split(new[] { separator }, options));
}
if (options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator, count));
}
if (count == int.MaxValue && options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator));
}
}
[Fact]
public static void SplitNullCharArraySeparator_BindsToCharArrayOverload()
{
string value = "a b c";
string[] expected = new[] { "a", "b", "c" };
// Ensure Split(null) compiles successfully as a call to Split(char[])
Assert.Equal(expected, value.Split(null));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new char[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new char[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ' }, M, StringSplitOptions.None, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's' }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "a", "", "", "tring", "", "with", "", "ome", "", "pace", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's', 'a' }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "", "", "", "", "tring", "", "with", "", "ome", "", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "a", "tring", "with", "ome", "pace" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.None, new[] { "thi" /*s*/, "" /*,*/, " i" /*s*/, "" /*,*/, " " /*a*/, "" /*,*/, " " /*s*/, "tring" /*,*/, " with " /*s*/, "ome " /*s*/, "p" /*a*/, "ce" /*s*/, "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", " i", " ", " ", "tring", " with ", "ome ", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.TrimEntries, new[] { "thi", "", "i", "", "", "", "", "tring", "with", "ome", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
public static void SplitCharArraySeparator(string value, char[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
Assert.Equal(expected, value.Split(ToStringArray(separators), count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new string[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { null }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { "" }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { " " }, M, StringSplitOptions.None, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s" }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "a", "", "", "tring", "", "with", "", "ome", "", "pace", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s", "a" }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "", "", "", "", "tring", "", "with", "", "ome", "", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "a", "tring", "with", "ome", "pace" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.None, new[] { "thi" /*s*/, "" /*,*/, " i" /*s*/, "" /*,*/, " " /*a*/, "" /*,*/, " " /*s*/, "tring" /*,*/, " with " /*s*/, "ome " /*s*/, "p" /*a*/, "ce" /*s*/, "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", " i", " ", " ", "tring", " with ", "ome ", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.TrimEntries, new[] { "thi", "", "i", "", "", "", "", "tring", "with", "ome", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.None, new[] { "this", " is", " a", "", "tring", " with", "ome", "paces", " " })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", " is", " a", "tring", " with", "ome", "paces", " " })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.TrimEntries, new[] { "this", "is", "a", "", "tring", "with", "ome", "paces", "" })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "this", "is", "a", "tring", "with", "ome", "paces" })]
public static void SplitStringArraySeparator(string value, string[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
}
private static string[] ToStringArray(char[] source)
{
if (source == null)
return null;
string[] result = new string[source.Length];
for (int i = 0; i < source.Length; i++)
{
result[i] = source[i].ToString();
}
return result;
}
}
}
| // 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.Tests
{
public static class StringSplitTests
{
[Fact]
public static void SplitInvalidCount()
{
const string value = "a,b";
const int count = -1;
const StringSplitOptions options = StringSplitOptions.None;
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(',', count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { ',' }, count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(",", count, options));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitInvalidOptions()
{
const string value = "a,b";
const int count = int.MaxValue;
const StringSplitOptions optionsTooLow = StringSplitOptions.None - 1;
const StringSplitOptions optionsTooHigh = (StringSplitOptions)0x04;
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(',', count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { ',' }, count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(",", count, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, optionsTooHigh));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, count, optionsTooLow));
AssertExtensions.Throws<ArgumentException>("options", () => value.Split(new[] { "," }, count, optionsTooHigh));
}
[Fact]
public static void SplitZeroCountEmptyResult()
{
const string value = "a,b";
const int count = 0;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitEmptyValueWithRemoveEmptyEntriesOptionEmptyResult()
{
string value = string.Empty;
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitOneCountSingleResult()
{
const string value = "a,b";
const int count = 1;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(',', count));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitNoMatchSingleResult()
{
const string value = "a b";
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(','));
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(","));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
private const int M = int.MaxValue;
[Theory]
[InlineData("", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 2, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 3, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 4, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', M, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.None, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 3, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 4, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', M, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.None, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.None, new[] { "", ",", })]
[InlineData(",,", ',', 3, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 4, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', M, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.None, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.None, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 3, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 4, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', M, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData(",b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.None, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', M, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.None, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.None, new[] { "", "a,b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', M, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.None, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.None, new[] { "a", "b,", })]
[InlineData("a,b,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', M, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b," })]
[InlineData("a,b,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.None, new[] { "a", "b,c" })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.None, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.None, new[] { "a", ",c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.None, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c" })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.None, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.None, new[] { "a", "b,c," })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c,", })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c,", })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.None, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c," })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c", "" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.None, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.None, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 3, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 4, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', M, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData(",second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.None, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', M, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.None, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.None, new[] { "", "first,second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', M, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.None, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.None, new[] { "first", "second,", })]
[InlineData("first,second,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', M, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second," })]
[InlineData("first,second,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.None, new[] { "first", "second,third" })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.None, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.None, new[] { "first", ",third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.None, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third" })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.None, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.None, new[] { "first", "second,third," })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third,", })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third,", })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.None, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third," })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third", "" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("Foo Bar Baz", ' ', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "Foo", "Bar Baz" })]
[InlineData("Foo Bar Baz", ' ', M, StringSplitOptions.None, new[] { "Foo", "Bar", "Baz" })]
[InlineData("a", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.TrimEntries, new string[0])]
[InlineData("a", ',', 0, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData("a", ',', 1, StringSplitOptions.None, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.TrimEntries, new string[] { "a" })]
[InlineData("a", ',', 1, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a" })]
[InlineData(" ", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" ", ',', 0, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" ", ',', 1, StringSplitOptions.None, new string[] { " " })]
[InlineData(" ", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[] { " " })]
[InlineData(" ", ',', 1, StringSplitOptions.TrimEntries, new string[] { "" })]
[InlineData(" ", ',', 1, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[0])]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.None, new string[] { " a", ", b, c " })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[] { " a", " b, c " })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.TrimEntries, new string[] { "a", ", b, c" })]
[InlineData(" a,, b, c ", ',', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a", "b, c" })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.None, new string[] { " a", "", " b, c " })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[] { " a", " b", " c " })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.TrimEntries, new string[] { "a", "", "b, c" })]
[InlineData(" a,, b, c ", ',', 3, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new string[] { "a", "b", "c" })]
public static void SplitCharSeparator(string value, char separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
Assert.Equal(expected, value.Split(separator.ToString(), count, options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, count, options));
if (count == int.MaxValue)
{
Assert.Equal(expected, value.Split(separator, options));
Assert.Equal(expected, value.Split(new[] { separator }, options));
Assert.Equal(expected, value.Split(separator.ToString(), options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, options));
}
if (options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator, count));
Assert.Equal(expected, value.Split(new[] { separator }, count));
Assert.Equal(expected, value.Split(separator.ToString(), count));
}
if (count == int.MaxValue && options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator));
Assert.Equal(expected, value.Split(new[] { separator }));
Assert.Equal(expected, value.Split(separator.ToString()));
}
}
[Theory]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", "", M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.None, new[] { "", "ab", "ab", "a" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab", "ab", "a" })]
[InlineData("this, is, a, string, with some spaces", ", ", M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with some spaces" })]
[InlineData("Monday, Tuesday, Wednesday, Thursday, Friday", ",", M, StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "", "Wednesday", "", "Thursday", "Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.RemoveEmptyEntries, new[] { "Monday", " Tuesday", "\r", " Wednesday", "\n", " Thursday", " Friday" })]
[InlineData("Monday, Tuesday,\r, Wednesday,\n, Thursday, Friday", ",", M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" })]
public static void SplitStringSeparator(string value, string separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
if (count == int.MaxValue)
{
Assert.Equal(expected, value.Split(separator, options));
Assert.Equal(expected, value.Split(new[] { separator }, options));
}
if (options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator, count));
}
if (count == int.MaxValue && options == StringSplitOptions.None)
{
Assert.Equal(expected, value.Split(separator));
}
}
[Fact]
public static void SplitNullCharArraySeparator_BindsToCharArrayOverload()
{
string value = "a b c";
string[] expected = new[] { "a", "b", "c" };
// Ensure Split(null) compiles successfully as a call to Split(char[])
Assert.Equal(expected, value.Split(null));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new char[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new char[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ' }, M, StringSplitOptions.None, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's' }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "a", "", "", "tring", "", "with", "", "ome", "", "pace", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's', 'a' }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "", "", "", "", "tring", "", "with", "", "ome", "", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "a", "tring", "with", "ome", "pace" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.None, new[] { "thi" /*s*/, "" /*,*/, " i" /*s*/, "" /*,*/, " " /*a*/, "" /*,*/, " " /*s*/, "tring" /*,*/, " with " /*s*/, "ome " /*s*/, "p" /*a*/, "ce" /*s*/, "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", " i", " ", " ", "tring", " with ", "ome ", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.TrimEntries, new[] { "thi", "", "i", "", "", "", "", "tring", "with", "ome", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', 's', 'a' }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
public static void SplitCharArraySeparator(string value, char[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
Assert.Equal(expected, value.Split(ToStringArray(separators), count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new string[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { null }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { "" }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { " " }, M, StringSplitOptions.None, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s" }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "a", "", "", "tring", "", "with", "", "ome", "", "pace", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s", "a" }, M, StringSplitOptions.None, new[] { "thi", "", "", "i", "", "", "", "", "", "", "tring", "", "with", "", "ome", "", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this,", "is,", "a,", "string,", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "a", "tring", "with", "ome", "pace" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", " ", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.None, new[] { "thi" /*s*/, "" /*,*/, " i" /*s*/, "" /*,*/, " " /*a*/, "" /*,*/, " " /*s*/, "tring" /*,*/, " with " /*s*/, "ome " /*s*/, "p" /*a*/, "ce" /*s*/, "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "thi", " i", " ", " ", "tring", " with ", "ome ", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.TrimEntries, new[] { "thi", "", "i", "", "", "", "", "tring", "with", "ome", "p", "ce", "" })]
[InlineData("this, is, a, string, with some spaces", new[] { ",", "s", "a" }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "thi", "i", "tring", "with", "ome", "p", "ce" })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.None, new[] { "this", " is", " a", "", "tring", " with", "ome", "paces", " " })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", " is", " a", "tring", " with", "ome", "paces", " " })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.TrimEntries, new[] { "this", "is", "a", "", "tring", "with", "ome", "paces", "" })]
[InlineData("this, is, a, string, with some spaces, ", new[] { ",", " s" }, M, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries, new[] { "this", "is", "a", "tring", "with", "ome", "paces" })]
public static void SplitStringArraySeparator(string value, string[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
}
private static string[] ToStringArray(char[] source)
{
if (source == null)
return null;
string[] result = new string[source.Length];
for (int i = 0; i < source.Length; i++)
{
result[i] = source[i].ToString();
}
return result;
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OtherCertificateFormat.xml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Formats.Asn1;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.Pkcs.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct OtherCertificateFormat
{
internal string OtherCertFormat;
internal ReadOnlyMemory<byte> OtherCert;
internal void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}
internal void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
try
{
writer.WriteObjectIdentifier(OtherCertFormat);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
try
{
writer.WriteEncodedValue(OtherCert.Span);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
writer.PopSequence(tag);
}
internal static OtherCertificateFormat Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}
internal static OtherCertificateFormat Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);
DecodeCore(ref reader, expectedTag, encoded, out OtherCertificateFormat decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
}
internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
try
{
DecodeCore(ref reader, expectedTag, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
decoded = default;
AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;
decoded.OtherCertFormat = sequenceReader.ReadObjectIdentifier();
tmpSpan = sequenceReader.ReadEncodedValue();
decoded.OtherCert = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
sequenceReader.ThrowIfNotEmpty();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Formats.Asn1;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.Pkcs.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct OtherCertificateFormat
{
internal string OtherCertFormat;
internal ReadOnlyMemory<byte> OtherCert;
internal void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}
internal void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);
try
{
writer.WriteObjectIdentifier(OtherCertFormat);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
try
{
writer.WriteEncodedValue(OtherCert.Span);
}
catch (ArgumentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
writer.PopSequence(tag);
}
internal static OtherCertificateFormat Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}
internal static OtherCertificateFormat Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);
DecodeCore(ref reader, expectedTag, encoded, out OtherCertificateFormat decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
}
internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
try
{
DecodeCore(ref reader, expectedTag, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out OtherCertificateFormat decoded)
{
decoded = default;
AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;
decoded.OtherCertFormat = sequenceReader.ReadObjectIdentifier();
tmpSpan = sequenceReader.ReadEncodedValue();
decoded.OtherCert = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
sequenceReader.ThrowIfNotEmpty();
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.DuplicateTokenEx_SafeTokenHandle.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
internal static partial class Interop
{
internal static partial class Advapi32
{
[GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool DuplicateTokenEx(
SafeTokenHandle ExistingTokenHandle,
TokenAccessLevels DesiredAccess,
IntPtr TokenAttributes,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
System.Security.Principal.TokenType TokenType,
ref SafeTokenHandle? DuplicateTokenHandle);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
internal static partial class Interop
{
internal static partial class Advapi32
{
[GeneratedDllImport(Interop.Libraries.Advapi32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool DuplicateTokenEx(
SafeTokenHandle ExistingTokenHandle,
TokenAccessLevels DesiredAccess,
IntPtr TokenAttributes,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
System.Security.Principal.TokenType TokenType,
ref SafeTokenHandle? DuplicateTokenHandle);
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Common/tests/System/Xml/XPath/XPathExpressionTests/EvaluateTests.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;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Xunit;
using XPathTests.Common;
namespace XPathTests.XPathExpressionTests
{
public class EvaluateTests
{
private const string xml = @"<DocumentElement>
<Level1 Data='0'>
<Name>first</Name>
<Level2 Data='1'></Level2>
</Level1>
<Level1 Data='1'>
<Name>second</Name>
<Level2 Data='2'></Level2>
</Level1>
<Level1 Data='2'>
<Name>third</Name>
<Level2 Data='3'></Level2>
</Level1>
<Level1 Data='3'>
<Name>last</Name>
<Level2 Data='4'></Level2>
</Level1>
</DocumentElement>";
private static void EvaluateTestNonCompiled<T>(string toEvaluate, T expected)
{
var navigator = Utils.CreateNavigator(xml);
var result = navigator.Evaluate(toEvaluate);
var convertedResult = Convert.ChangeType(result, typeof(T));
Assert.Equal(expected, convertedResult);
}
private static void EvaluateTestCompiledXPathExpression<T>(string toEvaluate, T expected)
{
var navigator = Utils.CreateNavigator(xml);
var xPathExpression = XPathExpression.Compile(toEvaluate);
var result = navigator.Evaluate(xPathExpression);
var convertedResult = Convert.ChangeType(result, typeof(T));
Assert.Equal(expected, convertedResult);
}
private static void EvaluateTestsBoth<T>(string toEvaluate, T expected)
{
EvaluateTestNonCompiled(toEvaluate, expected);
EvaluateTestCompiledXPathExpression(toEvaluate, expected);
}
private static void EvaluateTestsErrors(string toEvaluate, string exceptionString)
{
Assert.Throws<XPathException>(() => EvaluateTestCompiledXPathExpression<object>(toEvaluate, null));
Assert.Throws<XPathException>(() => EvaluateTestNonCompiled<object>(toEvaluate, null));
}
/// <summary>
/// Pass in valid XPath Expression (return type = String)
/// Priority: 0
/// </summary>
[Fact]
public static void Variation_1()
{
EvaluateTestsBoth("string(1)", "1");
}
/// <summary>
/// Pass in valid XPath Expression (return type = Number)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_2()
{
EvaluateTestsBoth("number('1')", 1);
}
/// <summary>
/// Pass in valid XPath Expression (return type = Boolean)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_3()
{
EvaluateTestsBoth("true()", true);
}
/// <summary>
/// Pass in empty String
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_5()
{
EvaluateTestsErrors(string.Empty, "Xp_NodeSetExpected");
}
/// <summary>
/// Pass in invalid XPath Expression (wrong syntax)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_6()
{
EvaluateTestsErrors("string(1, 2)", "Xp_InvalidNumArgs");
}
private static void EvaluateTestNonCompiledNodeset(string toEvaluate, string[] expected)
{
var navigator = Utils.CreateNavigator(xml);
var iter = (XPathNodeIterator)navigator.Evaluate(toEvaluate);
foreach (var e in expected)
{
iter.MoveNext();
Assert.Equal(e, iter.Current.Value.Trim());
}
}
private static void EvaluateTestCompiledNodeset(string toEvaluate, string[] expected)
{
var navigator = Utils.CreateNavigator(xml);
var xPathExpression = XPathExpression.Compile(toEvaluate);
var iter = (XPathNodeIterator)navigator.Evaluate(xPathExpression);
foreach (var e in expected)
{
iter.MoveNext();
Assert.Equal(e, iter.Current.Value.Trim());
}
}
/// <summary>
/// Pass in valid XPath Expression
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_7()
{
EvaluateTestCompiledNodeset("DocumentElement/child::*", new[] { "first", "second", "third", "last" });
EvaluateTestNonCompiledNodeset("DocumentElement/child::*", new[] { "first", "second", "third", "last" });
}
/// <summary>
/// Pass in NULL
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_9()
{
EvaluateTestsErrors(null, "Xp_ExprExpected");
}
/// <summary>
/// Pass in invalid XPath Expression (wrong syntax)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_10()
{
EvaluateTestsErrors("DocumentElement/child:::*", "Xp_InvalidToken");
}
/// <summary>
/// Pass in two different XPath Expression in a row
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_11()
{
var navigator = Utils.CreateNavigator(xml);
navigator.Evaluate("child::*");
navigator.Evaluate("descendant::*");
}
/// <summary>
/// Pass in valid XPath Expression, then empty string
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_12()
{
var navigator = Utils.CreateNavigator(xml);
navigator.Select("/DocumentElement/child::*");
Assert.Throws<XPathException>(() => navigator.Select(string.Empty));
}
}
public class XPathEvaluateTests
{
[Fact]
public static void EvaluateTextNode_1()
{
XElement element = XElement.Parse("<element>Text.</element>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("Text.", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_2()
{
XElement element = XElement.Parse("<root>1<element></element>2</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()[1]");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("1", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_3()
{
XElement element = XElement.Parse("<root>1<element></element>2</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()[2]");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("2", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_4()
{
XElement element = XElement.Parse("<root>1<element>2</element><element>3</element>4</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/element/text()[1]");
Assert.Equal(2, result.Cast<XText>().Count());
Assert.Equal("2", result.Cast<XText>().First().ToString());
Assert.Equal("3", result.Cast<XText>().Last().ToString());
}
}
}
| // 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;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Xunit;
using XPathTests.Common;
namespace XPathTests.XPathExpressionTests
{
public class EvaluateTests
{
private const string xml = @"<DocumentElement>
<Level1 Data='0'>
<Name>first</Name>
<Level2 Data='1'></Level2>
</Level1>
<Level1 Data='1'>
<Name>second</Name>
<Level2 Data='2'></Level2>
</Level1>
<Level1 Data='2'>
<Name>third</Name>
<Level2 Data='3'></Level2>
</Level1>
<Level1 Data='3'>
<Name>last</Name>
<Level2 Data='4'></Level2>
</Level1>
</DocumentElement>";
private static void EvaluateTestNonCompiled<T>(string toEvaluate, T expected)
{
var navigator = Utils.CreateNavigator(xml);
var result = navigator.Evaluate(toEvaluate);
var convertedResult = Convert.ChangeType(result, typeof(T));
Assert.Equal(expected, convertedResult);
}
private static void EvaluateTestCompiledXPathExpression<T>(string toEvaluate, T expected)
{
var navigator = Utils.CreateNavigator(xml);
var xPathExpression = XPathExpression.Compile(toEvaluate);
var result = navigator.Evaluate(xPathExpression);
var convertedResult = Convert.ChangeType(result, typeof(T));
Assert.Equal(expected, convertedResult);
}
private static void EvaluateTestsBoth<T>(string toEvaluate, T expected)
{
EvaluateTestNonCompiled(toEvaluate, expected);
EvaluateTestCompiledXPathExpression(toEvaluate, expected);
}
private static void EvaluateTestsErrors(string toEvaluate, string exceptionString)
{
Assert.Throws<XPathException>(() => EvaluateTestCompiledXPathExpression<object>(toEvaluate, null));
Assert.Throws<XPathException>(() => EvaluateTestNonCompiled<object>(toEvaluate, null));
}
/// <summary>
/// Pass in valid XPath Expression (return type = String)
/// Priority: 0
/// </summary>
[Fact]
public static void Variation_1()
{
EvaluateTestsBoth("string(1)", "1");
}
/// <summary>
/// Pass in valid XPath Expression (return type = Number)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_2()
{
EvaluateTestsBoth("number('1')", 1);
}
/// <summary>
/// Pass in valid XPath Expression (return type = Boolean)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_3()
{
EvaluateTestsBoth("true()", true);
}
/// <summary>
/// Pass in empty String
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_5()
{
EvaluateTestsErrors(string.Empty, "Xp_NodeSetExpected");
}
/// <summary>
/// Pass in invalid XPath Expression (wrong syntax)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_6()
{
EvaluateTestsErrors("string(1, 2)", "Xp_InvalidNumArgs");
}
private static void EvaluateTestNonCompiledNodeset(string toEvaluate, string[] expected)
{
var navigator = Utils.CreateNavigator(xml);
var iter = (XPathNodeIterator)navigator.Evaluate(toEvaluate);
foreach (var e in expected)
{
iter.MoveNext();
Assert.Equal(e, iter.Current.Value.Trim());
}
}
private static void EvaluateTestCompiledNodeset(string toEvaluate, string[] expected)
{
var navigator = Utils.CreateNavigator(xml);
var xPathExpression = XPathExpression.Compile(toEvaluate);
var iter = (XPathNodeIterator)navigator.Evaluate(xPathExpression);
foreach (var e in expected)
{
iter.MoveNext();
Assert.Equal(e, iter.Current.Value.Trim());
}
}
/// <summary>
/// Pass in valid XPath Expression
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_7()
{
EvaluateTestCompiledNodeset("DocumentElement/child::*", new[] { "first", "second", "third", "last" });
EvaluateTestNonCompiledNodeset("DocumentElement/child::*", new[] { "first", "second", "third", "last" });
}
/// <summary>
/// Pass in NULL
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_9()
{
EvaluateTestsErrors(null, "Xp_ExprExpected");
}
/// <summary>
/// Pass in invalid XPath Expression (wrong syntax)
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_10()
{
EvaluateTestsErrors("DocumentElement/child:::*", "Xp_InvalidToken");
}
/// <summary>
/// Pass in two different XPath Expression in a row
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_11()
{
var navigator = Utils.CreateNavigator(xml);
navigator.Evaluate("child::*");
navigator.Evaluate("descendant::*");
}
/// <summary>
/// Pass in valid XPath Expression, then empty string
/// Priority: 1
/// </summary>
[Fact]
public static void Variation_12()
{
var navigator = Utils.CreateNavigator(xml);
navigator.Select("/DocumentElement/child::*");
Assert.Throws<XPathException>(() => navigator.Select(string.Empty));
}
}
public class XPathEvaluateTests
{
[Fact]
public static void EvaluateTextNode_1()
{
XElement element = XElement.Parse("<element>Text.</element>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("Text.", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_2()
{
XElement element = XElement.Parse("<root>1<element></element>2</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()[1]");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("1", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_3()
{
XElement element = XElement.Parse("<root>1<element></element>2</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/text()[2]");
Assert.Equal(1, result.Cast<XText>().Count());
Assert.Equal("2", result.Cast<XText>().First().ToString());
}
[Fact]
public static void EvaluateTextNode_4()
{
XElement element = XElement.Parse("<root>1<element>2</element><element>3</element>4</root>");
IEnumerable result = (IEnumerable)element.XPathEvaluate("/element/text()[1]");
Assert.Equal(2, result.Cast<XText>().Count());
Assert.Equal("2", result.Cast<XText>().First().ToString());
Assert.Equal("3", result.Cast<XText>().Last().ToString());
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/Generics/Exceptions/general_struct_static01.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="general_struct_static01.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="general_struct_static01.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/Regression/CLR-x86-JIT/v2.1/b608198/b608198.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
/*
QFE regression TC for AV while optimizing away basic blocks that
are not used which contain switch statements.
*/
class TEST
{
public static int Main()
{
int SSS;
try
{
goto LB1;
LB7:
goto LB4;
LB1:
SSS = 0;
goto LB9;
LB3:
goto LB4;
LB4:
goto LB13;
LB9:
switch (SSS)
{
case 0:
goto LB7;
case 1:
goto LB3;
case 2:
goto LB4;
}
goto LB13;
}
finally
{
}
LB13:
System.Console.WriteLine("END");
System.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.
//
/*
QFE regression TC for AV while optimizing away basic blocks that
are not used which contain switch statements.
*/
class TEST
{
public static int Main()
{
int SSS;
try
{
goto LB1;
LB7:
goto LB4;
LB1:
SSS = 0;
goto LB9;
LB3:
goto LB4;
LB4:
goto LB13;
LB9:
switch (SSS)
{
case 0:
goto LB7;
case 1:
goto LB3;
case 2:
goto LB4;
}
goto LB13;
}
finally
{
}
LB13:
System.Console.WriteLine("END");
System.Console.WriteLine("!!!!!!!!!!!!! PASSED !!!!!!!!!!!!!");
return 100;
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/Interop/ObjectiveC/AutoReleaseTest/autorelease.mm | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <Foundation/Foundation.h>
#include <xplatform.h>
volatile int NumReleaseCalls = 0;
@interface AutoReleaseTest : NSObject
- (void)release;
@end
@implementation AutoReleaseTest : NSObject
- (void)release
{
NumReleaseCalls++;
[super release];
}
@end
extern "C" DLL_EXPORT AutoReleaseTest* STDMETHODCALLTYPE initObject()
{
return [[AutoReleaseTest alloc] init];
}
extern "C" DLL_EXPORT void STDMETHODCALLTYPE autoreleaseObject(AutoReleaseTest* art)
{
[art autorelease];
}
extern "C" DLL_EXPORT int STDMETHODCALLTYPE getNumReleaseCalls()
{
return NumReleaseCalls;
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <Foundation/Foundation.h>
#include <xplatform.h>
volatile int NumReleaseCalls = 0;
@interface AutoReleaseTest : NSObject
- (void)release;
@end
@implementation AutoReleaseTest : NSObject
- (void)release
{
NumReleaseCalls++;
[super release];
}
@end
extern "C" DLL_EXPORT AutoReleaseTest* STDMETHODCALLTYPE initObject()
{
return [[AutoReleaseTest alloc] init];
}
extern "C" DLL_EXPORT void STDMETHODCALLTYPE autoreleaseObject(AutoReleaseTest* art)
{
[art autorelease];
}
extern "C" DLL_EXPORT int STDMETHODCALLTYPE getNumReleaseCalls()
{
return NumReleaseCalls;
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/mono/wasm/runtime/types/emscripten.ts | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
export declare interface ManagedPointer {
__brandManagedPointer: "ManagedPointer"
}
export declare interface NativePointer {
__brandNativePointer: "NativePointer"
}
export declare interface VoidPtr extends NativePointer {
__brand: "VoidPtr"
}
export declare interface CharPtr extends NativePointer {
__brand: "CharPtr"
}
export declare interface Int32Ptr extends NativePointer {
__brand: "Int32Ptr"
}
export declare interface CharPtrPtr extends NativePointer {
__brand: "CharPtrPtr"
}
export declare interface EmscriptenModule {
HEAP8: Int8Array,
HEAP16: Int16Array;
HEAP32: Int32Array;
HEAPU8: Uint8Array;
HEAPU16: Uint16Array;
HEAPU32: Uint32Array;
HEAPF32: Float32Array;
HEAPF64: Float64Array;
// this should match emcc -s EXPORTED_FUNCTIONS
_malloc(size: number): VoidPtr;
_free(ptr: VoidPtr): void;
// this should match emcc -s EXPORTED_RUNTIME_METHODS
print(message: string): void;
printErr(message: string): void;
ccall<T>(ident: string, returnType?: string | null, argTypes?: string[], args?: any[], opts?: any): T;
cwrap<T extends Function>(ident: string, returnType: string, argTypes?: string[], opts?: any): T;
cwrap<T extends Function>(ident: string, ...args: any[]): T;
setValue(ptr: VoidPtr, value: number, type: string, noSafe?: number | boolean): void;
setValue(ptr: Int32Ptr, value: number, type: string, noSafe?: number | boolean): void;
getValue(ptr: number, type: string, noSafe?: number | boolean): number;
UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string;
UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string;
FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string;
FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string;
FS_readFile(filename: string, opts: any): any;
removeRunDependency(id: string): void;
addRunDependency(id: string): void;
ready: Promise<unknown>;
preInit?: (() => any)[];
preRun?: (() => any)[];
postRun?: (() => any)[];
onAbort?: { (error: any): void };
onRuntimeInitialized?: () => any;
instantiateWasm: (imports: any, successCallback: Function) => any;
}
export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
export declare interface ManagedPointer {
__brandManagedPointer: "ManagedPointer"
}
export declare interface NativePointer {
__brandNativePointer: "NativePointer"
}
export declare interface VoidPtr extends NativePointer {
__brand: "VoidPtr"
}
export declare interface CharPtr extends NativePointer {
__brand: "CharPtr"
}
export declare interface Int32Ptr extends NativePointer {
__brand: "Int32Ptr"
}
export declare interface CharPtrPtr extends NativePointer {
__brand: "CharPtrPtr"
}
export declare interface EmscriptenModule {
HEAP8: Int8Array,
HEAP16: Int16Array;
HEAP32: Int32Array;
HEAPU8: Uint8Array;
HEAPU16: Uint16Array;
HEAPU32: Uint32Array;
HEAPF32: Float32Array;
HEAPF64: Float64Array;
// this should match emcc -s EXPORTED_FUNCTIONS
_malloc(size: number): VoidPtr;
_free(ptr: VoidPtr): void;
// this should match emcc -s EXPORTED_RUNTIME_METHODS
print(message: string): void;
printErr(message: string): void;
ccall<T>(ident: string, returnType?: string | null, argTypes?: string[], args?: any[], opts?: any): T;
cwrap<T extends Function>(ident: string, returnType: string, argTypes?: string[], opts?: any): T;
cwrap<T extends Function>(ident: string, ...args: any[]): T;
setValue(ptr: VoidPtr, value: number, type: string, noSafe?: number | boolean): void;
setValue(ptr: Int32Ptr, value: number, type: string, noSafe?: number | boolean): void;
getValue(ptr: number, type: string, noSafe?: number | boolean): number;
UTF8ToString(ptr: CharPtr, maxBytesToRead?: number): string;
UTF8ArrayToString(u8Array: Uint8Array, idx?: number, maxBytesToRead?: number): string;
FS_createPath(parent: string, path: string, canRead?: boolean, canWrite?: boolean): string;
FS_createDataFile(parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string;
FS_readFile(filename: string, opts: any): any;
removeRunDependency(id: string): void;
addRunDependency(id: string): void;
ready: Promise<unknown>;
preInit?: (() => any)[];
preRun?: (() => any)[];
postRun?: (() => any)[];
onAbort?: { (error: any): void };
onRuntimeInitialized?: () => any;
instantiateWasm: (imports: any, successCallback: Function) => any;
}
export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; | -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/mono/mono/utils/mono-math-c.c | // This file bridges C++ to C runtime math functions
// without any chance of a C++ library dependency.
// In time it can probably be removed.
#include "config.h"
#include "glib.h"
#define MONO_MATH_DECLARE_ALL 1
#include "mono-math.h"
#if defined (__cplusplus) && !defined (_MSC_VER)
#error This file should be compiled as C.
#endif
int mono_isfinite_float (float a) { return isfinite (a); }
int mono_isfinite_double (double a) { return isfinite (a); }
int mono_isinf_float (float a) { return isinf (a); }
int mono_isinf_double (double a) { return isinf (a); }
int mono_isnan_float (float a) { return isnan (a); }
int mono_isnan_double (double a) { return isnan (a); }
int mono_isunordered_float (float a, float b) { return isunordered (a, b); }
int mono_isunordered_double (double a, double b) { return isunordered (a, b); }
int mono_signbit_float (float a) { return signbit (a); }
int mono_signbit_double (double a) { return signbit (a); }
float mono_trunc_float (float a) { return trunc (a); }
double mono_trunc_double (double a) { return trunc (a); }
| // This file bridges C++ to C runtime math functions
// without any chance of a C++ library dependency.
// In time it can probably be removed.
#include "config.h"
#include "glib.h"
#define MONO_MATH_DECLARE_ALL 1
#include "mono-math.h"
#if defined (__cplusplus) && !defined (_MSC_VER)
#error This file should be compiled as C.
#endif
int mono_isfinite_float (float a) { return isfinite (a); }
int mono_isfinite_double (double a) { return isfinite (a); }
int mono_isinf_float (float a) { return isinf (a); }
int mono_isinf_double (double a) { return isinf (a); }
int mono_isnan_float (float a) { return isnan (a); }
int mono_isnan_double (double a) { return isnan (a); }
int mono_isunordered_float (float a, float b) { return isunordered (a, b); }
int mono_isunordered_double (double a, double b) { return isunordered (a, b); }
int mono_signbit_float (float a) { return signbit (a); }
int mono_signbit_double (double a) { return signbit (a); }
float mono_trunc_float (float a) { return trunc (a); }
double mono_trunc_double (double a) { return trunc (a); }
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/infoset-quote-single.xml | <!--
Description: The kind of quotation marks (single or double) used to quote attribute values is not significant.
Expect: !Error
-->
<feed xmlns='http://www.w3.org/2005/Atom'>
<title>Example Feed</title>
<link href='http://contoso.com/'/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href='http://contoso.com/2003/12/13/atom03'/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| <!--
Description: The kind of quotation marks (single or double) used to quote attribute values is not significant.
Expect: !Error
-->
<feed xmlns='http://www.w3.org/2005/Atom'>
<title>Example Feed</title>
<link href='http://contoso.com/'/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href='http://contoso.com/2003/12/13/atom03'/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApiV2/XsltSettings13.xsl | <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<xsl:value-of select="document('')"/>
</xsl:template>
</xsl:stylesheet> | <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<xsl:value-of select="document('')"/>
</xsl:template>
</xsl:stylesheet> | -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/Regression/JitBlue/DevDiv_461649/Input.xml | <?xml version="1.0" encoding="UTF-8"?>
<root>
<bla test="20.0 20.0 20.0 20.0 20.0"/>
</root> | <?xml version="1.0" encoding="UTF-8"?>
<root>
<bla test="20.0 20.0 20.0 20.0 20.0"/>
</root> | -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyDoublingBySelectedScalarSaturateHigh.Vector128.Int16.Vector64.Int16.3.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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
var test = new ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
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 ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3
{
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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1;
public Vector64<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3 testClass)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(_fld1, _fld2, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly byte Imm = 3;
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector64<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector64<Int16> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[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.MultiplyDoublingBySelectedScalarSaturateHigh(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
3
);
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(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh), new Type[] { typeof(Vector128<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh), new Type[] { typeof(Vector128<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
_clsVar1,
_clsVar2,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pClsVar1)),
AdvSimd.LoadVector64((Int16*)(pClsVar2)),
3
);
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<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(op1, op2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(op1, op2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3);
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 ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector64<Int16>* pFld2 = &test._fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(_fld1, _fld2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3);
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 = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(&test._fld1)),
AdvSimd.LoadVector64((Int16*)(&test._fld2)),
3
);
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<Int16> firstOp, Vector64<Int16> secondOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyDoublingSaturateHigh(firstOp[i], secondOp[Imm]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh)}<Int16>(Vector128<Int16>, Vector64<Int16>, 3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
var test = new ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
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 ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3
{
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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1;
public Vector64<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3 testClass)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(_fld1, _fld2, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly byte Imm = 3;
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector64<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector64<Int16> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[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.MultiplyDoublingBySelectedScalarSaturateHigh(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
3
);
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(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh), new Type[] { typeof(Vector128<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh), new Type[] { typeof(Vector128<Int16>), typeof(Vector64<Int16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
_clsVar1,
_clsVar2,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int16>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pClsVar1)),
AdvSimd.LoadVector64((Int16*)(pClsVar2)),
3
);
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<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr);
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(op1, op2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(op1, op2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3);
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 ImmBinaryOpTest__MultiplyDoublingBySelectedScalarSaturateHigh_Vector128_Int16_Vector64_Int16_3();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector64<Int16>* pFld2 = &test._fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(_fld1, _fld2, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector64<Int16>* pFld2 = &_fld2)
{
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector64((Int16*)(pFld2)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3);
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 = AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh(
AdvSimd.LoadVector128((Int16*)(&test._fld1)),
AdvSimd.LoadVector64((Int16*)(&test._fld2)),
3
);
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<Int16> firstOp, Vector64<Int16> secondOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyDoublingSaturateHigh(firstOp[i], secondOp[Imm]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingBySelectedScalarSaturateHigh)}<Int16>(Vector128<Int16>, Vector64<Int16>, 3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/jit64/opt/cse/mixedexpr1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
//((a+b)+c)
//permutations for ((a+b)+c)
//((a+b)+c)
//(c+(a+b))
//(a+b)
//(b+a)
//a
//b
//(b+a)
//(a+b)
//c
//(a+(b+c))
//(b+(a+c))
//(b+c)
//(c+b)
//b
//c
//(c+b)
//(b+c)
//(a+c)
//(c+a)
//a
//c
//(c+a)
//(a+c)
//(c+(a+b))
//((a+b)+c)
//((s.a+s.b)+s.c)
//permutations for ((s.a+s.b)+s.c)
//((s.a+s.b)+s.c)
//(s.c+(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.c
//(s.a+(s.b+s.c))
//(s.b+(s.a+s.c))
//(s.b+s.c)
//(s.c+s.b)
//s.b
//s.c
//(s.c+s.b)
//(s.b+s.c)
//(s.a+s.c)
//(s.c+s.a)
//s.a
//s.c
//(s.c+s.a)
//(s.a+s.c)
//(s.c+(s.a+s.b))
//((s.a+s.b)+s.c)
//((ar[0]+ar[1])+ar[2])
//permutations for ((ar[0]+ar[1])+ar[2])
//((ar[0]+ar[1])+ar[2])
//(ar[2]+(ar[0]+ar[1]))
//(ar[0]+ar[1])
//(ar[1]+ar[0])
//ar[0]
//ar[1]
//(ar[1]+ar[0])
//(ar[0]+ar[1])
//ar[2]
//(ar[0]+(ar[1]+ar[2]))
//(ar[1]+(ar[0]+ar[2]))
//(ar[1]+ar[2])
//(ar[2]+ar[1])
//ar[1]
//ar[2]
//(ar[2]+ar[1])
//(ar[1]+ar[2])
//(ar[0]+ar[2])
//(ar[2]+ar[0])
//ar[0]
//ar[2]
//(ar[2]+ar[0])
//(ar[0]+ar[2])
//(ar[2]+(ar[0]+ar[1]))
//((ar[0]+ar[1])+ar[2])
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//permutations for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(a+(b*((c*c)-(c+d))))
//((b*((c*c)-(c+d)))+a)
//a
//(b*((c*c)-(c+d)))
//(((c*c)-(c+d))*b)
//b
//((c*c)-(c+d))
//(c*c)
//(c*c)
//c
//c
//(c*c)
//(c*c)
//(c+d)
//(d+c)
//c
//d
//(d+c)
//(c+d)
//(c*c)
//((c*c)-(c+d))
//(((c*c)-(c+d))*b)
//(b*((c*c)-(c+d)))
//((b*((c*c)-(c+d)))+a)
//(a+(b*((c*c)-(c+d))))
//(((a*a)+a)+(a*b))
//((a*b)+((a*a)+a))
//((a*a)+a)
//(a+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//a
//(a+(a*a))
//((a*a)+a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*a)+(a+(a*b)))
//(a+((a*a)+(a*b)))
//(a+(a*b))
//((a*b)+a)
//a
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+a)
//(a+(a*b))
//((a*a)+(a*b))
//((a*b)+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+(a*a))
//((a*a)+(a*b))
//((a*b)+((a*a)+a))
//(((a*a)+a)+(a*b))
//(a+(b*((c*c)-(c+d))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(((abc+c)-(a-(ad*a)))+r)
//(r+((abc+c)-(a-(ad*a))))
//((abc+c)-(a-(ad*a)))
//(abc+c)
//(c+abc)
//abc
//c
//(c+abc)
//(abc+c)
//(a-(ad*a))
//a
//(ad*a)
//(a*ad)
//ad
//a
//(a*ad)
//(ad*a)
//a
//(a-(ad*a))
//(abc+c)
//((abc+c)-(a-(ad*a)))
//r
//(r+((abc+c)-(a-(ad*a))))
//(((abc+c)-(a-(ad*a)))+r)
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//permutations for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a)
//a
//(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))
//b
//(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))
//(((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c)
//c
//((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))
//(((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e))
//(d-e)
//d
//e
//d
//(d-e)
//((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//(f+((f-a)+(a*(b-(c*(d-(e*f)))))))
//((f-a)+(a*(b-(c*(d-(e*f))))))
//((a*(b-(c*(d-(e*f)))))+(f-a))
//(f-a)
//f
//a
//f
//(f-a)
//(a*(b-(c*(d-(e*f)))))
//((b-(c*(d-(e*f))))*a)
//a
//(b-(c*(d-(e*f))))
//b
//(c*(d-(e*f)))
//((d-(e*f))*c)
//c
//(d-(e*f))
//d
//(e*f)
//(f*e)
//e
//f
//(f*e)
//(e*f)
//d
//(d-(e*f))
//((d-(e*f))*c)
//(c*(d-(e*f)))
//b
//(b-(c*(d-(e*f))))
//((b-(c*(d-(e*f))))*a)
//(a*(b-(c*(d-(e*f)))))
//((a*(b-(c*(d-(e*f)))))+(f-a))
//((f-a)+(a*(b-(c*(d-(e*f))))))
//f
//((f-a)+((a*(b-(c*(d-(e*f)))))+f))
//((a*(b-(c*(d-(e*f)))))+((f-a)+f))
//((a*(b-(c*(d-(e*f)))))+f)
//(f+(a*(b-(c*(d-(e*f))))))
//(a*(b-(c*(d-(e*f)))))
//((b-(c*(d-(e*f))))*a)
//a
//(b-(c*(d-(e*f))))
//b
//(c*(d-(e*f)))
//((d-(e*f))*c)
//c
//(d-(e*f))
//d
//(e*f)
//(f*e)
//e
//f
//(f*e)
//(e*f)
//d
//(d-(e*f))
//((d-(e*f))*c)
//(c*(d-(e*f)))
//b
//(b-(c*(d-(e*f))))
//((b-(c*(d-(e*f))))*a)
//(a*(b-(c*(d-(e*f)))))
//f
//(f+(a*(b-(c*(d-(e*f))))))
//((a*(b-(c*(d-(e*f)))))+f)
//((f-a)+f)
//(f+(f-a))
//(f-a)
//f
//a
//f
//(f-a)
//f
//(f+(f-a))
//((f-a)+f)
//(f+((f-a)+(a*(b-(c*(d-(e*f)))))))
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//(a*ab)
//(ab*a)
//a
//ab
//(ab*a)
//(a*ab)
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))
//(((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e))
//((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))
//(((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c)
//(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))
//b
//(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))
//((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a)
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
int d = return_int(false, -17);
int e = return_int(false, -9);
int ad = return_int(false, 30);
int[] ar = new int[5];
ar[0] = return_int(false, -67);
ar[1] = return_int(false, -72);
ar[2] = return_int(false, 9);
class_s s = new class_s();
s.a = return_int(false, 57);
s.b = return_int(false, 35);
s.c = return_int(false, 47);
int abc = return_int(false, 10);
int r = return_int(false, 34);
int ab = return_int(false, 78);
int b = return_int(false, -19);
int c = return_int(false, -31);
int a = return_int(false, -42);
int f = return_int(false, -8);
int v;
v = ((a + b) + c);
if (v != -92)
{
Console.WriteLine("test0: for ((a+b)+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + (a + b));
if (v != -92)
{
Console.WriteLine("test1: for (c+(a+b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + b);
if (v != -61)
{
Console.WriteLine("test2: for (a+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + a);
if (v != -61)
{
Console.WriteLine("test3: for (b+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + a);
if (v != -61)
{
Console.WriteLine("test4: for (b+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + b);
if (v != -61)
{
Console.WriteLine("test5: for (a+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b + c));
if (v != -92)
{
Console.WriteLine("test6: for (a+(b+c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + (a + c));
if (v != -92)
{
Console.WriteLine("test7: for (b+(a+c)) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, -6);
v = (b + c);
if (v != -50)
{
Console.WriteLine("test8: for (b+c) failed actual value {0} ", v);
ret = ret + 1;
}
e = return_int(false, 54);
v = (c + b);
if (v != -50)
{
Console.WriteLine("test9: for (c+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + b);
if (v != -50)
{
Console.WriteLine("test10: for (c+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + c);
if (v != -50)
{
Console.WriteLine("test11: for (b+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + c);
if (v != -73)
{
Console.WriteLine("test12: for (a+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + a);
if (v != -73)
{
Console.WriteLine("test13: for (c+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + a);
if (v != -73)
{
Console.WriteLine("test14: for (c+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + c);
if (v != -73)
{
Console.WriteLine("test15: for (a+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + (a + b));
if (v != -92)
{
Console.WriteLine("test16: for (c+(a+b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a + b) + c);
if (v != -92)
{
Console.WriteLine("test17: for ((a+b)+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((s.a + s.b) + s.c);
if (v != 86)
{
Console.WriteLine("test18: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != 86)
{
Console.WriteLine("test19: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != 92)
{
Console.WriteLine("test20: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != 92)
{
Console.WriteLine("test21: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != 92)
{
Console.WriteLine("test22: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != 92)
{
Console.WriteLine("test23: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + (s.b + s.c));
if (v != 86)
{
Console.WriteLine("test24: for (s.a+(s.b+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + (s.a + s.c));
if (v != 86)
{
Console.WriteLine("test25: for (s.b+(s.a+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 29)
{
Console.WriteLine("test26: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.b);
if (v != 29)
{
Console.WriteLine("test27: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.b);
if (v != 29)
{
Console.WriteLine("test28: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 29)
{
Console.WriteLine("test29: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != 51)
{
Console.WriteLine("test30: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != 51)
{
Console.WriteLine("test31: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != 51)
{
Console.WriteLine("test32: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != 51)
{
Console.WriteLine("test33: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != 86)
{
Console.WriteLine("test34: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((s.a + s.b) + s.c);
if (v != 86)
{
Console.WriteLine("test35: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((ar[0] + ar[1]) + ar[2]);
if (v != -130)
{
Console.WriteLine("test36: for ((ar[0]+ar[1])+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + (ar[0] + ar[1]));
if (v != -130)
{
Console.WriteLine("test37: for (ar[2]+(ar[0]+ar[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[1]);
if (v != -139)
{
Console.WriteLine("test38: for (ar[0]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[0]);
if (v != -139)
{
Console.WriteLine("test39: for (ar[1]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, -4);
v = (ar[1] + ar[0]);
if (v != -139)
{
Console.WriteLine("test40: for (ar[1]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[1]);
if (v != -139)
{
Console.WriteLine("test41: for (ar[0]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + (ar[1] + ar[2]));
if (v != -130)
{
Console.WriteLine("test42: for (ar[0]+(ar[1]+ar[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + (ar[0] + ar[2]));
if (v != -130)
{
Console.WriteLine("test43: for (ar[1]+(ar[0]+ar[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[2]);
if (v != -63)
{
Console.WriteLine("test44: for (ar[1]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[1]);
if (v != -63)
{
Console.WriteLine("test45: for (ar[2]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[1]);
if (v != -63)
{
Console.WriteLine("test46: for (ar[2]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[2]);
if (v != -63)
{
Console.WriteLine("test47: for (ar[1]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[2]);
if (v != -58)
{
Console.WriteLine("test48: for (ar[0]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
s.b = return_int(false, 33);
v = (ar[2] + ar[0]);
if (v != -58)
{
Console.WriteLine("test49: for (ar[2]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[0]);
if (v != -58)
{
Console.WriteLine("test50: for (ar[2]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[2]);
if (v != -58)
{
Console.WriteLine("test51: for (ar[0]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + (ar[0] + ar[1]));
if (v != -130)
{
Console.WriteLine("test52: for (ar[2]+(ar[0]+ar[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((ar[0] + ar[1]) + ar[2]);
if (v != -130)
{
Console.WriteLine("test53: for ((ar[0]+ar[1])+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 12);
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != 9758117)
{
Console.WriteLine("test54: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != 9758117)
{
Console.WriteLine("test55: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -21733)
{
Console.WriteLine("test56: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test57: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -19213)
{
Console.WriteLine("test58: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * ((c * c) - (c + d)));
if (v != -19171)
{
Console.WriteLine("test59: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((c * c) - (c + d)) * b);
if (v != -19171)
{
Console.WriteLine("test60: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 1009)
{
Console.WriteLine("test61: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test62: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test63: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test64: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test65: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -48)
{
Console.WriteLine("test66: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -48)
{
Console.WriteLine("test67: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -48)
{
Console.WriteLine("test68: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -48)
{
Console.WriteLine("test69: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test70: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 1009)
{
Console.WriteLine("test71: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((c * c) - (c + d)) * b);
if (v != -19171)
{
Console.WriteLine("test72: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * ((c * c) - (c + d)));
if (v != -19171)
{
Console.WriteLine("test73: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -19213)
{
Console.WriteLine("test74: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test75: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a * a) + a) + (a * b));
if (v != 2520)
{
Console.WriteLine("test76: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 2520)
{
Console.WriteLine("test77: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 1722)
{
Console.WriteLine("test78: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 1722)
{
Console.WriteLine("test79: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 12);
ad = return_int(false, 23);
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test80: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test81: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test82: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test83: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 1722)
{
Console.WriteLine("test84: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 1722)
{
Console.WriteLine("test85: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test86: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test87: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test88: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test89: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a + (a * b)));
if (v != 2520)
{
Console.WriteLine("test90: for ((a*a)+(a+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + ((a * a) + (a * b)));
if (v != 2520)
{
Console.WriteLine("test91: for (a+((a*a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != 756)
{
Console.WriteLine("test92: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + a);
if (v != 756)
{
Console.WriteLine("test93: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test94: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test95: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test96: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test97: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
e = return_int(false, 11);
v = ((a * b) + a);
if (v != 756)
{
Console.WriteLine("test98: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != 756)
{
Console.WriteLine("test99: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 2562)
{
Console.WriteLine("test100: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 2562)
{
Console.WriteLine("test101: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test102: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test103: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test104: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test105: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test106: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 8);
v = (b * a);
if (v != 798)
{
Console.WriteLine("test107: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test108: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test109: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 2562)
{
Console.WriteLine("test110: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 2562)
{
Console.WriteLine("test111: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 2520)
{
Console.WriteLine("test112: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a * a) + a) + (a * b));
if (v != 2520)
{
Console.WriteLine("test113: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test114: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
c = return_int(false, 32);
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -21733)
{
Console.WriteLine("test115: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != -848)
{
Console.WriteLine("test116: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 99);
v = (r + ((abc + c) - (a - (ad * a))));
if (v != -848)
{
Console.WriteLine("test117: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
ar[0] = return_int(false, -13);
s.c = return_int(false, 47);
v = ((abc + c) - (a - (ad * a)));
if (v != -882)
{
Console.WriteLine("test118: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test119: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + abc);
if (v != 42)
{
Console.WriteLine("test120: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + abc);
if (v != 42)
{
Console.WriteLine("test121: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test122: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a - (ad * a));
if (v != 924)
{
Console.WriteLine("test123: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ad * a);
if (v != -966)
{
Console.WriteLine("test124: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != -966)
{
Console.WriteLine("test125: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != -966)
{
Console.WriteLine("test126: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ad * a);
if (v != -966)
{
Console.WriteLine("test127: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a - (ad * a));
if (v != 924)
{
Console.WriteLine("test128: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test129: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((abc + c) - (a - (ad * a)));
if (v != -882)
{
Console.WriteLine("test130: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (r + ((abc + c) - (a - (ad * a))));
if (v != -848)
{
Console.WriteLine("test131: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != -848)
{
Console.WriteLine("test132: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != 18429584)
{
Console.WriteLine("test133: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != 18429584)
{
Console.WriteLine("test134: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))));
if (v != 133723422)
{
Console.WriteLine("test135: for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))) * a);
if (v != 133723422)
{
Console.WriteLine("test136: for ((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)))));
if (v != -3183891)
{
Console.WriteLine("test137: for (b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))));
if (v != 3183872)
{
Console.WriteLine("test138: for (c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))) * c);
if (v != 3183872)
{
Console.WriteLine("test139: for (((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)));
if (v != 99496)
{
Console.WriteLine("test140: for ((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)) + (d - e));
if (v != 99496)
{
Console.WriteLine("test141: for (((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - e);
if (v != -28)
{
Console.WriteLine("test142: for (d-e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - e);
if (v != -28)
{
Console.WriteLine("test143: for (d-e) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab));
if (v != 99524)
{
Console.WriteLine("test144: for ((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 96248)
{
Console.WriteLine("test145: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + ((f - a) + (a * (b - (c * (d - (e * f)))))));
if (v != 96248)
{
Console.WriteLine("test146: for (f+((f-a)+(a*(b-(c*(d-(e*f))))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + (a * (b - (c * (d - (e * f))))));
if (v != 96256)
{
Console.WriteLine("test147: for ((f-a)+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + (f - a));
if (v != 96256)
{
Console.WriteLine("test148: for ((a*(b-(c*(d-(e*f)))))+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != 34)
{
Console.WriteLine("test149: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != 34)
{
Console.WriteLine("test150: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test151: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test152: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test153: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test154: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test155: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test156: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test157: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test158: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test159: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test160: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test161: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test162: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test163: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test164: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
s.b = return_int(false, -51);
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test165: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test166: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + (f - a));
if (v != 96256)
{
Console.WriteLine("test167: for ((a*(b-(c*(d-(e*f)))))+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + (a * (b - (c * (d - (e * f))))));
if (v != 96256)
{
Console.WriteLine("test168: for ((f-a)+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + ((a * (b - (c * (d - (e * f))))) + f));
if (v != 96248)
{
Console.WriteLine("test169: for ((f-a)+((a*(b-(c*(d-(e*f)))))+f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + ((f - a) + f));
if (v != 96248)
{
Console.WriteLine("test170: for ((a*(b-(c*(d-(e*f)))))+((f-a)+f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + f);
if (v != 96214)
{
Console.WriteLine("test171: for ((a*(b-(c*(d-(e*f)))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (a * (b - (c * (d - (e * f))))));
if (v != 96214)
{
Console.WriteLine("test172: for (f+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test173: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test174: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test175: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
r = return_int(false, -10);
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test176: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test177: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test178: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test179: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test180: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test181: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test182: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test183: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
abc = return_int(false, 68);
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test184: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test185: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
ar[0] = return_int(false, -46);
r = return_int(false, 65);
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test186: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test187: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test188: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (a * (b - (c * (d - (e * f))))));
if (v != 96214)
{
Console.WriteLine("test189: for (f+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + f);
if (v != 96214)
{
Console.WriteLine("test190: for ((a*(b-(c*(d-(e*f)))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + f);
if (v != 26)
{
Console.WriteLine("test191: for ((f-a)+f) failed actual value {0} ", v);
ret = ret + 1;
}
f = return_int(false, -56);
v = (f + (f - a));
if (v != -70)
{
Console.WriteLine("test192: for (f+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != -14)
{
Console.WriteLine("test193: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != -14)
{
Console.WriteLine("test194: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (f - a));
if (v != -70)
{
Console.WriteLine("test195: for (f+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + f);
if (v != -70)
{
Console.WriteLine("test196: for ((f-a)+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + ((f - a) + (a * (b - (c * (d - (e * f)))))));
if (v != 805784)
{
Console.WriteLine("test197: for (f+((f-a)+(a*(b-(c*(d-(e*f))))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 805784)
{
Console.WriteLine("test198: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 2);
v = (a * ab);
if (v != -3276)
{
Console.WriteLine("test199: for (a*ab) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ab * a);
if (v != -3276)
{
Console.WriteLine("test200: for (ab*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ab * a);
if (v != -3276)
{
Console.WriteLine("test201: for (ab*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ab);
if (v != -3276)
{
Console.WriteLine("test202: for (a*ab) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 805784)
{
Console.WriteLine("test203: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 16);
v = ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab));
if (v != 809060)
{
Console.WriteLine("test204: for ((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)) + (d - e));
if (v != 809032)
{
Console.WriteLine("test205: for (((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)));
if (v != 809032)
{
Console.WriteLine("test206: for ((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))) * c);
if (v != 25889024)
{
Console.WriteLine("test207: for (((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))));
if (v != 25889024)
{
Console.WriteLine("test208: for (c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)))));
if (v != -25889043)
{
Console.WriteLine("test209: for (b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))) * a);
if (v != 1087339806)
{
Console.WriteLine("test210: for ((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))));
if (v != 1087339806)
{
Console.WriteLine("test211: for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))) failed actual value {0} ", v);
ret = ret + 1;
}
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 a;
public int b;
public int c;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
//((a+b)+c)
//permutations for ((a+b)+c)
//((a+b)+c)
//(c+(a+b))
//(a+b)
//(b+a)
//a
//b
//(b+a)
//(a+b)
//c
//(a+(b+c))
//(b+(a+c))
//(b+c)
//(c+b)
//b
//c
//(c+b)
//(b+c)
//(a+c)
//(c+a)
//a
//c
//(c+a)
//(a+c)
//(c+(a+b))
//((a+b)+c)
//((s.a+s.b)+s.c)
//permutations for ((s.a+s.b)+s.c)
//((s.a+s.b)+s.c)
//(s.c+(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.c
//(s.a+(s.b+s.c))
//(s.b+(s.a+s.c))
//(s.b+s.c)
//(s.c+s.b)
//s.b
//s.c
//(s.c+s.b)
//(s.b+s.c)
//(s.a+s.c)
//(s.c+s.a)
//s.a
//s.c
//(s.c+s.a)
//(s.a+s.c)
//(s.c+(s.a+s.b))
//((s.a+s.b)+s.c)
//((ar[0]+ar[1])+ar[2])
//permutations for ((ar[0]+ar[1])+ar[2])
//((ar[0]+ar[1])+ar[2])
//(ar[2]+(ar[0]+ar[1]))
//(ar[0]+ar[1])
//(ar[1]+ar[0])
//ar[0]
//ar[1]
//(ar[1]+ar[0])
//(ar[0]+ar[1])
//ar[2]
//(ar[0]+(ar[1]+ar[2]))
//(ar[1]+(ar[0]+ar[2]))
//(ar[1]+ar[2])
//(ar[2]+ar[1])
//ar[1]
//ar[2]
//(ar[2]+ar[1])
//(ar[1]+ar[2])
//(ar[0]+ar[2])
//(ar[2]+ar[0])
//ar[0]
//ar[2]
//(ar[2]+ar[0])
//(ar[0]+ar[2])
//(ar[2]+(ar[0]+ar[1]))
//((ar[0]+ar[1])+ar[2])
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//permutations for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(a+(b*((c*c)-(c+d))))
//((b*((c*c)-(c+d)))+a)
//a
//(b*((c*c)-(c+d)))
//(((c*c)-(c+d))*b)
//b
//((c*c)-(c+d))
//(c*c)
//(c*c)
//c
//c
//(c*c)
//(c*c)
//(c+d)
//(d+c)
//c
//d
//(d+c)
//(c+d)
//(c*c)
//((c*c)-(c+d))
//(((c*c)-(c+d))*b)
//(b*((c*c)-(c+d)))
//((b*((c*c)-(c+d)))+a)
//(a+(b*((c*c)-(c+d))))
//(((a*a)+a)+(a*b))
//((a*b)+((a*a)+a))
//((a*a)+a)
//(a+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//a
//(a+(a*a))
//((a*a)+a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*a)+(a+(a*b)))
//(a+((a*a)+(a*b)))
//(a+(a*b))
//((a*b)+a)
//a
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+a)
//(a+(a*b))
//((a*a)+(a*b))
//((a*b)+(a*a))
//(a*a)
//(a*a)
//a
//a
//(a*a)
//(a*a)
//(a*b)
//(b*a)
//a
//b
//(b*a)
//(a*b)
//((a*b)+(a*a))
//((a*a)+(a*b))
//((a*b)+((a*a)+a))
//(((a*a)+a)+(a*b))
//(a+(b*((c*c)-(c+d))))
//((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))
//(((abc+c)-(a-(ad*a)))+r)
//(r+((abc+c)-(a-(ad*a))))
//((abc+c)-(a-(ad*a)))
//(abc+c)
//(c+abc)
//abc
//c
//(c+abc)
//(abc+c)
//(a-(ad*a))
//a
//(ad*a)
//(a*ad)
//ad
//a
//(a*ad)
//(ad*a)
//a
//(a-(ad*a))
//(abc+c)
//((abc+c)-(a-(ad*a)))
//r
//(r+((abc+c)-(a-(ad*a))))
//(((abc+c)-(a-(ad*a)))+r)
//((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))))
//(((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r))
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//permutations for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
//((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a)
//a
//(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))
//b
//(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))
//(((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c)
//c
//((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))
//(((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e))
//(d-e)
//d
//e
//d
//(d-e)
//((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//(f+((f-a)+(a*(b-(c*(d-(e*f)))))))
//((f-a)+(a*(b-(c*(d-(e*f))))))
//((a*(b-(c*(d-(e*f)))))+(f-a))
//(f-a)
//f
//a
//f
//(f-a)
//(a*(b-(c*(d-(e*f)))))
//((b-(c*(d-(e*f))))*a)
//a
//(b-(c*(d-(e*f))))
//b
//(c*(d-(e*f)))
//((d-(e*f))*c)
//c
//(d-(e*f))
//d
//(e*f)
//(f*e)
//e
//f
//(f*e)
//(e*f)
//d
//(d-(e*f))
//((d-(e*f))*c)
//(c*(d-(e*f)))
//b
//(b-(c*(d-(e*f))))
//((b-(c*(d-(e*f))))*a)
//(a*(b-(c*(d-(e*f)))))
//((a*(b-(c*(d-(e*f)))))+(f-a))
//((f-a)+(a*(b-(c*(d-(e*f))))))
//f
//((f-a)+((a*(b-(c*(d-(e*f)))))+f))
//((a*(b-(c*(d-(e*f)))))+((f-a)+f))
//((a*(b-(c*(d-(e*f)))))+f)
//(f+(a*(b-(c*(d-(e*f))))))
//(a*(b-(c*(d-(e*f)))))
//((b-(c*(d-(e*f))))*a)
//a
//(b-(c*(d-(e*f))))
//b
//(c*(d-(e*f)))
//((d-(e*f))*c)
//c
//(d-(e*f))
//d
//(e*f)
//(f*e)
//e
//f
//(f*e)
//(e*f)
//d
//(d-(e*f))
//((d-(e*f))*c)
//(c*(d-(e*f)))
//b
//(b-(c*(d-(e*f))))
//((b-(c*(d-(e*f))))*a)
//(a*(b-(c*(d-(e*f)))))
//f
//(f+(a*(b-(c*(d-(e*f))))))
//((a*(b-(c*(d-(e*f)))))+f)
//((f-a)+f)
//(f+(f-a))
//(f-a)
//f
//a
//f
//(f-a)
//f
//(f+(f-a))
//((f-a)+f)
//(f+((f-a)+(a*(b-(c*(d-(e*f)))))))
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//(a*ab)
//(ab*a)
//a
//ab
//(ab*a)
//(a*ab)
//(((f-a)+(a*(b-(c*(d-(e*f))))))+f)
//((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))
//(((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e))
//((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))
//(((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c)
//(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))
//b
//(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))
//((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a)
//(a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))))
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
int d = return_int(false, -17);
int e = return_int(false, -9);
int ad = return_int(false, 30);
int[] ar = new int[5];
ar[0] = return_int(false, -67);
ar[1] = return_int(false, -72);
ar[2] = return_int(false, 9);
class_s s = new class_s();
s.a = return_int(false, 57);
s.b = return_int(false, 35);
s.c = return_int(false, 47);
int abc = return_int(false, 10);
int r = return_int(false, 34);
int ab = return_int(false, 78);
int b = return_int(false, -19);
int c = return_int(false, -31);
int a = return_int(false, -42);
int f = return_int(false, -8);
int v;
v = ((a + b) + c);
if (v != -92)
{
Console.WriteLine("test0: for ((a+b)+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + (a + b));
if (v != -92)
{
Console.WriteLine("test1: for (c+(a+b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + b);
if (v != -61)
{
Console.WriteLine("test2: for (a+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + a);
if (v != -61)
{
Console.WriteLine("test3: for (b+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + a);
if (v != -61)
{
Console.WriteLine("test4: for (b+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + b);
if (v != -61)
{
Console.WriteLine("test5: for (a+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b + c));
if (v != -92)
{
Console.WriteLine("test6: for (a+(b+c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + (a + c));
if (v != -92)
{
Console.WriteLine("test7: for (b+(a+c)) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, -6);
v = (b + c);
if (v != -50)
{
Console.WriteLine("test8: for (b+c) failed actual value {0} ", v);
ret = ret + 1;
}
e = return_int(false, 54);
v = (c + b);
if (v != -50)
{
Console.WriteLine("test9: for (c+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + b);
if (v != -50)
{
Console.WriteLine("test10: for (c+b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b + c);
if (v != -50)
{
Console.WriteLine("test11: for (b+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + c);
if (v != -73)
{
Console.WriteLine("test12: for (a+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + a);
if (v != -73)
{
Console.WriteLine("test13: for (c+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + a);
if (v != -73)
{
Console.WriteLine("test14: for (c+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + c);
if (v != -73)
{
Console.WriteLine("test15: for (a+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + (a + b));
if (v != -92)
{
Console.WriteLine("test16: for (c+(a+b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a + b) + c);
if (v != -92)
{
Console.WriteLine("test17: for ((a+b)+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((s.a + s.b) + s.c);
if (v != 86)
{
Console.WriteLine("test18: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != 86)
{
Console.WriteLine("test19: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != 92)
{
Console.WriteLine("test20: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != 92)
{
Console.WriteLine("test21: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != 92)
{
Console.WriteLine("test22: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != 92)
{
Console.WriteLine("test23: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + (s.b + s.c));
if (v != 86)
{
Console.WriteLine("test24: for (s.a+(s.b+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + (s.a + s.c));
if (v != 86)
{
Console.WriteLine("test25: for (s.b+(s.a+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 29)
{
Console.WriteLine("test26: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.b);
if (v != 29)
{
Console.WriteLine("test27: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.b);
if (v != 29)
{
Console.WriteLine("test28: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 29)
{
Console.WriteLine("test29: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != 51)
{
Console.WriteLine("test30: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != 51)
{
Console.WriteLine("test31: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != 51)
{
Console.WriteLine("test32: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != 51)
{
Console.WriteLine("test33: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != 86)
{
Console.WriteLine("test34: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((s.a + s.b) + s.c);
if (v != 86)
{
Console.WriteLine("test35: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((ar[0] + ar[1]) + ar[2]);
if (v != -130)
{
Console.WriteLine("test36: for ((ar[0]+ar[1])+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + (ar[0] + ar[1]));
if (v != -130)
{
Console.WriteLine("test37: for (ar[2]+(ar[0]+ar[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[1]);
if (v != -139)
{
Console.WriteLine("test38: for (ar[0]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[0]);
if (v != -139)
{
Console.WriteLine("test39: for (ar[1]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, -4);
v = (ar[1] + ar[0]);
if (v != -139)
{
Console.WriteLine("test40: for (ar[1]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[1]);
if (v != -139)
{
Console.WriteLine("test41: for (ar[0]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + (ar[1] + ar[2]));
if (v != -130)
{
Console.WriteLine("test42: for (ar[0]+(ar[1]+ar[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + (ar[0] + ar[2]));
if (v != -130)
{
Console.WriteLine("test43: for (ar[1]+(ar[0]+ar[2])) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[2]);
if (v != -63)
{
Console.WriteLine("test44: for (ar[1]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[1]);
if (v != -63)
{
Console.WriteLine("test45: for (ar[2]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[1]);
if (v != -63)
{
Console.WriteLine("test46: for (ar[2]+ar[1]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[1] + ar[2]);
if (v != -63)
{
Console.WriteLine("test47: for (ar[1]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[2]);
if (v != -58)
{
Console.WriteLine("test48: for (ar[0]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
s.b = return_int(false, 33);
v = (ar[2] + ar[0]);
if (v != -58)
{
Console.WriteLine("test49: for (ar[2]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + ar[0]);
if (v != -58)
{
Console.WriteLine("test50: for (ar[2]+ar[0]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[0] + ar[2]);
if (v != -58)
{
Console.WriteLine("test51: for (ar[0]+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ar[2] + (ar[0] + ar[1]));
if (v != -130)
{
Console.WriteLine("test52: for (ar[2]+(ar[0]+ar[1])) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((ar[0] + ar[1]) + ar[2]);
if (v != -130)
{
Console.WriteLine("test53: for ((ar[0]+ar[1])+ar[2]) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 12);
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != 9758117)
{
Console.WriteLine("test54: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != 9758117)
{
Console.WriteLine("test55: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -21733)
{
Console.WriteLine("test56: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test57: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -19213)
{
Console.WriteLine("test58: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * ((c * c) - (c + d)));
if (v != -19171)
{
Console.WriteLine("test59: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((c * c) - (c + d)) * b);
if (v != -19171)
{
Console.WriteLine("test60: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 1009)
{
Console.WriteLine("test61: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test62: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test63: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test64: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test65: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -48)
{
Console.WriteLine("test66: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -48)
{
Console.WriteLine("test67: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d + c);
if (v != -48)
{
Console.WriteLine("test68: for (d+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + d);
if (v != -48)
{
Console.WriteLine("test69: for (c+d) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * c);
if (v != 961)
{
Console.WriteLine("test70: for (c*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((c * c) - (c + d));
if (v != 1009)
{
Console.WriteLine("test71: for ((c*c)-(c+d)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((c * c) - (c + d)) * b);
if (v != -19171)
{
Console.WriteLine("test72: for (((c*c)-(c+d))*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * ((c * c) - (c + d)));
if (v != -19171)
{
Console.WriteLine("test73: for (b*((c*c)-(c+d))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b * ((c * c) - (c + d))) + a);
if (v != -19213)
{
Console.WriteLine("test74: for ((b*((c*c)-(c+d)))+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test75: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a * a) + a) + (a * b));
if (v != 2520)
{
Console.WriteLine("test76: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 2520)
{
Console.WriteLine("test77: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 1722)
{
Console.WriteLine("test78: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 1722)
{
Console.WriteLine("test79: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 12);
ad = return_int(false, 23);
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test80: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test81: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test82: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test83: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * a));
if (v != 1722)
{
Console.WriteLine("test84: for (a+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + a);
if (v != 1722)
{
Console.WriteLine("test85: for ((a*a)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test86: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test87: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test88: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test89: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a + (a * b)));
if (v != 2520)
{
Console.WriteLine("test90: for ((a*a)+(a+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + ((a * a) + (a * b)));
if (v != 2520)
{
Console.WriteLine("test91: for (a+((a*a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != 756)
{
Console.WriteLine("test92: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + a);
if (v != 756)
{
Console.WriteLine("test93: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test94: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test95: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test96: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test97: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
e = return_int(false, 11);
v = ((a * b) + a);
if (v != 756)
{
Console.WriteLine("test98: for ((a*b)+a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (a * b));
if (v != 756)
{
Console.WriteLine("test99: for (a+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 2562)
{
Console.WriteLine("test100: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 2562)
{
Console.WriteLine("test101: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test102: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test103: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test104: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * a);
if (v != 1764)
{
Console.WriteLine("test105: for (a*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test106: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 8);
v = (b * a);
if (v != 798)
{
Console.WriteLine("test107: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b * a);
if (v != 798)
{
Console.WriteLine("test108: for (b*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * b);
if (v != 798)
{
Console.WriteLine("test109: for (a*b) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + (a * a));
if (v != 2562)
{
Console.WriteLine("test110: for ((a*b)+(a*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * a) + (a * b));
if (v != 2562)
{
Console.WriteLine("test111: for ((a*a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * b) + ((a * a) + a));
if (v != 2520)
{
Console.WriteLine("test112: for ((a*b)+((a*a)+a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a * a) + a) + (a * b));
if (v != 2520)
{
Console.WriteLine("test113: for (((a*a)+a)+(a*b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a + (b * ((c * c) - (c + d))));
if (v != -19213)
{
Console.WriteLine("test114: for (a+(b*((c*c)-(c+d)))) failed actual value {0} ", v);
ret = ret + 1;
}
c = return_int(false, 32);
v = ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b)));
if (v != -21733)
{
Console.WriteLine("test115: for ((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != -848)
{
Console.WriteLine("test116: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 99);
v = (r + ((abc + c) - (a - (ad * a))));
if (v != -848)
{
Console.WriteLine("test117: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
ar[0] = return_int(false, -13);
s.c = return_int(false, 47);
v = ((abc + c) - (a - (ad * a)));
if (v != -882)
{
Console.WriteLine("test118: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test119: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + abc);
if (v != 42)
{
Console.WriteLine("test120: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c + abc);
if (v != 42)
{
Console.WriteLine("test121: for (c+abc) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test122: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a - (ad * a));
if (v != 924)
{
Console.WriteLine("test123: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ad * a);
if (v != -966)
{
Console.WriteLine("test124: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != -966)
{
Console.WriteLine("test125: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ad);
if (v != -966)
{
Console.WriteLine("test126: for (a*ad) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ad * a);
if (v != -966)
{
Console.WriteLine("test127: for (ad*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a - (ad * a));
if (v != 924)
{
Console.WriteLine("test128: for (a-(ad*a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (abc + c);
if (v != 42)
{
Console.WriteLine("test129: for (abc+c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((abc + c) - (a - (ad * a)));
if (v != -882)
{
Console.WriteLine("test130: for ((abc+c)-(a-(ad*a))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (r + ((abc + c) - (a - (ad * a))));
if (v != -848)
{
Console.WriteLine("test131: for (r+((abc+c)-(a-(ad*a)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((abc + c) - (a - (ad * a))) + r);
if (v != -848)
{
Console.WriteLine("test132: for (((abc+c)-(a-(ad*a)))+r) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((abc + c) - (a - (ad * a))) + r) * ((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))));
if (v != 18429584)
{
Console.WriteLine("test133: for ((((abc+c)-(a-(ad*a)))+r)*((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((a + (b * ((c * c) - (c + d)))) - (((a * a) + a) + (a * b))) * (((abc + c) - (a - (ad * a))) + r));
if (v != 18429584)
{
Console.WriteLine("test134: for (((a+(b*((c*c)-(c+d))))-(((a*a)+a)+(a*b)))*(((abc+c)-(a-(ad*a)))+r)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))));
if (v != 133723422)
{
Console.WriteLine("test135: for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))) * a);
if (v != 133723422)
{
Console.WriteLine("test136: for ((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)))));
if (v != -3183891)
{
Console.WriteLine("test137: for (b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))));
if (v != 3183872)
{
Console.WriteLine("test138: for (c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))) * c);
if (v != 3183872)
{
Console.WriteLine("test139: for (((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)));
if (v != 99496)
{
Console.WriteLine("test140: for ((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)) + (d - e));
if (v != 99496)
{
Console.WriteLine("test141: for (((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - e);
if (v != -28)
{
Console.WriteLine("test142: for (d-e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - e);
if (v != -28)
{
Console.WriteLine("test143: for (d-e) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab));
if (v != 99524)
{
Console.WriteLine("test144: for ((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 96248)
{
Console.WriteLine("test145: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + ((f - a) + (a * (b - (c * (d - (e * f)))))));
if (v != 96248)
{
Console.WriteLine("test146: for (f+((f-a)+(a*(b-(c*(d-(e*f))))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + (a * (b - (c * (d - (e * f))))));
if (v != 96256)
{
Console.WriteLine("test147: for ((f-a)+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + (f - a));
if (v != 96256)
{
Console.WriteLine("test148: for ((a*(b-(c*(d-(e*f)))))+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != 34)
{
Console.WriteLine("test149: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != 34)
{
Console.WriteLine("test150: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test151: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test152: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test153: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test154: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test155: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test156: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test157: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test158: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test159: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test160: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test161: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test162: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test163: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test164: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
s.b = return_int(false, -51);
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test165: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test166: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + (f - a));
if (v != 96256)
{
Console.WriteLine("test167: for ((a*(b-(c*(d-(e*f)))))+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + (a * (b - (c * (d - (e * f))))));
if (v != 96256)
{
Console.WriteLine("test168: for ((f-a)+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + ((a * (b - (c * (d - (e * f))))) + f));
if (v != 96248)
{
Console.WriteLine("test169: for ((f-a)+((a*(b-(c*(d-(e*f)))))+f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + ((f - a) + f));
if (v != 96248)
{
Console.WriteLine("test170: for ((a*(b-(c*(d-(e*f)))))+((f-a)+f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + f);
if (v != 96214)
{
Console.WriteLine("test171: for ((a*(b-(c*(d-(e*f)))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (a * (b - (c * (d - (e * f))))));
if (v != 96214)
{
Console.WriteLine("test172: for (f+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test173: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test174: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test175: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
r = return_int(false, -10);
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test176: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test177: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test178: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test179: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test180: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f * e);
if (v != -88)
{
Console.WriteLine("test181: for (f*e) failed actual value {0} ", v);
ret = ret + 1;
}
v = (e * f);
if (v != -88)
{
Console.WriteLine("test182: for (e*f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (d - (e * f));
if (v != 71)
{
Console.WriteLine("test183: for (d-(e*f)) failed actual value {0} ", v);
ret = ret + 1;
}
abc = return_int(false, 68);
v = ((d - (e * f)) * c);
if (v != 2272)
{
Console.WriteLine("test184: for ((d-(e*f))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * (d - (e * f)));
if (v != 2272)
{
Console.WriteLine("test185: for (c*(d-(e*f))) failed actual value {0} ", v);
ret = ret + 1;
}
ar[0] = return_int(false, -46);
r = return_int(false, 65);
v = (b - (c * (d - (e * f))));
if (v != -2291)
{
Console.WriteLine("test186: for (b-(c*(d-(e*f)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * (d - (e * f)))) * a);
if (v != 96222)
{
Console.WriteLine("test187: for ((b-(c*(d-(e*f))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * (d - (e * f)))));
if (v != 96222)
{
Console.WriteLine("test188: for (a*(b-(c*(d-(e*f))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (a * (b - (c * (d - (e * f))))));
if (v != 96214)
{
Console.WriteLine("test189: for (f+(a*(b-(c*(d-(e*f)))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((a * (b - (c * (d - (e * f))))) + f);
if (v != 96214)
{
Console.WriteLine("test190: for ((a*(b-(c*(d-(e*f)))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + f);
if (v != 26)
{
Console.WriteLine("test191: for ((f-a)+f) failed actual value {0} ", v);
ret = ret + 1;
}
f = return_int(false, -56);
v = (f + (f - a));
if (v != -70)
{
Console.WriteLine("test192: for (f+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != -14)
{
Console.WriteLine("test193: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f - a);
if (v != -14)
{
Console.WriteLine("test194: for (f-a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + (f - a));
if (v != -70)
{
Console.WriteLine("test195: for (f+(f-a)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((f - a) + f);
if (v != -70)
{
Console.WriteLine("test196: for ((f-a)+f) failed actual value {0} ", v);
ret = ret + 1;
}
v = (f + ((f - a) + (a * (b - (c * (d - (e * f)))))));
if (v != 805784)
{
Console.WriteLine("test197: for (f+((f-a)+(a*(b-(c*(d-(e*f))))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 805784)
{
Console.WriteLine("test198: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
s.c = return_int(false, 2);
v = (a * ab);
if (v != -3276)
{
Console.WriteLine("test199: for (a*ab) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ab * a);
if (v != -3276)
{
Console.WriteLine("test200: for (ab*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (ab * a);
if (v != -3276)
{
Console.WriteLine("test201: for (ab*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * ab);
if (v != -3276)
{
Console.WriteLine("test202: for (a*ab) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((f - a) + (a * (b - (c * (d - (e * f)))))) + f);
if (v != 805784)
{
Console.WriteLine("test203: for (((f-a)+(a*(b-(c*(d-(e*f))))))+f) failed actual value {0} ", v);
ret = ret + 1;
}
ad = return_int(false, 16);
v = ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab));
if (v != 809060)
{
Console.WriteLine("test204: for ((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)) + (d - e));
if (v != 809032)
{
Console.WriteLine("test205: for (((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))+(d-e)) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)));
if (v != 809032)
{
Console.WriteLine("test206: for ((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))) * c);
if (v != 25889024)
{
Console.WriteLine("test207: for (((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))*c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))));
if (v != 25889024)
{
Console.WriteLine("test208: for (c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))) failed actual value {0} ", v);
ret = ret + 1;
}
v = (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab)))));
if (v != -25889043)
{
Console.WriteLine("test209: for (b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab))))) failed actual value {0} ", v);
ret = ret + 1;
}
v = ((b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))) * a);
if (v != 1087339806)
{
Console.WriteLine("test210: for ((b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))*a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (a * (b - (c * ((d - e) + ((((f - a) + (a * (b - (c * (d - (e * f)))))) + f) - (a * ab))))));
if (v != 1087339806)
{
Console.WriteLine("test211: for (a*(b-(c*((d-e)+((((f-a)+(a*(b-(c*(d-(e*f))))))+f)-(a*ab)))))) failed actual value {0} ", v);
ret = ret + 1;
}
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 a;
public int b;
public int c;
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/Microsoft.Extensions.FileProviders.Abstractions/src/IDirectoryContents.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;
namespace Microsoft.Extensions.FileProviders
{
/// <summary>
/// Represents a directory's content in the file provider.
/// </summary>
public interface IDirectoryContents : IEnumerable<IFileInfo>
{
/// <summary>
/// True if a directory was located at the given path.
/// </summary>
bool Exists { get; }
}
}
| // 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;
namespace Microsoft.Extensions.FileProviders
{
/// <summary>
/// Represents a directory's content in the file provider.
/// </summary>
public interface IDirectoryContents : IEnumerable<IFileInfo>
{
/// <summary>
/// True if a directory was located at the given path.
/// </summary>
bool Exists { get; }
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/baseservices/exceptions/unittests/Recurse.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;
public class TestSet
{
static void CountResults(int testReturnValue, ref int nSuccesses, ref int nFailures)
{
if (100 == testReturnValue)
{
nSuccesses++;
}
else
{
nFailures++;
}
}
public static int Main()
{
int nSuccesses = 0;
int nFailures = 0;
CountResults(new RecurseTest().Run(), ref nSuccesses, ref nFailures);
if (0 == nFailures)
{
Console.WriteLine("OVERALL PASS: " + nSuccesses + " tests");
return 100;
}
else
{
Console.WriteLine("OVERALL FAIL: " + nFailures + " tests failed");
return 999;
}
}
}
class RecurseTest
{
Trace _trace;
void DoTest(int level)
{
_trace.Write(level.ToString());
if (level <= 0)
return;
try
{
throw new Exception("" + (level - 1));
}
catch (Exception e)
{
Console.WriteLine(e);
_trace.Write(e.Message);
DoTest(level - 2);
}
}
public int Run()
{
int n = 8;
string expected = "";
// create expected result string
for (int i = n; i >= 0; i--)
{
expected += i.ToString();
}
_trace = new Trace("RecurseTest", expected);
DoTest(n);
return _trace.Match();
}
}
| // 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;
public class TestSet
{
static void CountResults(int testReturnValue, ref int nSuccesses, ref int nFailures)
{
if (100 == testReturnValue)
{
nSuccesses++;
}
else
{
nFailures++;
}
}
public static int Main()
{
int nSuccesses = 0;
int nFailures = 0;
CountResults(new RecurseTest().Run(), ref nSuccesses, ref nFailures);
if (0 == nFailures)
{
Console.WriteLine("OVERALL PASS: " + nSuccesses + " tests");
return 100;
}
else
{
Console.WriteLine("OVERALL FAIL: " + nFailures + " tests failed");
return 999;
}
}
}
class RecurseTest
{
Trace _trace;
void DoTest(int level)
{
_trace.Write(level.ToString());
if (level <= 0)
return;
try
{
throw new Exception("" + (level - 1));
}
catch (Exception e)
{
Console.WriteLine(e);
_trace.Write(e.Message);
DoTest(level - 2);
}
}
public int Run()
{
int n = 8;
string expected = "";
// create expected result string
for (int i = n; i >= 0; i--)
{
expected += i.ToString();
}
_trace = new Trace("RecurseTest", expected);
DoTest(n);
return _trace.Match();
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.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.Xml;
namespace System.Security.Cryptography.Xml
{
public abstract class EncryptedType
{
private string _id;
private string _type;
private string _mimeType;
private string _encoding;
private EncryptionMethod _encryptionMethod;
private CipherData _cipherData;
private EncryptionPropertyCollection _props;
private KeyInfo _keyInfo;
internal XmlElement _cachedXml;
internal bool CacheValid
{
get
{
return (_cachedXml != null);
}
}
public virtual string Id
{
get { return _id; }
set
{
_id = value;
_cachedXml = null;
}
}
public virtual string Type
{
get { return _type; }
set
{
_type = value;
_cachedXml = null;
}
}
public virtual string MimeType
{
get { return _mimeType; }
set
{
_mimeType = value;
_cachedXml = null;
}
}
public virtual string Encoding
{
get { return _encoding; }
set
{
_encoding = value;
_cachedXml = null;
}
}
public KeyInfo KeyInfo
{
get
{
if (_keyInfo == null)
_keyInfo = new KeyInfo();
return _keyInfo;
}
set { _keyInfo = value; }
}
public virtual EncryptionMethod EncryptionMethod
{
get { return _encryptionMethod; }
set
{
_encryptionMethod = value;
_cachedXml = null;
}
}
public virtual EncryptionPropertyCollection EncryptionProperties
{
get
{
if (_props == null)
_props = new EncryptionPropertyCollection();
return _props;
}
}
public void AddProperty(EncryptionProperty ep)
{
EncryptionProperties.Add(ep);
}
public virtual CipherData CipherData
{
get
{
if (_cipherData == null)
_cipherData = new CipherData();
return _cipherData;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_cipherData = value;
_cachedXml = null;
}
}
public abstract void LoadXml(XmlElement value);
public abstract XmlElement GetXml();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Xml;
namespace System.Security.Cryptography.Xml
{
public abstract class EncryptedType
{
private string _id;
private string _type;
private string _mimeType;
private string _encoding;
private EncryptionMethod _encryptionMethod;
private CipherData _cipherData;
private EncryptionPropertyCollection _props;
private KeyInfo _keyInfo;
internal XmlElement _cachedXml;
internal bool CacheValid
{
get
{
return (_cachedXml != null);
}
}
public virtual string Id
{
get { return _id; }
set
{
_id = value;
_cachedXml = null;
}
}
public virtual string Type
{
get { return _type; }
set
{
_type = value;
_cachedXml = null;
}
}
public virtual string MimeType
{
get { return _mimeType; }
set
{
_mimeType = value;
_cachedXml = null;
}
}
public virtual string Encoding
{
get { return _encoding; }
set
{
_encoding = value;
_cachedXml = null;
}
}
public KeyInfo KeyInfo
{
get
{
if (_keyInfo == null)
_keyInfo = new KeyInfo();
return _keyInfo;
}
set { _keyInfo = value; }
}
public virtual EncryptionMethod EncryptionMethod
{
get { return _encryptionMethod; }
set
{
_encryptionMethod = value;
_cachedXml = null;
}
}
public virtual EncryptionPropertyCollection EncryptionProperties
{
get
{
if (_props == null)
_props = new EncryptionPropertyCollection();
return _props;
}
}
public void AddProperty(EncryptionProperty ep)
{
EncryptionProperties.Add(ep);
}
public virtual CipherData CipherData
{
get
{
if (_cipherData == null)
_cipherData = new CipherData();
return _cipherData;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_cipherData = value;
_cachedXml = null;
}
}
public abstract void LoadXml(XmlElement value);
public abstract XmlElement GetXml();
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/libraries/System.Formats.Asn1/tests/Writer/WriteUtcTime.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 Xunit;
namespace System.Formats.Asn1.Tests.Writer
{
public class WriteUtcTime : Asn1WriterTests
{
public static IEnumerable<object[]> TestCases { get; } = new object[][]
{
new object[]
{
new DateTimeOffset(2017, 10, 16, 8, 24, 3, TimeSpan.FromHours(-7)),
"0D3137313031363135323430335A",
},
new object[]
{
new DateTimeOffset(1817, 10, 16, 21, 24, 3, TimeSpan.FromHours(6)),
"0D3137313031363135323430335A",
},
new object[]
{
new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero),
"0D3030303130313030303030305A",
},
};
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_BER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.BER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_BER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.BER);
Asn1Tag tag = new Asn1Tag(TagClass.Application, 11);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_CER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_CER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
Asn1Tag tag = new Asn1Tag(TagClass.Private, 95);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_DER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_DER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 3);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[InlineData(AsnEncodingRules.BER)]
[InlineData(AsnEncodingRules.CER)]
[InlineData(AsnEncodingRules.DER)]
public void VerifyWriteUtcTime_Null(AsnEncodingRules ruleSet)
{
AsnWriter writer = new AsnWriter(ruleSet);
AssertExtensions.Throws<ArgumentException>(
"tag",
() => writer.WriteUtcTime(DateTimeOffset.Now, Asn1Tag.Null));
}
[Theory]
[InlineData(AsnEncodingRules.BER)]
[InlineData(AsnEncodingRules.CER)]
[InlineData(AsnEncodingRules.DER)]
public void VerifyWriteUtcTime_IgnoresConstructed(AsnEncodingRules ruleSet)
{
AsnWriter writer = new AsnWriter(ruleSet);
DateTimeOffset value = new DateTimeOffset(2017, 11, 16, 17, 35, 1, TimeSpan.Zero);
writer.WriteUtcTime(value, new Asn1Tag(UniversalTagNumber.UtcTime, true));
writer.WriteUtcTime(value, new Asn1Tag(TagClass.ContextSpecific, 3, true));
Verify(writer, "170D3137313131363137333530315A" + "830D3137313131363137333530315A");
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_RespectsYearMax_DER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
Assert.Equal(0, writer.GetEncodedLength());
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() => writer.WriteUtcTime(input, input.Year - 1));
Assert.Equal(0, writer.GetEncodedLength());
writer.WriteUtcTime(input, input.Year);
Assert.Equal(15, writer.GetEncodedLength());
writer.WriteUtcTime(input, input.Year + 99);
Assert.Equal(30, writer.GetEncodedLength());
writer.Reset();
_ = expectedHexPayload;
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() => writer.WriteUtcTime(input, input.Year + 100));
Assert.Equal(0, writer.GetEncodedLength());
}
[Fact]
public void VerifyWriteUtcTime_RespectsYearMax_UniversalLimit()
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
Asn1Tag tag = new Asn1Tag(TagClass.Private, 11);
// 1950 after ToUniversal
writer.WriteUtcTime(
new DateTimeOffset(1949, 12, 31, 23, 11, 19, TimeSpan.FromHours(-8)),
2049,
tag);
Assert.Equal(15, writer.GetEncodedLength());
// 1949 after ToUniversal
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() =>
writer.WriteUtcTime(
new DateTimeOffset(1950, 1, 1, 3, 11, 19, TimeSpan.FromHours(8)),
2049,
tag));
Assert.Equal(15, writer.GetEncodedLength());
// 2050 after ToUniversal
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() =>
writer.WriteUtcTime(
new DateTimeOffset(2049, 12, 31, 23, 11, 19, TimeSpan.FromHours(-8)),
2049,
tag));
Assert.Equal(15, writer.GetEncodedLength());
// 1950 after ToUniversal
writer.WriteUtcTime(
new DateTimeOffset(2050, 1, 1, 3, 11, 19, TimeSpan.FromHours(8)),
2049,
tag);
Assert.Equal(30, writer.GetEncodedLength());
string hex =
Stringify(tag) + "0D3530303130313037313131395A" +
Stringify(tag) + "0D3439313233313139313131395A";
Verify(writer, hex);
}
}
}
| // 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 Xunit;
namespace System.Formats.Asn1.Tests.Writer
{
public class WriteUtcTime : Asn1WriterTests
{
public static IEnumerable<object[]> TestCases { get; } = new object[][]
{
new object[]
{
new DateTimeOffset(2017, 10, 16, 8, 24, 3, TimeSpan.FromHours(-7)),
"0D3137313031363135323430335A",
},
new object[]
{
new DateTimeOffset(1817, 10, 16, 21, 24, 3, TimeSpan.FromHours(6)),
"0D3137313031363135323430335A",
},
new object[]
{
new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero),
"0D3030303130313030303030305A",
},
};
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_BER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.BER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_BER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.BER);
Asn1Tag tag = new Asn1Tag(TagClass.Application, 11);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_CER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_CER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
Asn1Tag tag = new Asn1Tag(TagClass.Private, 95);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_DER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteUtcTime(input);
Verify(writer, "17" + expectedHexPayload);
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_DER_CustomTag(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 3);
writer.WriteUtcTime(input, tag);
Verify(writer, Stringify(tag) + expectedHexPayload);
}
[Theory]
[InlineData(AsnEncodingRules.BER)]
[InlineData(AsnEncodingRules.CER)]
[InlineData(AsnEncodingRules.DER)]
public void VerifyWriteUtcTime_Null(AsnEncodingRules ruleSet)
{
AsnWriter writer = new AsnWriter(ruleSet);
AssertExtensions.Throws<ArgumentException>(
"tag",
() => writer.WriteUtcTime(DateTimeOffset.Now, Asn1Tag.Null));
}
[Theory]
[InlineData(AsnEncodingRules.BER)]
[InlineData(AsnEncodingRules.CER)]
[InlineData(AsnEncodingRules.DER)]
public void VerifyWriteUtcTime_IgnoresConstructed(AsnEncodingRules ruleSet)
{
AsnWriter writer = new AsnWriter(ruleSet);
DateTimeOffset value = new DateTimeOffset(2017, 11, 16, 17, 35, 1, TimeSpan.Zero);
writer.WriteUtcTime(value, new Asn1Tag(UniversalTagNumber.UtcTime, true));
writer.WriteUtcTime(value, new Asn1Tag(TagClass.ContextSpecific, 3, true));
Verify(writer, "170D3137313131363137333530315A" + "830D3137313131363137333530315A");
}
[Theory]
[MemberData(nameof(TestCases))]
public void VerifyWriteUtcTime_RespectsYearMax_DER(DateTimeOffset input, string expectedHexPayload)
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
Assert.Equal(0, writer.GetEncodedLength());
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() => writer.WriteUtcTime(input, input.Year - 1));
Assert.Equal(0, writer.GetEncodedLength());
writer.WriteUtcTime(input, input.Year);
Assert.Equal(15, writer.GetEncodedLength());
writer.WriteUtcTime(input, input.Year + 99);
Assert.Equal(30, writer.GetEncodedLength());
writer.Reset();
_ = expectedHexPayload;
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() => writer.WriteUtcTime(input, input.Year + 100));
Assert.Equal(0, writer.GetEncodedLength());
}
[Fact]
public void VerifyWriteUtcTime_RespectsYearMax_UniversalLimit()
{
AsnWriter writer = new AsnWriter(AsnEncodingRules.CER);
Asn1Tag tag = new Asn1Tag(TagClass.Private, 11);
// 1950 after ToUniversal
writer.WriteUtcTime(
new DateTimeOffset(1949, 12, 31, 23, 11, 19, TimeSpan.FromHours(-8)),
2049,
tag);
Assert.Equal(15, writer.GetEncodedLength());
// 1949 after ToUniversal
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() =>
writer.WriteUtcTime(
new DateTimeOffset(1950, 1, 1, 3, 11, 19, TimeSpan.FromHours(8)),
2049,
tag));
Assert.Equal(15, writer.GetEncodedLength());
// 2050 after ToUniversal
AssertExtensions.Throws<ArgumentOutOfRangeException>(
"value",
() =>
writer.WriteUtcTime(
new DateTimeOffset(2049, 12, 31, 23, 11, 19, TimeSpan.FromHours(-8)),
2049,
tag));
Assert.Equal(15, writer.GetEncodedLength());
// 1950 after ToUniversal
writer.WriteUtcTime(
new DateTimeOffset(2050, 1, 1, 3, 11, 19, TimeSpan.FromHours(8)),
2049,
tag);
Assert.Equal(30, writer.GetEncodedLength());
string hex =
Stringify(tag) + "0D3530303130313037313131395A" +
Stringify(tag) + "0D3439313233313139313131395A";
Verify(writer, hex);
}
}
}
| -1 |
dotnet/runtime | 66,215 | Revisiting nullable annotations on caching | This PR fixes some mismatches between nullability of the arguments between ref and src
| maryamariyan | 2022-03-04T20:21:17Z | 2022-03-07T22:45:03Z | f9747669109a5e95cea6cb54e949dc46d1d6d101 | 440dfe4a7beecd7755767aa247f47af00b119383 | Revisiting nullable annotations on caching. This PR fixes some mismatches between nullability of the arguments between ref and src
| ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ReverseElement16.Vector128.Int64.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 ReverseElement16_Vector128_Int64()
{
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
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 SimpleUnaryOpTest__ReverseElement16_Vector128_Int64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, 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 struct TestStruct
{
public Vector128<Int64> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ReverseElement16_Vector128_Int64 testClass)
{
var result = AdvSimd.ReverseElement16(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReverseElement16_Vector128_Int64 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar1;
private Vector128<Int64> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ReverseElement16_Vector128_Int64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public SimpleUnaryOpTest__ReverseElement16_Vector128_Int64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, new Int64[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.ReverseElement16(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement16), new Type[] { typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement16), new Type[] { typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ReverseElement16(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var result = AdvSimd.ReverseElement16(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var result = AdvSimd.ReverseElement16(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
var result = AdvSimd.ReverseElement16(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ReverseElement16(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ReverseElement16(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<Int64> op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ReverseElement16(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReverseElement16)}<Int64>(Vector128<Int64>): {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.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 ReverseElement16_Vector128_Int64()
{
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
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 SimpleUnaryOpTest__ReverseElement16_Vector128_Int64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, 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 struct TestStruct
{
public Vector128<Int64> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ReverseElement16_Vector128_Int64 testClass)
{
var result = AdvSimd.ReverseElement16(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReverseElement16_Vector128_Int64 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar1;
private Vector128<Int64> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ReverseElement16_Vector128_Int64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public SimpleUnaryOpTest__ReverseElement16_Vector128_Int64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, new Int64[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.ReverseElement16(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement16), new Type[] { typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReverseElement16), new Type[] { typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ReverseElement16(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var result = AdvSimd.ReverseElement16(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var result = AdvSimd.ReverseElement16(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
var result = AdvSimd.ReverseElement16(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__ReverseElement16_Vector128_Int64();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ReverseElement16(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ReverseElement16(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ReverseElement16(
AdvSimd.LoadVector128((Int64*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<Int64> op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ReverseElement16(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReverseElement16)}<Int64>(Vector128<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/cmake/config.h.in | #ifndef __MONO_CONFIG_H__
#define __MONO_CONFIG_H__
#ifdef _MSC_VER
// FIXME This is all questionable but the logs are flooded and nothing else is fixing them.
#pragma warning(disable:4018) // signed/unsigned mismatch
#pragma warning(disable:4090) // const problem
#pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned
#pragma warning(disable:4244) // integer conversion, possible loss of data
#pragma warning(disable:4267) // integer conversion, possible loss of data
// promote warnings to errors
#pragma warning( error:4013) // function undefined; assuming extern returning int
#pragma warning( error:4022) // call and prototype disagree
#pragma warning( error:4047) // differs in level of indirection
#pragma warning( error:4098) // void return returns a value
#pragma warning( error:4113) // call and prototype disagree
#pragma warning( error:4172) // returning address of local variable or temporary
#pragma warning( error:4197) // top-level volatile in cast is ignored
#pragma warning( error:4273) // inconsistent dll linkage
#pragma warning( error:4293) // shift count negative or too big, undefined behavior
#pragma warning( error:4312) // 'type cast': conversion from 'MonoNativeThreadId' to 'gpointer' of greater size
#pragma warning( error:4715) // 'keyword' not all control paths return a value
#include <SDKDDKVer.h>
#if _WIN32_WINNT < 0x0601
#error "Mono requires Windows 7 or later."
#endif /* _WIN32_WINNT < 0x0601 */
#ifndef HAVE_WINAPI_FAMILY_SUPPORT
#define HAVE_WINAPI_FAMILY_SUPPORT
/* WIN API Family support */
#include <winapifamily.h>
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#define HAVE_CLASSIC_WINAPI_SUPPORT 1
#define HAVE_UWP_WINAPI_SUPPORT 0
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
#define HAVE_CLASSIC_WINAPI_SUPPORT 0
#define HAVE_UWP_WINAPI_SUPPORT 1
#else
#define HAVE_CLASSIC_WINAPI_SUPPORT 0
#define HAVE_UWP_WINAPI_SUPPORT 0
#ifndef HAVE_EXTERN_DEFINED_WINAPI_SUPPORT
#error Unsupported WINAPI family
#endif
#endif
#endif
#endif
/* This platform does not support symlinks */
#cmakedefine HOST_NO_SYMLINKS 1
/* pthread is a pointer */
#cmakedefine PTHREAD_POINTER_ID 1
/* Targeting the Android platform */
#cmakedefine HOST_ANDROID 1
/* ... */
#cmakedefine TARGET_ANDROID 1
/* ... */
#cmakedefine USE_MACH_SEMA 1
/* Targeting the Fuchsia platform */
#cmakedefine HOST_FUCHSIA 1
/* Targeting the AIX and PASE platforms */
#cmakedefine HOST_AIX 1
/* Host Platform is Win32 */
#cmakedefine HOST_WIN32 1
/* Target Platform is Win32 */
#cmakedefine TARGET_WIN32 1
/* Host Platform is Darwin */
#cmakedefine HOST_DARWIN 1
/* Host Platform is iOS */
#cmakedefine HOST_IOS 1
/* Host Platform is tvOS */
#cmakedefine HOST_TVOS 1
/* Host Platform is Mac Catalyst */
#cmakedefine HOST_MACCAT 1
/* Use classic Windows API support */
#cmakedefine HAVE_CLASSIC_WINAPI_SUPPORT 1
/* Don't use UWP Windows API support */
#cmakedefine HAVE_UWP_WINAPI_SUPPORT 1
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H 1
/* Define to 1 if you have the <signal.h> header file. */
#cmakedefine HAVE_SIGNAL_H 1
/* Define to 1 if you have the <setjmp.h> header file. */
#cmakedefine HAVE_SETJMP_H 1
/* Define to 1 if you have the <syslog.h> header file. */
#cmakedefine HAVE_SYSLOG_H 1
/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>.
*/
#cmakedefine MAJOR_IN_MKDEV 1
/* Define to 1 if `major', `minor', and `makedev' are declared in
<sysmacros.h>. */
#cmakedefine MAJOR_IN_SYSMACROS 1
/* Define to 1 if you have the <sys/filio.h> header file. */
#cmakedefine HAVE_SYS_FILIO_H 1
/* Define to 1 if you have the <sys/sockio.h> header file. */
#cmakedefine HAVE_SYS_SOCKIO_H 1
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine HAVE_NETDB_H 1
/* Define to 1 if you have the <utime.h> header file. */
#cmakedefine HAVE_UTIME_H 1
/* Define to 1 if you have the <sys/utime.h> header file. */
#cmakedefine HAVE_SYS_UTIME_H 1
/* Define to 1 if you have the <semaphore.h> header file. */
#cmakedefine HAVE_SEMAPHORE_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#cmakedefine HAVE_SYS_UN_H 1
/* Define to 1 if you have the <sys/syscall.h> header file. */
#cmakedefine HAVE_SYS_SYSCALL_H 1
/* Define to 1 if you have the <sys/uio.h> header file. */
#cmakedefine HAVE_SYS_UIO_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/sysctl.h> header file. */
#cmakedefine HAVE_SYS_SYSCTL_H 1
/* Define to 1 if you have the <libproc.h> header file. */
#cmakedefine HAVE_LIBPROC_H 1
/* Define to 1 if you have the <sys/prctl.h> header file. */
#cmakedefine HAVE_SYS_PRCTL_H 1
/* Define to 1 if you have the <gnu/lib-names.h> header file. */
#cmakedefine HAVE_GNU_LIB_NAMES_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#cmakedefine HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/utsname.h> header file. */
#cmakedefine HAVE_SYS_UTSNAME_H 1
/* Define to 1 if you have the <alloca.h> header file. */
#cmakedefine HAVE_ALLOCA_H 1
/* Define to 1 if you have the <ucontext.h> header file. */
#cmakedefine HAVE_UCONTEXT_H 1
/* Define to 1 if you have the <pwd.h> header file. */
#cmakedefine HAVE_PWD_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#cmakedefine HAVE_NETINET_TCP_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <link.h> header file. */
#cmakedefine HAVE_LINK_H 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <unwind.h> header file. */
#cmakedefine HAVE_UNWIND_H 1
/* Define to 1 if you have the <sys/user.h> header file. */
#cmakedefine HAVE_SYS_USER_H 1
/* Use static ICU */
#cmakedefine STATIC_ICU 1
/* Use in-tree zlib */
#cmakedefine INTERNAL_ZLIB 1
/* Define to 1 if you have the <poll.h> header file. */
#cmakedefine HAVE_POLL_H 1
/* Define to 1 if you have the <sys/poll.h> header file. */
#cmakedefine HAVE_SYS_POLL_H 1
/* Define to 1 if you have the <sys/wait.h> header file. */
#cmakedefine HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the <wchar.h> header file. */
#cmakedefine HAVE_WCHAR_H 1
/* Define to 1 if you have the <linux/magic.h> header file. */
#cmakedefine HAVE_LINUX_MAGIC_H 1
/* Define to 1 if you have the <android/legacy_signal_inlines.h> header file.
*/
#cmakedefine HAVE_ANDROID_LEGACY_SIGNAL_INLINES_H 1
/* Define to 1 if you have the <android/ndk-version.h> header file. */
#cmakedefine HAVE_ANDROID_NDK_VERSION_H 1
/* Whether Android NDK unified headers are used */
#cmakedefine ANDROID_UNIFIED_HEADERS 1
/* The size of `void *', as computed by sizeof. */
#define SIZEOF_VOID_P @SIZEOF_VOID_P@
/* The size of `long', as computed by sizeof. */
#define SIZEOF_LONG @SIZEOF_LONG@
/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT @SIZEOF_INT@
/* The size of `long long', as computed by sizeof. */
#define SIZEOF_LONG_LONG @SIZEOF_LONG_LONG@
/* Xen-specific behaviour */
#cmakedefine MONO_XEN_OPT 1
/* Reduce runtime requirements (and capabilities) */
#cmakedefine MONO_SMALL_CONFIG 1
/* Make jemalloc assert for mono */
#cmakedefine MONO_JEMALLOC_ASSERT 1
/* Make jemalloc default for mono */
#cmakedefine MONO_JEMALLOC_DEFAULT 1
/* Enable jemalloc usage for mono */
#cmakedefine MONO_JEMALLOC_ENABLED 1
/* Do not include names of unmanaged functions in the crash dump */
#cmakedefine MONO_PRIVATE_CRASHES 1
/* Do not create structured crash files during unmanaged crashes */
#cmakedefine DISABLE_STRUCTURED_CRASH 1
/* String of disabled features */
#define DISABLED_FEATURES @DISABLED_FEATURES@
/* Disable AOT Compiler */
#cmakedefine DISABLE_AOT 1
/* Disable runtime debugging support */
#cmakedefine DISABLE_DEBUG 1
/* Disable reflection emit support */
#cmakedefine DISABLE_REFLECTION_EMIT 1
/* Disable support debug logging */
#cmakedefine DISABLE_LOGGING 1
/* Disable COM support */
#cmakedefine DISABLE_COM 1
/* Disable advanced SSA JIT optimizations */
#cmakedefine DISABLE_SSA 1
/* Disable the JIT, only full-aot mode or interpreter will be supported by the
runtime. */
#cmakedefine DISABLE_JIT 1
/* Disable the interpreter. */
#cmakedefine DISABLE_INTERPRETER 1
/* Some VES is available at runtime */
#cmakedefine ENABLE_ILGEN 1
/* Disable non-blittable marshalling */
#cmakedefine DISABLE_NONBLITTABLE
/* Disable SIMD intrinsics related optimizations. */
#cmakedefine DISABLE_SIMD 1
/* Disable Soft Debugger Agent. */
#cmakedefine DISABLE_DEBUGGER_AGENT 1
/* Disable Performance Counters. */
#cmakedefine DISABLE_PERFCOUNTERS 1
/* Disable shared perfcounters. */
#cmakedefine DISABLE_SHARED_PERFCOUNTERS 1
/* Disable support code for the LLDB plugin. */
#cmakedefine DISABLE_LLDB 1
/* Disable assertion messages. */
#cmakedefine DISABLE_ASSERT_MESSAGES 1
/* Disable concurrent gc support in SGEN. */
#cmakedefine DISABLE_SGEN_MAJOR_MARKSWEEP_CONC 1
/* Disable minor=split support in SGEN. */
#cmakedefine DISABLE_SGEN_SPLIT_NURSERY 1
/* Disable gc bridge support in SGEN. */
#cmakedefine DISABLE_SGEN_GC_BRIDGE 1
/* Disable debug helpers in SGEN. */
#cmakedefine DISABLE_SGEN_DEBUG_HELPERS 1
/* Disable sockets */
#cmakedefine DISABLE_SOCKETS 1
/* Disables use of DllMaps in MonoVM */
#cmakedefine DISABLE_DLLMAP 1
/* Disable Threads */
#cmakedefine DISABLE_THREADS 1
/* Disable perf counters */
#cmakedefine DISABLE_PERF_COUNTERS
/* Disable MONO_LOG_DEST */
#cmakedefine DISABLE_LOG_DEST
/* GC description */
#cmakedefine DEFAULT_GC_NAME 1
/* No GC support. */
#cmakedefine HAVE_NULL_GC 1
/* Length of zero length arrays */
#define MONO_ZERO_LEN_ARRAY @MONO_ZERO_LEN_ARRAY@
/* Define to 1 if you have the `sigaction' function. */
#cmakedefine HAVE_SIGACTION 1
/* Define to 1 if you have the `kill' function. */
#cmakedefine HAVE_KILL 1
/* CLOCK_MONOTONIC */
#cmakedefine HAVE_CLOCK_MONOTONIC 1
/* CLOCK_MONOTONIC_COARSE */
#cmakedefine HAVE_CLOCK_MONOTONIC_COARSE 1
/* clockid_t */
#cmakedefine HAVE_CLOCKID_T 1
/* mach_absolute_time */
#cmakedefine HAVE_MACH_ABSOLUTE_TIME 1
/* gethrtime */
#cmakedefine HAVE_GETHRTIME 1
/* read_real_time */
#cmakedefine HAVE_READ_REAL_TIME 1
/* Define to 1 if you have the `clock_nanosleep' function. */
#cmakedefine HAVE_CLOCK_NANOSLEEP 1
/* Does dlsym require leading underscore. */
#cmakedefine MONO_DL_NEED_USCORE 1
/* Define to 1 if you have the <execinfo.h> header file. */
#cmakedefine HAVE_EXECINFO_H 1
/* Define to 1 if you have the <sys/auxv.h> header file. */
#cmakedefine HAVE_SYS_AUXV_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H 1
/* kqueue */
#cmakedefine HAVE_KQUEUE 1
/* Define to 1 if you have the `backtrace_symbols' function. */
#cmakedefine HAVE_BACKTRACE_SYMBOLS 1
/* Define to 1 if you have the `mkstemp' function. */
#cmakedefine HAVE_MKSTEMP 1
/* Define to 1 if you have the `mmap' function. */
#cmakedefine HAVE_MMAP 1
/* Define to 1 if you have the `madvise' function. */
#cmakedefine HAVE_MADVISE 1
/* Define to 1 if you have the `getrusage' function. */
#cmakedefine HAVE_GETRUSAGE 1
/* Define to 1 if you have the `dladdr' function. */
#cmakedefine HAVE_DLADDR 1
/* Define to 1 if you have the `sysconf' function. */
#cmakedefine HAVE_SYSCONF 1
/* Define to 1 if you have the `getrlimit' function. */
#cmakedefine HAVE_GETRLIMIT 1
/* Define to 1 if you have the `prctl' function. */
#cmakedefine HAVE_PRCTL 1
/* Define to 1 if you have the `nl_langinfo' function. */
#cmakedefine HAVE_NL_LANGINFO 1
/* sched_getaffinity */
#cmakedefine HAVE_SCHED_GETAFFINITY 1
/* sched_setaffinity */
#cmakedefine HAVE_SCHED_SETAFFINITY 1
/* Define to 1 if you have the `sched_getcpu' function. */
#cmakedefine HAVE_SCHED_GETCPU 1
/* Define to 1 if you have the `getpwuid_r' function. */
#cmakedefine HAVE_GETPWUID_R 1
/* Define to 1 if you have the `readlink' function. */
#cmakedefine HAVE_READLINK 1
/* Define to 1 if you have the `chmod' function. */
#cmakedefine HAVE_CHMOD 1
/* Define to 1 if you have the `lstat' function. */
#cmakedefine HAVE_LSTAT 1
/* Define to 1 if you have the `getdtablesize' function. */
#cmakedefine HAVE_GETDTABLESIZE 1
/* Define to 1 if you have the `ftruncate' function. */
#cmakedefine HAVE_FTRUNCATE 1
/* Define to 1 if you have the `msync' function. */
#cmakedefine HAVE_MSYNC 1
/* Define to 1 if you have the `getpeername' function. */
#cmakedefine HAVE_GETPEERNAME 1
/* Define to 1 if you have the `utime' function. */
#cmakedefine HAVE_UTIME 1
/* Define to 1 if you have the `utimes' function. */
#cmakedefine HAVE_UTIMES 1
/* Define to 1 if you have the `openlog' function. */
#cmakedefine HAVE_OPENLOG 1
/* Define to 1 if you have the `closelog' function. */
#cmakedefine HAVE_CLOSELOG 1
/* Define to 1 if you have the `atexit' function. */
#cmakedefine HAVE_ATEXIT 1
/* Define to 1 if you have the `popen' function. */
#cmakedefine HAVE_POPEN 1
/* Define to 1 if you have the `strerror_r' function. */
#cmakedefine HAVE_STRERROR_R 1
/* Have GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY */
#cmakedefine GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY 1
/* GLIBC has CPU_COUNT macro in sched.h */
#cmakedefine HAVE_GNU_CPU_COUNT
/* Have large file support */
#cmakedefine HAVE_LARGE_FILE_SUPPORT 1
/* Have getaddrinfo */
#cmakedefine HAVE_GETADDRINFO 1
/* Have gethostbyname2 */
#cmakedefine HAVE_GETHOSTBYNAME2 1
/* Have gethostbyname */
#cmakedefine HAVE_GETHOSTBYNAME 1
/* Have getprotobyname */
#cmakedefine HAVE_GETPROTOBYNAME 1
/* Have getprotobyname_r */
#cmakedefine HAVE_GETPROTOBYNAME_R 1
/* Have getnameinfo */
#cmakedefine HAVE_GETNAMEINFO 1
/* Have inet_ntop */
#cmakedefine HAVE_INET_NTOP 1
/* Have inet_pton */
#cmakedefine HAVE_INET_PTON 1
/* Define to 1 if you have the `inet_aton' function. */
#cmakedefine HAVE_INET_ATON 1
/* Define to 1 if you have the <pthread.h> header file. */
#cmakedefine HAVE_PTHREAD_H 1
/* Define to 1 if you have the <pthread_np.h> header file. */
#cmakedefine HAVE_PTHREAD_NP_H 1
/* Define to 1 if you have the `pthread_mutex_timedlock' function. */
#cmakedefine HAVE_PTHREAD_MUTEX_TIMEDLOCK 1
/* Define to 1 if you have the `pthread_getattr_np' function. */
#cmakedefine HAVE_PTHREAD_GETATTR_NP 1
/* Define to 1 if you have the `pthread_attr_get_np' function. */
#cmakedefine HAVE_PTHREAD_ATTR_GET_NP 1
/* Define to 1 if you have the `pthread_getname_np' function. */
#cmakedefine HAVE_PTHREAD_GETNAME_NP 1
/* Define to 1 if you have the `pthread_setname_np' function. */
#cmakedefine HAVE_PTHREAD_SETNAME_NP 1
/* Define to 1 if you have the `pthread_cond_timedwait_relative_np' function.
*/
#cmakedefine HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP 1
/* Define to 1 if you have the `pthread_kill' function. */
#cmakedefine HAVE_PTHREAD_KILL 1
/* Define to 1 if you have the `pthread_attr_setstacksize' function. */
#cmakedefine HAVE_PTHREAD_ATTR_SETSTACKSIZE 1
/* Define to 1 if you have the `pthread_get_stackaddr_np' function. */
#cmakedefine HAVE_PTHREAD_GET_STACKADDR_NP 1
/* Define to 1 if you have the `pthread_jit_write_protect_np' function. */
#cmakedefine HAVE_PTHREAD_JIT_WRITE_PROTECT_NP 1
#cmakedefine01 HAVE_GETAUXVAL
/* Define to 1 if you have the declaration of `pthread_mutexattr_setprotocol',
and to 0 if you don't. */
#cmakedefine HAVE_DECL_PTHREAD_MUTEXATTR_SETPROTOCOL 1
/* Have a working sigaltstack */
#cmakedefine HAVE_WORKING_SIGALTSTACK 1
/* Define to 1 if you have the `shm_open' function. */
#cmakedefine HAVE_SHM_OPEN 1
/* Define to 1 if you have the `poll' function. */
#cmakedefine HAVE_POLL 1
/* epoll_create1 */
#cmakedefine HAVE_EPOLL 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#cmakedefine HAVE_NET_IF_H 1
/* Can get interface list */
#cmakedefine HAVE_SIOCGIFCONF 1
/* sockaddr_in has sin_len */
#cmakedefine HAVE_SOCKADDR_IN_SIN_LEN 1
/* sockaddr_in6 has sin6_len */
#cmakedefine HAVE_SOCKADDR_IN6_SIN_LEN 1
/* Have getifaddrs */
#cmakedefine HAVE_GETIFADDRS 1
/* Have struct ifaddrs */
#cmakedefine HAVE_IFADDRS 1
/* Have access */
#cmakedefine HAVE_ACCESS 1
/* Have getpid */
#cmakedefine HAVE_GETPID 1
/* Have mktemp */
#cmakedefine HAVE_MKTEMP 1
/* Define to 1 if you have the <sys/errno.h> header file. */
#cmakedefine HAVE_SYS_ERRNO_H 1
/* Define to 1 if you have the <sys/sendfile.h> header file. */
#cmakedefine HAVE_SYS_SENDFILE_H 1
/* Define to 1 if you have the <sys/statvfs.h> header file. */
#cmakedefine HAVE_SYS_STATVFS_H 1
/* Define to 1 if you have the <sys/statfs.h> header file. */
#cmakedefine HAVE_SYS_STATFS_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#cmakedefine HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/mount.h> header file. */
#cmakedefine HAVE_SYS_MOUNT_H 1
/* Define to 1 if you have the `getfsstat' function. */
#cmakedefine HAVE_GETFSSTAT 1
/* Define to 1 if you have the `mremap' function. */
#cmakedefine HAVE_MREMAP 1
/* Define to 1 if you have the `posix_fadvise' function. */
#cmakedefine HAVE_POSIX_FADVISE 1
/* Define to 1 if you have the `vsnprintf' function. */
#cmakedefine HAVE_VSNPRINTF 1
/* Define to 1 if you have the `sendfile' function. */
#cmakedefine HAVE_SENDFILE 1
/* struct statfs */
#cmakedefine HAVE_STATFS 1
/* Define to 1 if you have the `statvfs' function. */
#cmakedefine HAVE_STATVFS 1
/* Define to 1 if you have the `setpgid' function. */
#cmakedefine HAVE_SETPGID 1
/* Define to 1 if you have the `system' function. */
#ifdef _MSC_VER
#if HAVE_WINAPI_FAMILY_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
#cmakedefine HAVE_SYSTEM 1
#endif
#else
#cmakedefine HAVE_SYSTEM 1
#endif
/* Define to 1 if you have the `fork' function. */
#cmakedefine HAVE_FORK 1
/* Define to 1 if you have the `execv' function. */
#cmakedefine HAVE_EXECV 1
/* Define to 1 if you have the `execve' function. */
#cmakedefine HAVE_EXECVE 1
/* Define to 1 if you have the `waitpid' function. */
#cmakedefine HAVE_WAITPID 1
/* Define to 1 if you have the `localtime_r' function. */
#cmakedefine HAVE_LOCALTIME_R 1
/* Define to 1 if you have the `mkdtemp' function. */
#cmakedefine HAVE_MKDTEMP 1
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T @SIZEOF_SIZE_T@
#cmakedefine01 HAVE_GNU_STRERROR_R
/* Define to 1 if the system has the type `struct sockaddr'. */
#cmakedefine HAVE_STRUCT_SOCKADDR 1
/* Define to 1 if the system has the type `struct sockaddr_in'. */
#cmakedefine HAVE_STRUCT_SOCKADDR_IN 1
/* Define to 1 if the system has the type `struct sockaddr_in6'. */
#cmakedefine HAVE_STRUCT_SOCKADDR_IN6 1
/* Define to 1 if the system has the type `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT 1
/* Define to 1 if the system has the type `struct timeval'. */
#cmakedefine HAVE_STRUCT_TIMEVAL 1
/* Define to 1 if `st_atim' is a member of `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT_ST_ATIM 1
/* Define to 1 if `st_atimespec' is a member of `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT_ST_ATIMESPEC 1
/* Define to 1 if `kp_proc' is a member of `struct kinfo_proc'. */
#cmakedefine HAVE_STRUCT_KINFO_PROC_KP_PROC 1
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <dirent.h> header file. */
#cmakedefine HAVE_DIRENT_H 1
/* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. */
#cmakedefine HAVE_COMMONCRYPTO_COMMONDIGEST_H 1
/* Define to 1 if you have the <sys/random.h> header file. */
#cmakedefine HAVE_SYS_RANDOM_H 1
/* Define to 1 if you have the `getrandom' function. */
#cmakedefine HAVE_GETRANDOM 1
/* Define to 1 if you have the `getentropy' function. */
#cmakedefine HAVE_GETENTROPY 1
/* Qp2getifaddrs */
#cmakedefine HAVE_QP2GETIFADDRS 1
/* Define to 1 if you have the `strlcpy' function. */
#cmakedefine HAVE_STRLCPY 1
/* Define to 1 if you have the <winternl.h> header file. */
#cmakedefine HAVE_WINTERNL_H 1
/* Have socklen_t */
#cmakedefine HAVE_SOCKLEN_T 1
/* Define to 1 if you have the `execvp' function. */
#cmakedefine HAVE_EXECVP 1
/* Name of /dev/random */
#define NAME_DEV_RANDOM @NAME_DEV_RANDOM@
/* Enable the allocation and indexing of arrays greater than Int32.MaxValue */
#cmakedefine MONO_BIG_ARRAYS 1
/* Enable DTrace probes */
#cmakedefine ENABLE_DTRACE 1
/* AOT cross offsets file */
#cmakedefine MONO_OFFSETS_FILE "@MONO_OFFSETS_FILE@"
/* Enable the LLVM back end */
#cmakedefine ENABLE_LLVM 1
/* Runtime support code for llvm enabled */
#cmakedefine ENABLE_LLVM_RUNTIME 1
/* 64 bit mode with 4 byte longs and pointers */
#cmakedefine MONO_ARCH_ILP32 1
/* The runtime is compiled for cross-compiling mode */
#cmakedefine MONO_CROSS_COMPILE 1
/* ... */
#cmakedefine TARGET_WASM 1
/* The JIT/AOT targets WatchOS */
#cmakedefine TARGET_WATCHOS 1
/* ... */
#cmakedefine TARGET_PS3 1
/* ... */
#cmakedefine __mono_ppc64__ 1
/* ... */
#cmakedefine TARGET_XBOX360 1
/* ... */
#cmakedefine TARGET_PS4 1
/* ... */
#cmakedefine DISABLE_HW_TRAPS 1
/* Target is RISC-V */
#cmakedefine TARGET_RISCV 1
/* Target is 32-bit RISC-V */
#cmakedefine TARGET_RISCV32 1
/* Target is 64-bit RISC-V */
#cmakedefine TARGET_RISCV64 1
/* ... */
#cmakedefine TARGET_X86 1
/* ... */
#cmakedefine TARGET_AMD64 1
/* ... */
#cmakedefine TARGET_ARM 1
/* ... */
#cmakedefine TARGET_ARM64 1
/* ... */
#cmakedefine TARGET_POWERPC 1
/* ... */
#cmakedefine TARGET_POWERPC64 1
/* ... */
#cmakedefine TARGET_S390X 1
/* ... */
#cmakedefine TARGET_MIPS 1
/* ... */
#cmakedefine TARGET_SPARC 1
/* ... */
#cmakedefine TARGET_SPARC64 1
/* ... */
#cmakedefine HOST_WASM 1
/* ... */
#cmakedefine HOST_BROWSER 1
/* ... */
#cmakedefine HOST_WASI 1
/* ... */
#cmakedefine HOST_X86 1
/* ... */
#cmakedefine HOST_AMD64 1
/* ... */
#cmakedefine HOST_ARM 1
/* ... */
#cmakedefine HOST_ARM64 1
/* ... */
#cmakedefine HOST_POWERPC 1
/* ... */
#cmakedefine HOST_POWERPC64 1
/* ... */
#cmakedefine HOST_S390X 1
/* ... */
#cmakedefine HOST_MIPS 1
/* ... */
#cmakedefine HOST_SPARC 1
/* ... */
#cmakedefine HOST_SPARC64 1
/* Host is RISC-V */
#cmakedefine HOST_RISCV 1
/* Host is 32-bit RISC-V */
#cmakedefine HOST_RISCV32 1
/* Host is 64-bit RISC-V */
#cmakedefine HOST_RISCV64 1
/* ... */
#cmakedefine USE_GCC_ATOMIC_OPS 1
/* The JIT/AOT targets iOS */
#cmakedefine TARGET_IOS 1
/* The JIT/AOT targets tvOS */
#cmakedefine TARGET_TVOS 1
/* The JIT/AOT targets Mac Catalyst */
#cmakedefine TARGET_MACCAT 1
/* The JIT/AOT targets OSX */
#cmakedefine TARGET_OSX 1
/* The JIT/AOT targets Apple platforms */
#cmakedefine TARGET_MACH 1
/* byte order of target */
#define TARGET_BYTE_ORDER @TARGET_BYTE_ORDER@
/* wordsize of target */
#define TARGET_SIZEOF_VOID_P @TARGET_SIZEOF_VOID_P@
/* size of target machine integer registers */
#define SIZEOF_REGISTER @SIZEOF_REGISTER@
/* host or target doesn't allow unaligned memory access */
#cmakedefine NO_UNALIGNED_ACCESS 1
/* Support for the visibility ("hidden") attribute */
#cmakedefine HAVE_VISIBILITY_HIDDEN 1
/* Support for the deprecated attribute */
#cmakedefine HAVE_DEPRECATED 1
/* Moving collector */
#cmakedefine HAVE_MOVING_COLLECTOR 1
/* Defaults to concurrent GC */
#cmakedefine HAVE_CONC_GC_AS_DEFAULT 1
/* Define to 1 if you have the `stpcpy' function. */
#cmakedefine HAVE_STPCPY 1
/* Define to 1 if you have the `strtok_r' function. */
#cmakedefine HAVE_STRTOK_R 1
/* Define to 1 if you have the `rewinddir' function. */
#cmakedefine HAVE_REWINDDIR 1
/* Define to 1 if you have the `vasprintf' function. */
#cmakedefine HAVE_VASPRINTF 1
/* Overridable allocator support enabled */
#cmakedefine ENABLE_OVERRIDABLE_ALLOCATORS 1
/* Define to 1 if you have the `strndup' function. */
#cmakedefine HAVE_STRNDUP 1
/* Define to 1 if you have the <getopt.h> header file. */
#cmakedefine HAVE_GETOPT_H 1
/* Icall symbol map enabled */
#cmakedefine ENABLE_ICALL_SYMBOL_MAP 1
/* Icall export enabled */
#cmakedefine ENABLE_ICALL_EXPORT 1
/* Icall tables disabled */
#cmakedefine DISABLE_ICALL_TABLES 1
/* QCalls disabled */
#cmakedefine DISABLE_QCALLS 1
/* Embedded PDB support disabled */
#cmakedefine DISABLE_EMBEDDED_PDB
/* log profiler compressed output disabled */
#cmakedefine DISABLE_LOG_PROFILER_GZ
/* Have __thread keyword */
#cmakedefine MONO_KEYWORD_THREAD @MONO_KEYWORD_THREAD@
/* tls_model available */
#cmakedefine HAVE_TLS_MODEL_ATTR 1
/* ARM v5 */
#cmakedefine HAVE_ARMV5 1
/* ARM v6 */
#cmakedefine HAVE_ARMV6 1
/* ARM v7 */
#cmakedefine HAVE_ARMV7 1
/* RISC-V FPABI is double-precision */
#cmakedefine RISCV_FPABI_DOUBLE 1
/* RISC-V FPABI is single-precision */
#cmakedefine RISCV_FPABI_SINGLE 1
/* RISC-V FPABI is soft float */
#cmakedefine RISCV_FPABI_SOFT 1
/* Use malloc for each single mempool allocation */
#cmakedefine USE_MALLOC_FOR_MEMPOOLS 1
/* Enable lazy gc thread creation by the embedding host. */
#cmakedefine LAZY_GC_THREAD_CREATION 1
/* Enable cooperative stop-the-world garbage collection. */
#cmakedefine ENABLE_COOP_SUSPEND 1
/* Enable hybrid suspend for GC stop-the-world */
#cmakedefine ENABLE_HYBRID_SUSPEND 1
/* Enable feature experiments */
#cmakedefine ENABLE_EXPERIMENTS 1
/* Enable experiment 'null' */
#cmakedefine ENABLE_EXPERIMENT_null 1
/* Enable experiment 'Tiered Compilation' */
#cmakedefine ENABLE_EXPERIMENT_TIERED 1
/* Enable checked build */
#cmakedefine ENABLE_CHECKED_BUILD 1
/* Enable GC checked build */
#cmakedefine ENABLE_CHECKED_BUILD_GC 1
/* Enable metadata checked build */
#cmakedefine ENABLE_CHECKED_BUILD_METADATA 1
/* Enable thread checked build */
#cmakedefine ENABLE_CHECKED_BUILD_THREAD 1
/* Enable private types checked build */
#cmakedefine ENABLE_CHECKED_BUILD_PRIVATE_TYPES 1
/* Enable EventPipe library support */
#cmakedefine ENABLE_PERFTRACING 1
/* Define to 1 if you have /usr/include/malloc.h. */
#cmakedefine HAVE_USR_INCLUDE_MALLOC_H 1
/* The architecture this is running on */
#define MONO_ARCHITECTURE @MONO_ARCHITECTURE@
/* Disable banned functions from being used by the runtime */
#cmakedefine MONO_INSIDE_RUNTIME 1
/* Version number of package */
#define VERSION @VERSION@
/* Full version number of package */
#define FULL_VERSION @FULL_VERSION@
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H 1
/* Enable lazy gc thread creation by the embedding host */
#cmakedefine LAZY_GC_THREAD_CREATION 1
/* Enable additional checks */
#cmakedefine ENABLE_CHECKED_BUILD 1
/* Enable compile time checking that getter functions are used */
#cmakedefine ENABLE_CHECKED_BUILD_PRIVATE_TYPES 1
/* Enable runtime GC Safe / Unsafe mode assertion checks (must set env var MONO_CHECK_MODE=gc) */
#cmakedefine ENABLE_CHECKED_BUILD_GC 1
/* Enable runtime history of per-thread coop state transitions (must set env var MONO_CHECK_MODE=thread) */
#cmakedefine ENABLE_CHECKED_BUILD_THREAD 1
/* Enable runtime checks of mempool references between metadata images (must set env var MONO_CHECK_MODE=metadata) */
#cmakedefine ENABLE_CHECKED_BUILD_METADATA 1
/* Enable static linking of mono runtime components */
#cmakedefine STATIC_COMPONENTS
/* Enable perf jit dump support */
#cmakedefine ENABLE_JIT_DUMP 1
#if defined(ENABLE_LLVM) && defined(HOST_WIN32) && defined(TARGET_WIN32) && (!defined(TARGET_AMD64) || !defined(_MSC_VER))
#error LLVM for host=Windows and target=Windows is only supported on x64 MSVC build.
#endif
#endif
| #ifndef __MONO_CONFIG_H__
#define __MONO_CONFIG_H__
#ifdef _MSC_VER
// FIXME This is all questionable but the logs are flooded and nothing else is fixing them.
#pragma warning(disable:4018) // signed/unsigned mismatch
#pragma warning(disable:4090) // const problem
#pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned
#pragma warning(disable:4244) // integer conversion, possible loss of data
#pragma warning(disable:4267) // integer conversion, possible loss of data
// promote warnings to errors
#pragma warning( error:4013) // function undefined; assuming extern returning int
#pragma warning( error:4022) // call and prototype disagree
#pragma warning( error:4047) // differs in level of indirection
#pragma warning( error:4098) // void return returns a value
#pragma warning( error:4113) // call and prototype disagree
#pragma warning( error:4172) // returning address of local variable or temporary
#pragma warning( error:4197) // top-level volatile in cast is ignored
#pragma warning( error:4273) // inconsistent dll linkage
#pragma warning( error:4293) // shift count negative or too big, undefined behavior
#pragma warning( error:4312) // 'type cast': conversion from 'MonoNativeThreadId' to 'gpointer' of greater size
#pragma warning( error:4715) // 'keyword' not all control paths return a value
#include <SDKDDKVer.h>
#if _WIN32_WINNT < 0x0601
#error "Mono requires Windows 7 or later."
#endif /* _WIN32_WINNT < 0x0601 */
#ifndef HAVE_WINAPI_FAMILY_SUPPORT
#define HAVE_WINAPI_FAMILY_SUPPORT
/* WIN API Family support */
#include <winapifamily.h>
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#define HAVE_CLASSIC_WINAPI_SUPPORT 1
#define HAVE_UWP_WINAPI_SUPPORT 0
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
#define HAVE_CLASSIC_WINAPI_SUPPORT 0
#define HAVE_UWP_WINAPI_SUPPORT 1
#else
#define HAVE_CLASSIC_WINAPI_SUPPORT 0
#define HAVE_UWP_WINAPI_SUPPORT 0
#ifndef HAVE_EXTERN_DEFINED_WINAPI_SUPPORT
#error Unsupported WINAPI family
#endif
#endif
#endif
#endif
/* This platform does not support symlinks */
#cmakedefine HOST_NO_SYMLINKS 1
/* pthread is a pointer */
#cmakedefine PTHREAD_POINTER_ID 1
/* Targeting the Android platform */
#cmakedefine HOST_ANDROID 1
/* ... */
#cmakedefine TARGET_ANDROID 1
/* ... */
#cmakedefine USE_MACH_SEMA 1
/* Targeting the Fuchsia platform */
#cmakedefine HOST_FUCHSIA 1
/* Targeting the AIX and PASE platforms */
#cmakedefine HOST_AIX 1
/* Host Platform is Win32 */
#cmakedefine HOST_WIN32 1
/* Target Platform is Win32 */
#cmakedefine TARGET_WIN32 1
/* Host Platform is Darwin */
#cmakedefine HOST_DARWIN 1
/* Host Platform is iOS */
#cmakedefine HOST_IOS 1
/* Host Platform is tvOS */
#cmakedefine HOST_TVOS 1
/* Host Platform is Mac Catalyst */
#cmakedefine HOST_MACCAT 1
/* Use classic Windows API support */
#cmakedefine HAVE_CLASSIC_WINAPI_SUPPORT 1
/* Don't use UWP Windows API support */
#cmakedefine HAVE_UWP_WINAPI_SUPPORT 1
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H 1
/* Define to 1 if you have the <signal.h> header file. */
#cmakedefine HAVE_SIGNAL_H 1
/* Define to 1 if you have the <setjmp.h> header file. */
#cmakedefine HAVE_SETJMP_H 1
/* Define to 1 if you have the <syslog.h> header file. */
#cmakedefine HAVE_SYSLOG_H 1
/* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>.
*/
#cmakedefine MAJOR_IN_MKDEV 1
/* Define to 1 if `major', `minor', and `makedev' are declared in
<sysmacros.h>. */
#cmakedefine MAJOR_IN_SYSMACROS 1
/* Define to 1 if you have the <sys/filio.h> header file. */
#cmakedefine HAVE_SYS_FILIO_H 1
/* Define to 1 if you have the <sys/sockio.h> header file. */
#cmakedefine HAVE_SYS_SOCKIO_H 1
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine HAVE_NETDB_H 1
/* Define to 1 if you have the <utime.h> header file. */
#cmakedefine HAVE_UTIME_H 1
/* Define to 1 if you have the <sys/utime.h> header file. */
#cmakedefine HAVE_SYS_UTIME_H 1
/* Define to 1 if you have the <semaphore.h> header file. */
#cmakedefine HAVE_SEMAPHORE_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#cmakedefine HAVE_SYS_UN_H 1
/* Define to 1 if you have the <sys/syscall.h> header file. */
#cmakedefine HAVE_SYS_SYSCALL_H 1
/* Define to 1 if you have the <sys/uio.h> header file. */
#cmakedefine HAVE_SYS_UIO_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/sysctl.h> header file. */
#cmakedefine HAVE_SYS_SYSCTL_H 1
/* Define to 1 if you have the <libproc.h> header file. */
#cmakedefine HAVE_LIBPROC_H 1
/* Define to 1 if you have the <sys/prctl.h> header file. */
#cmakedefine HAVE_SYS_PRCTL_H 1
/* Define to 1 if you have the <gnu/lib-names.h> header file. */
#cmakedefine HAVE_GNU_LIB_NAMES_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#cmakedefine HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/utsname.h> header file. */
#cmakedefine HAVE_SYS_UTSNAME_H 1
/* Define to 1 if you have the <alloca.h> header file. */
#cmakedefine HAVE_ALLOCA_H 1
/* Define to 1 if you have the <ucontext.h> header file. */
#cmakedefine HAVE_UCONTEXT_H 1
/* Define to 1 if you have the <pwd.h> header file. */
#cmakedefine HAVE_PWD_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#cmakedefine HAVE_NETINET_TCP_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <link.h> header file. */
#cmakedefine HAVE_LINK_H 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <unwind.h> header file. */
#cmakedefine HAVE_UNWIND_H 1
/* Define to 1 if you have the <sys/user.h> header file. */
#cmakedefine HAVE_SYS_USER_H 1
/* Use static ICU */
#cmakedefine STATIC_ICU 1
/* Use in-tree zlib */
#cmakedefine INTERNAL_ZLIB 1
/* Define to 1 if you have the <poll.h> header file. */
#cmakedefine HAVE_POLL_H 1
/* Define to 1 if you have the <sys/poll.h> header file. */
#cmakedefine HAVE_SYS_POLL_H 1
/* Define to 1 if you have the <sys/wait.h> header file. */
#cmakedefine HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the <wchar.h> header file. */
#cmakedefine HAVE_WCHAR_H 1
/* Define to 1 if you have the <linux/magic.h> header file. */
#cmakedefine HAVE_LINUX_MAGIC_H 1
/* Define to 1 if you have the <android/legacy_signal_inlines.h> header file.
*/
#cmakedefine HAVE_ANDROID_LEGACY_SIGNAL_INLINES_H 1
/* Define to 1 if you have the <android/ndk-version.h> header file. */
#cmakedefine HAVE_ANDROID_NDK_VERSION_H 1
/* Whether Android NDK unified headers are used */
#cmakedefine ANDROID_UNIFIED_HEADERS 1
/* The size of `void *', as computed by sizeof. */
#define SIZEOF_VOID_P @SIZEOF_VOID_P@
/* The size of `long', as computed by sizeof. */
#define SIZEOF_LONG @SIZEOF_LONG@
/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT @SIZEOF_INT@
/* The size of `long long', as computed by sizeof. */
#define SIZEOF_LONG_LONG @SIZEOF_LONG_LONG@
/* Xen-specific behaviour */
#cmakedefine MONO_XEN_OPT 1
/* Reduce runtime requirements (and capabilities) */
#cmakedefine MONO_SMALL_CONFIG 1
/* Make jemalloc assert for mono */
#cmakedefine MONO_JEMALLOC_ASSERT 1
/* Make jemalloc default for mono */
#cmakedefine MONO_JEMALLOC_DEFAULT 1
/* Enable jemalloc usage for mono */
#cmakedefine MONO_JEMALLOC_ENABLED 1
/* Do not include names of unmanaged functions in the crash dump */
#cmakedefine MONO_PRIVATE_CRASHES 1
/* Do not create structured crash files during unmanaged crashes */
#cmakedefine DISABLE_STRUCTURED_CRASH 1
/* String of disabled features */
#define DISABLED_FEATURES @DISABLED_FEATURES@
/* Disable AOT Compiler */
#cmakedefine DISABLE_AOT 1
/* Disable runtime debugging support */
#cmakedefine DISABLE_DEBUG 1
/* Disable reflection emit support */
#cmakedefine DISABLE_REFLECTION_EMIT 1
/* Disable support debug logging */
#cmakedefine DISABLE_LOGGING 1
/* Disable COM support */
#cmakedefine DISABLE_COM 1
/* Disable advanced SSA JIT optimizations */
#cmakedefine DISABLE_SSA 1
/* Disable the JIT, only full-aot mode or interpreter will be supported by the
runtime. */
#cmakedefine DISABLE_JIT 1
/* Disable the interpreter. */
#cmakedefine DISABLE_INTERPRETER 1
/* Some VES is available at runtime */
#cmakedefine ENABLE_ILGEN 1
/* Disable non-blittable marshalling */
#cmakedefine DISABLE_NONBLITTABLE
/* Disable SIMD intrinsics related optimizations. */
#cmakedefine DISABLE_SIMD 1
/* Disable Soft Debugger Agent. */
#cmakedefine DISABLE_DEBUGGER_AGENT 1
/* Disable Performance Counters. */
#cmakedefine DISABLE_PERFCOUNTERS 1
/* Disable shared perfcounters. */
#cmakedefine DISABLE_SHARED_PERFCOUNTERS 1
/* Disable support code for the LLDB plugin. */
#cmakedefine DISABLE_LLDB 1
/* Disable assertion messages. */
#cmakedefine DISABLE_ASSERT_MESSAGES 1
/* Disable concurrent gc support in SGEN. */
#cmakedefine DISABLE_SGEN_MAJOR_MARKSWEEP_CONC 1
/* Disable minor=split support in SGEN. */
#cmakedefine DISABLE_SGEN_SPLIT_NURSERY 1
/* Disable gc bridge support in SGEN. */
#cmakedefine DISABLE_SGEN_GC_BRIDGE 1
/* Disable debug helpers in SGEN. */
#cmakedefine DISABLE_SGEN_DEBUG_HELPERS 1
/* Disable sockets */
#cmakedefine DISABLE_SOCKETS 1
/* Disables use of DllMaps in MonoVM */
#cmakedefine DISABLE_DLLMAP 1
/* Disable Threads */
#cmakedefine DISABLE_THREADS 1
/* Disable perf counters */
#cmakedefine DISABLE_PERF_COUNTERS
/* Disable MONO_LOG_DEST */
#cmakedefine DISABLE_LOG_DEST
/* GC description */
#cmakedefine DEFAULT_GC_NAME 1
/* No GC support. */
#cmakedefine HAVE_NULL_GC 1
/* Length of zero length arrays */
#define MONO_ZERO_LEN_ARRAY @MONO_ZERO_LEN_ARRAY@
/* Define to 1 if you have the `sigaction' function. */
#cmakedefine HAVE_SIGACTION 1
/* Define to 1 if you have the `kill' function. */
#cmakedefine HAVE_KILL 1
/* CLOCK_MONOTONIC */
#cmakedefine HAVE_CLOCK_MONOTONIC 1
/* CLOCK_MONOTONIC_COARSE */
#cmakedefine HAVE_CLOCK_MONOTONIC_COARSE 1
/* clockid_t */
#cmakedefine HAVE_CLOCKID_T 1
/* mach_absolute_time */
#cmakedefine HAVE_MACH_ABSOLUTE_TIME 1
/* gethrtime */
#cmakedefine HAVE_GETHRTIME 1
/* read_real_time */
#cmakedefine HAVE_READ_REAL_TIME 1
/* Define to 1 if you have the `clock_nanosleep' function. */
#cmakedefine HAVE_CLOCK_NANOSLEEP 1
/* Does dlsym require leading underscore. */
#cmakedefine MONO_DL_NEED_USCORE 1
/* Define to 1 if you have the <execinfo.h> header file. */
#cmakedefine HAVE_EXECINFO_H 1
/* Define to 1 if you have the <sys/auxv.h> header file. */
#cmakedefine HAVE_SYS_AUXV_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H 1
/* kqueue */
#cmakedefine HAVE_KQUEUE 1
/* Define to 1 if you have the `backtrace_symbols' function. */
#cmakedefine HAVE_BACKTRACE_SYMBOLS 1
/* Define to 1 if you have the `mkstemp' function. */
#cmakedefine HAVE_MKSTEMP 1
/* Define to 1 if you have the `mmap' function. */
#cmakedefine HAVE_MMAP 1
/* Define to 1 if you have the `madvise' function. */
#cmakedefine HAVE_MADVISE 1
/* Define to 1 if you have the `getrusage' function. */
#cmakedefine HAVE_GETRUSAGE 1
/* Define to 1 if you have the `dladdr' function. */
#cmakedefine HAVE_DLADDR 1
/* Define to 1 if you have the `sysconf' function. */
#cmakedefine HAVE_SYSCONF 1
/* Define to 1 if you have the `getrlimit' function. */
#cmakedefine HAVE_GETRLIMIT 1
/* Define to 1 if you have the `prctl' function. */
#cmakedefine HAVE_PRCTL 1
/* Define to 1 if you have the `nl_langinfo' function. */
#cmakedefine HAVE_NL_LANGINFO 1
/* sched_getaffinity */
#cmakedefine HAVE_SCHED_GETAFFINITY 1
/* sched_setaffinity */
#cmakedefine HAVE_SCHED_SETAFFINITY 1
/* Define to 1 if you have the `sched_getcpu' function. */
#cmakedefine HAVE_SCHED_GETCPU 1
/* Define to 1 if you have the `getpwuid_r' function. */
#cmakedefine HAVE_GETPWUID_R 1
/* Define to 1 if you have the `readlink' function. */
#cmakedefine HAVE_READLINK 1
/* Define to 1 if you have the `chmod' function. */
#cmakedefine HAVE_CHMOD 1
/* Define to 1 if you have the `lstat' function. */
#cmakedefine HAVE_LSTAT 1
/* Define to 1 if you have the `getdtablesize' function. */
#cmakedefine HAVE_GETDTABLESIZE 1
/* Define to 1 if you have the `ftruncate' function. */
#cmakedefine HAVE_FTRUNCATE 1
/* Define to 1 if you have the `msync' function. */
#cmakedefine HAVE_MSYNC 1
/* Define to 1 if you have the `getpeername' function. */
#cmakedefine HAVE_GETPEERNAME 1
/* Define to 1 if you have the `utime' function. */
#cmakedefine HAVE_UTIME 1
/* Define to 1 if you have the `utimes' function. */
#cmakedefine HAVE_UTIMES 1
/* Define to 1 if you have the `openlog' function. */
#cmakedefine HAVE_OPENLOG 1
/* Define to 1 if you have the `closelog' function. */
#cmakedefine HAVE_CLOSELOG 1
/* Define to 1 if you have the `atexit' function. */
#cmakedefine HAVE_ATEXIT 1
/* Define to 1 if you have the `popen' function. */
#cmakedefine HAVE_POPEN 1
/* Define to 1 if you have the `strerror_r' function. */
#cmakedefine HAVE_STRERROR_R 1
/* Have GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY */
#cmakedefine GLIBC_BEFORE_2_3_4_SCHED_SETAFFINITY 1
/* GLIBC has CPU_COUNT macro in sched.h */
#cmakedefine HAVE_GNU_CPU_COUNT
/* Have large file support */
#cmakedefine HAVE_LARGE_FILE_SUPPORT 1
/* Have getaddrinfo */
#cmakedefine HAVE_GETADDRINFO 1
/* Have gethostbyname2 */
#cmakedefine HAVE_GETHOSTBYNAME2 1
/* Have gethostbyname */
#cmakedefine HAVE_GETHOSTBYNAME 1
/* Have getprotobyname */
#cmakedefine HAVE_GETPROTOBYNAME 1
/* Have getprotobyname_r */
#cmakedefine HAVE_GETPROTOBYNAME_R 1
/* Have getnameinfo */
#cmakedefine HAVE_GETNAMEINFO 1
/* Have inet_ntop */
#cmakedefine HAVE_INET_NTOP 1
/* Have inet_pton */
#cmakedefine HAVE_INET_PTON 1
/* Define to 1 if you have the `inet_aton' function. */
#cmakedefine HAVE_INET_ATON 1
/* Define to 1 if you have the <pthread.h> header file. */
#cmakedefine HAVE_PTHREAD_H 1
/* Define to 1 if you have the <pthread_np.h> header file. */
#cmakedefine HAVE_PTHREAD_NP_H 1
/* Define to 1 if you have the `pthread_mutex_timedlock' function. */
#cmakedefine HAVE_PTHREAD_MUTEX_TIMEDLOCK 1
/* Define to 1 if you have the `pthread_getattr_np' function. */
#cmakedefine HAVE_PTHREAD_GETATTR_NP 1
/* Define to 1 if you have the `pthread_attr_get_np' function. */
#cmakedefine HAVE_PTHREAD_ATTR_GET_NP 1
/* Define to 1 if you have the `pthread_getname_np' function. */
#cmakedefine HAVE_PTHREAD_GETNAME_NP 1
/* Define to 1 if you have the `pthread_setname_np' function. */
#cmakedefine HAVE_PTHREAD_SETNAME_NP 1
/* Define to 1 if you have the `pthread_cond_timedwait_relative_np' function.
*/
#cmakedefine HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP 1
/* Define to 1 if you have the `pthread_kill' function. */
#cmakedefine HAVE_PTHREAD_KILL 1
/* Define to 1 if you have the `pthread_attr_setstacksize' function. */
#cmakedefine HAVE_PTHREAD_ATTR_SETSTACKSIZE 1
/* Define to 1 if you have the `pthread_get_stackaddr_np' function. */
#cmakedefine HAVE_PTHREAD_GET_STACKADDR_NP 1
/* Define to 1 if you have the `pthread_jit_write_protect_np' function. */
#cmakedefine HAVE_PTHREAD_JIT_WRITE_PROTECT_NP 1
#cmakedefine01 HAVE_GETAUXVAL
/* Define to 1 if you have the declaration of `pthread_mutexattr_setprotocol',
and to 0 if you don't. */
#cmakedefine HAVE_DECL_PTHREAD_MUTEXATTR_SETPROTOCOL 1
/* Have a working sigaltstack */
#cmakedefine HAVE_WORKING_SIGALTSTACK 1
/* Define to 1 if you have the `shm_open' function. */
#cmakedefine HAVE_SHM_OPEN 1
/* Define to 1 if you have the `poll' function. */
#cmakedefine HAVE_POLL 1
/* epoll_create1 */
#cmakedefine HAVE_EPOLL 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#cmakedefine HAVE_NET_IF_H 1
/* Can get interface list */
#cmakedefine HAVE_SIOCGIFCONF 1
/* sockaddr_in has sin_len */
#cmakedefine HAVE_SOCKADDR_IN_SIN_LEN 1
/* sockaddr_in6 has sin6_len */
#cmakedefine HAVE_SOCKADDR_IN6_SIN_LEN 1
/* Have getifaddrs */
#cmakedefine HAVE_GETIFADDRS 1
/* Have struct ifaddrs */
#cmakedefine HAVE_IFADDRS 1
/* Have access */
#cmakedefine HAVE_ACCESS 1
/* Have getpid */
#cmakedefine HAVE_GETPID 1
/* Have mktemp */
#cmakedefine HAVE_MKTEMP 1
/* Define to 1 if you have the <sys/errno.h> header file. */
#cmakedefine HAVE_SYS_ERRNO_H 1
/* Define to 1 if you have the <sys/sendfile.h> header file. */
#cmakedefine HAVE_SYS_SENDFILE_H 1
/* Define to 1 if you have the <sys/statvfs.h> header file. */
#cmakedefine HAVE_SYS_STATVFS_H 1
/* Define to 1 if you have the <sys/statfs.h> header file. */
#cmakedefine HAVE_SYS_STATFS_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#cmakedefine HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/mount.h> header file. */
#cmakedefine HAVE_SYS_MOUNT_H 1
/* Define to 1 if you have the `getfsstat' function. */
#cmakedefine HAVE_GETFSSTAT 1
/* Define to 1 if you have the `mremap' function. */
#cmakedefine HAVE_MREMAP 1
/* Define to 1 if you have the `posix_fadvise' function. */
#cmakedefine HAVE_POSIX_FADVISE 1
/* Define to 1 if you have the `vsnprintf' function. */
#cmakedefine HAVE_VSNPRINTF 1
/* Define to 1 if you have the `sendfile' function. */
#cmakedefine HAVE_SENDFILE 1
/* struct statfs */
#cmakedefine HAVE_STATFS 1
/* Define to 1 if you have the `statvfs' function. */
#cmakedefine HAVE_STATVFS 1
/* Define to 1 if you have the `setpgid' function. */
#cmakedefine HAVE_SETPGID 1
/* Define to 1 if you have the `system' function. */
#ifdef _MSC_VER
#if HAVE_WINAPI_FAMILY_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
#cmakedefine HAVE_SYSTEM 1
#endif
#else
#cmakedefine HAVE_SYSTEM 1
#endif
/* Define to 1 if you have the `fork' function. */
#cmakedefine HAVE_FORK 1
/* Define to 1 if you have the `execv' function. */
#cmakedefine HAVE_EXECV 1
/* Define to 1 if you have the `execve' function. */
#cmakedefine HAVE_EXECVE 1
/* Define to 1 if you have the `waitpid' function. */
#cmakedefine HAVE_WAITPID 1
/* Define to 1 if you have the `localtime_r' function. */
#cmakedefine HAVE_LOCALTIME_R 1
/* Define to 1 if you have the `mkdtemp' function. */
#cmakedefine HAVE_MKDTEMP 1
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T @SIZEOF_SIZE_T@
#cmakedefine01 HAVE_GNU_STRERROR_R
/* Define to 1 if the system has the type `struct sockaddr'. */
#cmakedefine HAVE_STRUCT_SOCKADDR 1
/* Define to 1 if the system has the type `struct sockaddr_in'. */
#cmakedefine HAVE_STRUCT_SOCKADDR_IN 1
/* Define to 1 if the system has the type `struct sockaddr_in6'. */
#cmakedefine HAVE_STRUCT_SOCKADDR_IN6 1
/* Define to 1 if the system has the type `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT 1
/* Define to 1 if the system has the type `struct timeval'. */
#cmakedefine HAVE_STRUCT_TIMEVAL 1
/* Define to 1 if `st_atim' is a member of `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT_ST_ATIM 1
/* Define to 1 if `st_atimespec' is a member of `struct stat'. */
#cmakedefine HAVE_STRUCT_STAT_ST_ATIMESPEC 1
/* Define to 1 if `kp_proc' is a member of `struct kinfo_proc'. */
#cmakedefine HAVE_STRUCT_KINFO_PROC_KP_PROC 1
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <dirent.h> header file. */
#cmakedefine HAVE_DIRENT_H 1
/* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. */
#cmakedefine HAVE_COMMONCRYPTO_COMMONDIGEST_H 1
/* Define to 1 if you have the <sys/random.h> header file. */
#cmakedefine HAVE_SYS_RANDOM_H 1
/* Define to 1 if you have the `getrandom' function. */
#cmakedefine HAVE_GETRANDOM 1
/* Define to 1 if you have the `getentropy' function. */
#cmakedefine HAVE_GETENTROPY 1
/* Qp2getifaddrs */
#cmakedefine HAVE_QP2GETIFADDRS 1
/* Define to 1 if you have the `strlcpy' function. */
#cmakedefine HAVE_STRLCPY 1
/* Define to 1 if you have the <winternl.h> header file. */
#cmakedefine HAVE_WINTERNL_H 1
/* Have socklen_t */
#cmakedefine HAVE_SOCKLEN_T 1
/* Define to 1 if you have the `execvp' function. */
#cmakedefine HAVE_EXECVP 1
/* Name of /dev/random */
#define NAME_DEV_RANDOM @NAME_DEV_RANDOM@
/* Enable the allocation and indexing of arrays greater than Int32.MaxValue */
#cmakedefine MONO_BIG_ARRAYS 1
/* Enable DTrace probes */
#cmakedefine ENABLE_DTRACE 1
/* AOT cross offsets file */
#cmakedefine MONO_OFFSETS_FILE "@MONO_OFFSETS_FILE@"
/* Enable the LLVM back end */
#cmakedefine ENABLE_LLVM 1
/* Runtime support code for llvm enabled */
#cmakedefine ENABLE_LLVM_RUNTIME 1
/* 64 bit mode with 4 byte longs and pointers */
#cmakedefine MONO_ARCH_ILP32 1
/* The runtime is compiled for cross-compiling mode */
#cmakedefine MONO_CROSS_COMPILE 1
/* ... */
#cmakedefine TARGET_WASM 1
/* The JIT/AOT targets WatchOS */
#cmakedefine TARGET_WATCHOS 1
/* ... */
#cmakedefine TARGET_PS3 1
/* ... */
#cmakedefine __mono_ppc64__ 1
/* ... */
#cmakedefine TARGET_XBOX360 1
/* ... */
#cmakedefine TARGET_PS4 1
/* ... */
#cmakedefine DISABLE_HW_TRAPS 1
/* Target is RISC-V */
#cmakedefine TARGET_RISCV 1
/* Target is 32-bit RISC-V */
#cmakedefine TARGET_RISCV32 1
/* Target is 64-bit RISC-V */
#cmakedefine TARGET_RISCV64 1
/* ... */
#cmakedefine TARGET_X86 1
/* ... */
#cmakedefine TARGET_AMD64 1
/* ... */
#cmakedefine TARGET_ARM 1
/* ... */
#cmakedefine TARGET_ARM64 1
/* ... */
#cmakedefine TARGET_POWERPC 1
/* ... */
#cmakedefine TARGET_POWERPC64 1
/* ... */
#cmakedefine TARGET_S390X 1
/* ... */
#cmakedefine TARGET_MIPS 1
/* ... */
#cmakedefine TARGET_SPARC 1
/* ... */
#cmakedefine TARGET_SPARC64 1
/* ... */
#cmakedefine HOST_WASM 1
/* ... */
#cmakedefine HOST_BROWSER 1
/* ... */
#cmakedefine HOST_WASI 1
/* ... */
#cmakedefine HOST_X86 1
/* ... */
#cmakedefine HOST_AMD64 1
/* ... */
#cmakedefine HOST_ARM 1
/* ... */
#cmakedefine HOST_ARM64 1
/* ... */
#cmakedefine HOST_POWERPC 1
/* ... */
#cmakedefine HOST_POWERPC64 1
/* ... */
#cmakedefine HOST_S390X 1
/* ... */
#cmakedefine HOST_MIPS 1
/* ... */
#cmakedefine HOST_SPARC 1
/* ... */
#cmakedefine HOST_SPARC64 1
/* Host is RISC-V */
#cmakedefine HOST_RISCV 1
/* Host is 32-bit RISC-V */
#cmakedefine HOST_RISCV32 1
/* Host is 64-bit RISC-V */
#cmakedefine HOST_RISCV64 1
/* ... */
#cmakedefine USE_GCC_ATOMIC_OPS 1
/* The JIT/AOT targets iOS */
#cmakedefine TARGET_IOS 1
/* The JIT/AOT targets tvOS */
#cmakedefine TARGET_TVOS 1
/* The JIT/AOT targets Mac Catalyst */
#cmakedefine TARGET_MACCAT 1
/* The JIT/AOT targets OSX */
#cmakedefine TARGET_OSX 1
/* The JIT/AOT targets Apple platforms */
#cmakedefine TARGET_MACH 1
/* byte order of target */
#define TARGET_BYTE_ORDER @TARGET_BYTE_ORDER@
/* wordsize of target */
#define TARGET_SIZEOF_VOID_P @TARGET_SIZEOF_VOID_P@
/* size of target machine integer registers */
#define SIZEOF_REGISTER @SIZEOF_REGISTER@
/* host or target doesn't allow unaligned memory access */
#cmakedefine NO_UNALIGNED_ACCESS 1
/* Support for the visibility ("hidden") attribute */
#cmakedefine HAVE_VISIBILITY_HIDDEN 1
/* Support for the deprecated attribute */
#cmakedefine HAVE_DEPRECATED 1
/* Moving collector */
#cmakedefine HAVE_MOVING_COLLECTOR 1
/* Defaults to concurrent GC */
#cmakedefine HAVE_CONC_GC_AS_DEFAULT 1
/* Define to 1 if you have the `stpcpy' function. */
#cmakedefine HAVE_STPCPY 1
/* Define to 1 if you have the `strtok_r' function. */
#cmakedefine HAVE_STRTOK_R 1
/* Define to 1 if you have the `rewinddir' function. */
#cmakedefine HAVE_REWINDDIR 1
/* Define to 1 if you have the `vasprintf' function. */
#cmakedefine HAVE_VASPRINTF 1
/* Overridable allocator support enabled */
#cmakedefine ENABLE_OVERRIDABLE_ALLOCATORS 1
/* Define to 1 if you have the `strndup' function. */
#cmakedefine HAVE_STRNDUP 1
/* Define to 1 if you have the <getopt.h> header file. */
#cmakedefine HAVE_GETOPT_H 1
/* Icall symbol map enabled */
#cmakedefine ENABLE_ICALL_SYMBOL_MAP 1
/* Icall export enabled */
#cmakedefine ENABLE_ICALL_EXPORT 1
/* Icall tables disabled */
#cmakedefine DISABLE_ICALL_TABLES 1
/* QCalls disabled */
#cmakedefine DISABLE_QCALLS 1
/* Embedded PDB support disabled */
#cmakedefine DISABLE_EMBEDDED_PDB
/* log profiler compressed output disabled */
#cmakedefine DISABLE_LOG_PROFILER_GZ
/* Have __thread keyword */
#cmakedefine MONO_KEYWORD_THREAD @MONO_KEYWORD_THREAD@
/* tls_model available */
#cmakedefine HAVE_TLS_MODEL_ATTR 1
/* ARM v5 */
#cmakedefine HAVE_ARMV5 1
/* ARM v6 */
#cmakedefine HAVE_ARMV6 1
/* ARM v7 */
#cmakedefine HAVE_ARMV7 1
/* RISC-V FPABI is double-precision */
#cmakedefine RISCV_FPABI_DOUBLE 1
/* RISC-V FPABI is single-precision */
#cmakedefine RISCV_FPABI_SINGLE 1
/* RISC-V FPABI is soft float */
#cmakedefine RISCV_FPABI_SOFT 1
/* Use malloc for each single mempool allocation */
#cmakedefine USE_MALLOC_FOR_MEMPOOLS 1
/* Enable lazy gc thread creation by the embedding host. */
#cmakedefine LAZY_GC_THREAD_CREATION 1
/* Enable cooperative stop-the-world garbage collection. */
#cmakedefine ENABLE_COOP_SUSPEND 1
/* Enable hybrid suspend for GC stop-the-world */
#cmakedefine ENABLE_HYBRID_SUSPEND 1
/* Enable feature experiments */
#cmakedefine ENABLE_EXPERIMENTS 1
/* Enable experiment 'null' */
#cmakedefine ENABLE_EXPERIMENT_null 1
/* Enable experiment 'Tiered Compilation' */
#cmakedefine ENABLE_EXPERIMENT_TIERED 1
/* Enable checked build */
#cmakedefine ENABLE_CHECKED_BUILD 1
/* Enable GC checked build */
#cmakedefine ENABLE_CHECKED_BUILD_GC 1
/* Enable metadata checked build */
#cmakedefine ENABLE_CHECKED_BUILD_METADATA 1
/* Enable thread checked build */
#cmakedefine ENABLE_CHECKED_BUILD_THREAD 1
/* Enable private types checked build */
#cmakedefine ENABLE_CHECKED_BUILD_PRIVATE_TYPES 1
/* Enable EventPipe library support */
#cmakedefine ENABLE_PERFTRACING 1
/* Define to 1 if you have /usr/include/malloc.h. */
#cmakedefine HAVE_USR_INCLUDE_MALLOC_H 1
/* The architecture this is running on */
#define MONO_ARCHITECTURE @MONO_ARCHITECTURE@
/* Disable banned functions from being used by the runtime */
#cmakedefine MONO_INSIDE_RUNTIME 1
/* Version number of package */
#define VERSION @VERSION@
/* Full version number of package */
#define FULL_VERSION @FULL_VERSION@
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H 1
/* Enable lazy gc thread creation by the embedding host */
#cmakedefine LAZY_GC_THREAD_CREATION 1
/* Enable additional checks */
#cmakedefine ENABLE_CHECKED_BUILD 1
/* Enable compile time checking that getter functions are used */
#cmakedefine ENABLE_CHECKED_BUILD_PRIVATE_TYPES 1
/* Enable runtime GC Safe / Unsafe mode assertion checks (must set env var MONO_CHECK_MODE=gc) */
#cmakedefine ENABLE_CHECKED_BUILD_GC 1
/* Enable runtime history of per-thread coop state transitions (must set env var MONO_CHECK_MODE=thread) */
#cmakedefine ENABLE_CHECKED_BUILD_THREAD 1
/* Enable runtime checks of mempool references between metadata images (must set env var MONO_CHECK_MODE=metadata) */
#cmakedefine ENABLE_CHECKED_BUILD_METADATA 1
/* Enable static linking of mono runtime components */
#cmakedefine STATIC_COMPONENTS
/* Enable perf jit dump support */
#cmakedefine ENABLE_JIT_DUMP 1
/* Enable System.WeakAttribute support */
#cmakedefine ENABLE_WEAK_ATTR 1
#if defined(ENABLE_LLVM) && defined(HOST_WIN32) && defined(TARGET_WIN32) && (!defined(TARGET_AMD64) || !defined(_MSC_VER))
#error LLVM for host=Windows and target=Windows is only supported on x64 MSVC build.
#endif
#endif
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/class-init.c | /**
* \file MonoClass construction and initialization
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2012 Xamarin Inc (http://www.xamarin.com)
* Copyright 2018 Microsoft
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include <config.h>
#include <mono/metadata/class-init.h>
#include <mono/metadata/class-init-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/marshal.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/unlocked.h>
#ifdef MONO_CLASS_DEF_PRIVATE
/* Class initialization gets to see the fields of MonoClass */
#define REALLY_INCLUDE_CLASS_DEF 1
#include <mono/metadata/class-private-definition.h>
#undef REALLY_INCLUDE_CLASS_DEF
#endif
#define FEATURE_COVARIANT_RETURNS
gboolean mono_print_vtable = FALSE;
gboolean mono_align_small_structs = FALSE;
/* Set by the EE */
gint32 mono_simd_register_size;
/* Statistics */
static gint32 classes_size;
static gint32 inflated_classes_size;
gint32 mono_inflated_methods_size;
static gint32 class_def_count, class_gtd_count, class_ginst_count, class_gparam_count, class_array_count, class_pointer_count;
/* Low level lock which protects data structures in this module */
static mono_mutex_t classes_mutex;
static gboolean class_kind_may_contain_generic_instances (MonoTypeKind kind);
static void mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd);
static int generic_array_methods (MonoClass *klass);
static void setup_generic_array_ifaces (MonoClass *klass, MonoClass *iface, MonoMethod **methods, int pos, GHashTable *cache);
static gboolean class_has_isbyreflike_attribute (MonoClass *klass);
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(icollection, "System.Collections.Generic", "ICollection`1");
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(ienumerable, "System.Collections.Generic", "IEnumerable`1");
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(ireadonlycollection, "System.Collections.Generic", "IReadOnlyCollection`1");
/* This TLS variable points to a GSList of classes which have setup_fields () executing */
static MonoNativeTlsKey setup_fields_tls_id;
static MonoNativeTlsKey init_pending_tls_id;
static void
classes_lock (void)
{
mono_locks_os_acquire (&classes_mutex, ClassesLock);
}
static void
classes_unlock (void)
{
mono_locks_os_release (&classes_mutex, ClassesLock);
}
/*
We use gclass recording to allow recursive system f types to be referenced by a parent.
Given the following type hierarchy:
class TextBox : TextBoxBase<TextBox> {}
class TextBoxBase<T> : TextInput<TextBox> where T : TextBoxBase<T> {}
class TextInput<T> : Input<T> where T: TextInput<T> {}
class Input<T> {}
The runtime tries to load TextBoxBase<>.
To load TextBoxBase<> to do so it must resolve the parent which is TextInput<TextBox>.
To instantiate TextInput<TextBox> it must resolve TextInput<> and TextBox.
To load TextBox it must resolve the parent which is TextBoxBase<TextBox>.
At this point the runtime must instantiate TextBoxBase<TextBox>. Both types are partially loaded
at this point, iow, both are registered in the type map and both and a NULL parent. This means
that the resulting generic instance will have a NULL parent, which is wrong and will cause breakage.
To fix that what we do is to record all generic instantes created while resolving the parent of
any generic type definition and, after resolved, correct the parent field if needed.
*/
static int record_gclass_instantiation;
static GSList *gclass_recorded_list;
typedef gboolean (*gclass_record_func) (MonoClass*, void*);
/*
* LOCKING: loader lock must be held until pairing disable_gclass_recording is called.
*/
static void
enable_gclass_recording (void)
{
++record_gclass_instantiation;
}
/*
* LOCKING: loader lock must be held since pairing enable_gclass_recording was called.
*/
static void
disable_gclass_recording (gclass_record_func func, void *user_data)
{
GSList **head = &gclass_recorded_list;
g_assert (record_gclass_instantiation > 0);
--record_gclass_instantiation;
while (*head) {
GSList *node = *head;
if (func ((MonoClass*)node->data, user_data)) {
*head = node->next;
g_slist_free_1 (node);
} else {
head = &node->next;
}
}
/* We automatically discard all recorded gclasses when disabled. */
if (!record_gclass_instantiation && gclass_recorded_list) {
g_slist_free (gclass_recorded_list);
gclass_recorded_list = NULL;
}
}
#define mono_class_new0(klass,struct_type, n_structs) \
((struct_type *) mono_class_alloc0 ((klass), ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
/**
* mono_class_setup_basic_field_info:
* \param class The class to initialize
*
* Initializes the following fields in MonoClass:
* * klass->fields (only field->parent and field->name)
* * klass->field.count
* * klass->first_field_idx
* LOCKING: Acquires the loader lock
*/
void
mono_class_setup_basic_field_info (MonoClass *klass)
{
MonoGenericClass *gklass;
MonoClassField *field;
MonoClassField *fields;
MonoClass *gtd;
MonoImage *image;
int i, top;
if (klass->fields)
return;
gklass = mono_class_try_get_generic_class (klass);
gtd = gklass ? mono_class_get_generic_type_definition (klass) : NULL;
image = klass->image;
if (gklass && image_is_dynamic (gklass->container_class->image) && !gklass->container_class->wastypebuilder) {
/*
* This happens when a generic instance of an unfinished generic typebuilder
* is used as an element type for creating an array type. We can't initialize
* the fields of this class using the fields of gklass, since gklass is not
* finished yet, fields could be added to it later.
*/
return;
}
if (gtd) {
mono_class_setup_basic_field_info (gtd);
mono_loader_lock ();
mono_class_set_field_count (klass, mono_class_get_field_count (gtd));
mono_loader_unlock ();
}
top = mono_class_get_field_count (klass);
fields = (MonoClassField *)mono_class_alloc0 (klass, sizeof (MonoClassField) * top);
/*
* Fetch all the field information.
*/
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
for (i = 0; i < top; i++) {
field = &fields [i];
m_field_set_parent (field, klass);
if (gtd) {
field->name = mono_field_get_name (>d->fields [i]);
} else {
int idx = first_field_idx + i;
/* first_field_idx and idx points into the fieldptr table */
guint32 name_idx = mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_NAME);
/* The name is needed for fieldrefs */
field->name = mono_metadata_string_heap (image, name_idx);
}
}
mono_memory_barrier ();
mono_loader_lock ();
if (!klass->fields)
klass->fields = fields;
mono_loader_unlock ();
}
/**
* mono_class_setup_fields:
* \p klass The class to initialize
*
* Initializes klass->fields, computes class layout and sizes.
* typebuilder_setup_fields () is the corresponding function for dynamic classes.
* Sets the following fields in \p klass:
* - all the fields initialized by mono_class_init_sizes ()
* - element_class/cast_class (for enums)
* - sizes:element_size (for arrays)
* - field->type/offset for all fields
* - fields_inited
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_fields (MonoClass *klass)
{
ERROR_DECL (error);
MonoImage *m = klass->image;
int top;
guint32 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
int i;
guint32 real_size = 0;
guint32 packing_size = 0;
int instance_size;
gboolean explicit_size;
MonoClassField *field;
MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
MonoClass *gtd = gklass ? mono_class_get_generic_type_definition (klass) : NULL;
if (klass->fields_inited)
return;
if (gklass && image_is_dynamic (gklass->container_class->image) && !gklass->container_class->wastypebuilder) {
/*
* This happens when a generic instance of an unfinished generic typebuilder
* is used as an element type for creating an array type. We can't initialize
* the fields of this class using the fields of gklass, since gklass is not
* finished yet, fields could be added to it later.
*/
return;
}
mono_class_setup_basic_field_info (klass);
top = mono_class_get_field_count (klass);
if (gtd) {
mono_class_setup_fields (gtd);
if (mono_class_set_type_load_failure_causedby_class (klass, gtd, "Generic type definition failed"))
return;
}
instance_size = 0;
if (klass->parent) {
/* For generic instances, klass->parent might not have been initialized */
mono_class_init_internal (klass->parent);
mono_class_setup_fields (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Could not set up parent class"))
return;
instance_size = klass->parent->instance_size;
} else {
instance_size = MONO_ABI_SIZEOF (MonoObject);
}
/* Get the real size */
explicit_size = mono_metadata_packing_from_typedef (klass->image, klass->type_token, &packing_size, &real_size);
if (explicit_size)
instance_size += real_size;
if (mono_is_corlib_image (klass->image) && !strcmp (klass->name_space, "System.Numerics") && !strcmp (klass->name, "Register")) {
if (mono_simd_register_size)
instance_size += mono_simd_register_size;
}
/*
* This function can recursively call itself.
* Prevent infinite recursion by using a list in TLS.
*/
GSList *init_list = (GSList *)mono_native_tls_get_value (setup_fields_tls_id);
if (g_slist_find (init_list, klass))
return;
init_list = g_slist_prepend (init_list, klass);
mono_native_tls_set_value (setup_fields_tls_id, init_list);
/*
* Fetch all the field information.
*/
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
for (i = 0; i < top; i++) {
int idx = first_field_idx + i;
field = &klass->fields [i];
if (!field->type) {
mono_field_resolve_type (field, error);
if (!is_ok (error)) {
/*mono_field_resolve_type already failed class*/
mono_error_cleanup (error);
break;
}
if (!field->type)
g_error ("could not resolve %s:%s\n", mono_type_get_full_name(klass), field->name);
g_assert (field->type);
}
if (!mono_type_get_underlying_type (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' is an enum type with a bad underlying type", field->name);
break;
}
if (mono_field_is_deleted (field))
continue;
if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
guint32 uoffset;
mono_metadata_field_info (m, idx, &uoffset, NULL, NULL);
int offset = uoffset;
if (offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
mono_class_set_type_load_failure (klass, "Missing field layout info for %s", field->name);
break;
}
if (m_type_is_byref (field->type) && (offset % MONO_ABI_ALIGNOF (gpointer) != 0)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid offset", field->name);
break;
}
if (offset < -1) { /*-1 is used to encode special static fields */
mono_class_set_type_load_failure (klass, "Field '%s' has a negative offset %d", field->name, offset);
break;
}
if (mono_class_is_gtd (klass)) {
mono_class_set_type_load_failure (klass, "Generic class cannot have explicit layout.");
break;
}
}
if (mono_type_has_exceptions (field->type)) {
char *class_name = mono_type_get_full_name (klass);
char *type_name = mono_type_full_name (field->type);
mono_class_set_type_load_failure (klass, "Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
g_free (class_name);
g_free (type_name);
break;
}
if (m_type_is_byref (field->type)) {
if (!m_class_is_byreflike (klass)) {
char *class_name = mono_type_get_full_name (klass);
mono_class_set_type_load_failure (klass, "Type %s is not a ByRefLike type so ref field, '%s', is invalid", class_name, field->name);
g_free (class_name);
break;
}
}
/* The def_value of fields is compute lazily during vtable creation */
}
if (!mono_class_has_failure (klass)) {
mono_loader_lock ();
mono_class_layout_fields (klass, instance_size, packing_size, real_size, FALSE);
mono_loader_unlock ();
}
init_list = g_slist_remove (init_list, klass);
mono_native_tls_set_value (setup_fields_tls_id, init_list);
}
static gboolean
discard_gclass_due_to_failure (MonoClass *gclass, void *user_data)
{
return mono_class_get_generic_class (gclass)->container_class == user_data;
}
static gboolean
fix_gclass_incomplete_instantiation (MonoClass *gclass, void *user_data)
{
MonoClass *gtd = (MonoClass*)user_data;
/* Only try to fix generic instances of @gtd */
if (mono_class_get_generic_class (gclass)->container_class != gtd)
return FALSE;
/* Check if the generic instance has no parent. */
if (gtd->parent && !gclass->parent)
mono_generic_class_setup_parent (gclass, gtd);
return TRUE;
}
static void
mono_class_set_failure_and_error (MonoClass *klass, MonoError *error, const char *msg)
{
mono_class_set_type_load_failure (klass, "%s", msg);
mono_error_set_type_load_class (error, klass, "%s", msg);
}
/**
* mono_class_create_from_typedef:
* \param image: image where the token is valid
* \param type_token: typedef token
* \param error: used to return any error found while creating the type
*
* Create the MonoClass* representing the specified type token.
* \p type_token must be a TypeDef token.
*
* FIXME: don't return NULL on failure, just let the caller figure it out.
*/
MonoClass *
mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError *error)
{
MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
MonoClass *klass, *parent = NULL;
guint32 cols [MONO_TYPEDEF_SIZE];
guint32 cols_next [MONO_TYPEDEF_SIZE];
guint tidx = mono_metadata_token_index (type_token);
MonoGenericContext *context = NULL;
const char *name, *nspace;
guint icount = 0;
MonoClass **interfaces;
guint32 field_last, method_last;
guint32 nesting_tokeen;
error_init (error);
/* FIXME: metadata-update - this function needs extensive work */
if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || mono_metadata_table_bounds_check (image, MONO_TABLE_TYPEDEF, tidx)) {
mono_error_set_bad_image (error, image, "Invalid typedef token %x", type_token);
return NULL;
}
mono_loader_lock ();
if ((klass = (MonoClass *)mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
mono_loader_unlock ();
return klass;
}
mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
if (mono_metadata_has_generic_params (image, type_token)) {
klass = (MonoClass*)mono_image_alloc0 (image, sizeof (MonoClassGtd));
klass->class_kind = MONO_CLASS_GTD;
UnlockedAdd (&classes_size, sizeof (MonoClassGtd));
++class_gtd_count;
} else {
klass = (MonoClass*)mono_image_alloc0 (image, sizeof (MonoClassDef));
klass->class_kind = MONO_CLASS_DEF;
UnlockedAdd (&classes_size, sizeof (MonoClassDef));
++class_def_count;
}
klass->name = name;
klass->name_space = nspace;
MONO_PROFILER_RAISE (class_loading, (klass));
klass->image = image;
klass->type_token = type_token;
mono_class_set_flags (klass, cols [MONO_TYPEDEF_FLAGS]);
mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), klass);
/*
* Check whether we're a generic type definition.
*/
if (mono_class_is_gtd (klass)) {
MonoGenericContainer *generic_container = mono_metadata_load_generic_params (image, klass->type_token, NULL, klass);
context = &generic_container->context;
mono_class_set_generic_container (klass, generic_container);
MonoType *canonical_inst = &((MonoClassGtd*)klass)->canonical_inst;
canonical_inst->type = MONO_TYPE_GENERICINST;
canonical_inst->data.generic_class = mono_metadata_lookup_generic_class (klass, context->class_inst, FALSE);
enable_gclass_recording ();
}
if (cols [MONO_TYPEDEF_EXTENDS]) {
MonoClass *tmp;
guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
/*WARNING: this must satisfy mono_metadata_type_hash*/
klass->this_arg.byref__ = 1;
klass->this_arg.data.klass = klass;
klass->this_arg.type = MONO_TYPE_CLASS;
klass->_byval_arg.data.klass = klass;
klass->_byval_arg.type = MONO_TYPE_CLASS;
}
parent = mono_class_get_checked (image, parent_token, error);
if (parent && context) /* Always inflate */
parent = mono_class_inflate_generic_class_checked (parent, context, error);
if (parent == NULL) {
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
goto parent_failure;
}
for (tmp = parent; tmp; tmp = tmp->parent) {
if (tmp == klass) {
mono_class_set_failure_and_error (klass, error, "Cycle found while resolving parent");
goto parent_failure;
}
if (mono_class_is_gtd (klass) && mono_class_is_ginst (tmp) && mono_class_get_generic_class (tmp)->container_class == klass) {
mono_class_set_failure_and_error (klass, error, "Parent extends generic instance of this type");
goto parent_failure;
}
}
}
mono_class_setup_parent (klass, parent);
/* uses ->valuetype, which is initialized by mono_class_setup_parent above */
mono_class_setup_mono_type (klass);
if (mono_class_is_gtd (klass))
disable_gclass_recording (fix_gclass_incomplete_instantiation, klass);
/*
* This might access klass->_byval_arg for recursion generated by generic constraints,
* so it has to come after setup_mono_type ().
*/
if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
klass->nested_in = mono_class_create_from_typedef (image, nesting_tokeen, error);
if (!is_ok (error)) {
/*FIXME implement a mono_class_set_failure_from_mono_error */
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
}
if ((mono_class_get_flags (klass) & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
klass->unicode = 1;
#ifdef HOST_WIN32
if ((mono_class_get_flags (klass) & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
klass->unicode = 1;
#endif
klass->cast_class = klass->element_class = klass;
if (mono_is_corlib_image (klass->image)) {
switch (m_class_get_byval_arg (klass)->type) {
case MONO_TYPE_I1:
if (mono_defaults.byte_class)
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_U1:
if (mono_defaults.sbyte_class)
mono_defaults.sbyte_class = klass;
break;
case MONO_TYPE_I2:
if (mono_defaults.uint16_class)
mono_defaults.uint16_class = klass;
break;
case MONO_TYPE_U2:
if (mono_defaults.int16_class)
klass->cast_class = mono_defaults.int16_class;
break;
case MONO_TYPE_I4:
if (mono_defaults.uint32_class)
mono_defaults.uint32_class = klass;
break;
case MONO_TYPE_U4:
if (mono_defaults.int32_class)
klass->cast_class = mono_defaults.int32_class;
break;
case MONO_TYPE_I8:
if (mono_defaults.uint64_class)
mono_defaults.uint64_class = klass;
break;
case MONO_TYPE_U8:
if (mono_defaults.int64_class)
klass->cast_class = mono_defaults.int64_class;
break;
default:
break;
}
}
if (!klass->enumtype) {
if (!mono_metadata_interfaces_from_typedef_full (
image, type_token, &interfaces, &icount, FALSE, context, error)){
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
/* This is required now that it is possible for more than 2^16 interfaces to exist. */
g_assert(icount <= 65535);
klass->interfaces = interfaces;
klass->interface_count = icount;
klass->interfaces_inited = 1;
}
/*g_print ("Load class %s\n", name);*/
/*
* Compute the field and method lists
*/
/*
* EnC metadata-update: new classes are added with method and field indices set to 0, new
* methods are added using the EnCLog AddMethod or AddField functions that will be added to
* MonoClassMetadataUpdateInfo
*/
if (G_LIKELY (cols [MONO_TYPEDEF_FIELD_LIST] != 0 || cols [MONO_TYPEDEF_METHOD_LIST] != 0)) {
int first_field_idx;
first_field_idx = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
mono_class_set_first_field_idx (klass, first_field_idx);
int first_method_idx;
first_method_idx = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
mono_class_set_first_method_idx (klass, first_method_idx);
if (table_info_get_rows (tt) > tidx) {
mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
} else {
field_last = table_info_get_rows (&image->tables [MONO_TABLE_FIELD]);
method_last = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
}
if (cols [MONO_TYPEDEF_FIELD_LIST] &&
cols [MONO_TYPEDEF_FIELD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_FIELD]))
mono_class_set_field_count (klass, field_last - first_field_idx);
if (cols [MONO_TYPEDEF_METHOD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_METHOD]))
mono_class_set_method_count (klass, method_last - first_method_idx);
}
/* reserve space to store vector pointer in arrays */
if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
klass->instance_size += 2 * TARGET_SIZEOF_VOID_P;
/* TODO: check that array has 0 non-const fields */
}
if (klass->enumtype) {
MonoType *enum_basetype = mono_class_find_enum_basetype (klass, error);
if (!enum_basetype) {
/*set it to a default value as the whole runtime can't handle this to be null*/
klass->cast_class = klass->element_class = mono_defaults.int32_class;
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
klass->cast_class = klass->element_class = mono_class_from_mono_type_internal (enum_basetype);
}
/*
* If we're a generic type definition, load the constraints.
* We must do this after the class has been constructed to make certain recursive scenarios
* work.
*/
if (mono_class_is_gtd (klass) && !mono_metadata_load_generic_param_constraints_checked (image, type_token, mono_class_get_generic_container (klass), error)) {
mono_class_set_type_load_failure (klass, "Could not load generic parameter constrains due to %s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
if (klass->image->assembly_name && !strcmp (klass->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
if (!strncmp (name, "Vector", 6))
klass->simd_type = !strcmp (name + 6, "2d") || !strcmp (name + 6, "2ul") || !strcmp (name + 6, "2l") || !strcmp (name + 6, "4f") || !strcmp (name + 6, "4ui") || !strcmp (name + 6, "4i") || !strcmp (name + 6, "8s") || !strcmp (name + 6, "8us") || !strcmp (name + 6, "16b") || !strcmp (name + 6, "16sb");
} else if (klass->image->assembly_name && !strcmp (klass->image->assembly_name, "System.Numerics") && !strcmp (nspace, "System.Numerics")) {
/* The JIT can't handle SIMD types with != 16 size yet */
//if (!strcmp (name, "Vector2") || !strcmp (name, "Vector3") || !strcmp (name, "Vector4"))
if (!strcmp (name, "Vector4"))
klass->simd_type = 1;
}
// compute is_byreflike
if (m_class_is_valuetype (klass))
if (class_has_isbyreflike_attribute (klass))
klass->is_byreflike = 1;
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
parent_failure:
if (mono_class_is_gtd (klass))
disable_gclass_recording (discard_gclass_due_to_failure, klass);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
static void
mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd)
{
if (gtd->parent) {
ERROR_DECL (error);
MonoGenericClass *gclass = mono_class_get_generic_class (klass);
klass->parent = mono_class_inflate_generic_class_checked (gtd->parent, mono_generic_class_get_context (gclass), error);
if (!is_ok (error)) {
/*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
klass->parent = mono_defaults.object_class;
mono_class_set_type_load_failure (klass, "Parent is a generic type instantiation that failed due to: %s", mono_error_get_message (error));
mono_error_cleanup (error);
}
}
mono_loader_lock ();
if (klass->parent)
mono_class_setup_parent (klass, klass->parent);
if (klass->enumtype) {
klass->cast_class = gtd->cast_class;
klass->element_class = gtd->element_class;
}
mono_loader_unlock ();
}
struct FoundAttrUD {
/* inputs */
const char *nspace;
const char *name;
gboolean in_corlib;
/* output */
gboolean has_attr;
};
static gboolean
has_wellknown_attribute_func (MonoImage *image, guint32 typeref_scope_token, const char *nspace, const char *name, guint32 method_token, gpointer user_data)
{
struct FoundAttrUD *has_attr = (struct FoundAttrUD *)user_data;
if (!strcmp (name, has_attr->name) && !strcmp (nspace, has_attr->nspace)) {
has_attr->has_attr = TRUE;
return TRUE;
}
/* TODO: use typeref_scope_token to check that attribute comes from
* corlib if in_corlib is TRUE, without triggering an assembly load.
* If we're inside corlib, expect the scope to be
* MONO_RESOLUTION_SCOPE_MODULE I think, if we're outside it'll be an
* MONO_RESOLUTION_SCOPE_ASSEMBLYREF and we'll need to check the
* name.*/
return FALSE;
}
static gboolean
class_has_wellknown_attribute (MonoClass *klass, const char *nspace, const char *name, gboolean in_corlib)
{
struct FoundAttrUD has_attr;
has_attr.nspace = nspace;
has_attr.name = name;
has_attr.in_corlib = in_corlib;
has_attr.has_attr = FALSE;
mono_class_metadata_foreach_custom_attr (klass, has_wellknown_attribute_func, &has_attr);
return has_attr.has_attr;
}
static gboolean
method_has_wellknown_attribute (MonoMethod *method, const char *nspace, const char *name, gboolean in_corlib)
{
struct FoundAttrUD has_attr;
has_attr.nspace = nspace;
has_attr.name = name;
has_attr.in_corlib = in_corlib;
has_attr.has_attr = FALSE;
mono_method_metadata_foreach_custom_attr (method, has_wellknown_attribute_func, &has_attr);
return has_attr.has_attr;
}
static gboolean
class_has_isbyreflike_attribute (MonoClass *klass)
{
return class_has_wellknown_attribute (klass, "System.Runtime.CompilerServices", "IsByRefLikeAttribute", TRUE);
}
gboolean
mono_class_setup_method_has_preserve_base_overrides_attribute (MonoMethod *method)
{
MonoImage *image = m_class_get_image (method->klass);
/* FIXME: implement well known attribute check for dynamic images */
if (image_is_dynamic (image))
return FALSE;
return method_has_wellknown_attribute (method, "System.Runtime.CompilerServices", "PreserveBaseOverridesAttribute", TRUE);
}
static gboolean
check_valid_generic_inst_arguments (MonoGenericInst *inst, MonoError *error)
{
for (int i = 0; i < inst->type_argc; i++) {
if (!mono_type_is_valid_generic_argument (inst->type_argv [i])) {
char *type_name = mono_type_full_name (inst->type_argv [i]);
mono_error_set_invalid_program (error, "generic type cannot be instantiated with type '%s'", type_name);
g_free (type_name);
return FALSE;
}
}
return TRUE;
}
/*
* Create the `MonoClass' for an instantiation of a generic type.
* We only do this if we actually need it.
* This will sometimes return a GTD due to checking the cached_class.
*/
MonoClass*
mono_class_create_generic_inst (MonoGenericClass *gclass)
{
MonoClass *klass, *gklass;
if (gclass->cached_class)
return gclass->cached_class;
klass = (MonoClass *)mono_mem_manager_alloc0 ((MonoMemoryManager*)gclass->owner, sizeof (MonoClassGenericInst));
gklass = gclass->container_class;
if (gklass->nested_in) {
/* The nested_in type should not be inflated since it's possible to produce a nested type with less generic arguments*/
klass->nested_in = gklass->nested_in;
}
klass->name = gklass->name;
klass->name_space = gklass->name_space;
klass->image = gklass->image;
klass->type_token = gklass->type_token;
klass->class_kind = MONO_CLASS_GINST;
//FIXME add setter
((MonoClassGenericInst*)klass)->generic_class = gclass;
klass->_byval_arg.type = MONO_TYPE_GENERICINST;
klass->this_arg.type = m_class_get_byval_arg (klass)->type;
klass->this_arg.data.generic_class = klass->_byval_arg.data.generic_class = gclass;
klass->this_arg.byref__ = TRUE;
klass->enumtype = gklass->enumtype;
klass->valuetype = gklass->valuetype;
if (gklass->image->assembly_name && !strcmp (gklass->image->assembly_name, "System.Numerics.Vectors") && !strcmp (gklass->name_space, "System.Numerics") && !strcmp (gklass->name, "Vector`1")) {
g_assert (gclass->context.class_inst);
g_assert (gclass->context.class_inst->type_argc > 0);
if (mono_type_is_primitive (gclass->context.class_inst->type_argv [0]))
klass->simd_type = 1;
}
if (mono_is_corlib_image (gklass->image) &&
(!strcmp (gklass->name, "Vector`1") || !strcmp (gklass->name, "Vector64`1") || !strcmp (gklass->name, "Vector128`1") || !strcmp (gklass->name, "Vector256`1"))) {
MonoType *etype = gclass->context.class_inst->type_argv [0];
if (mono_type_is_primitive (etype) && etype->type != MONO_TYPE_CHAR && etype->type != MONO_TYPE_BOOLEAN)
klass->simd_type = 1;
}
klass->is_array_special_interface = gklass->is_array_special_interface;
klass->cast_class = klass->element_class = klass;
if (m_class_is_valuetype (klass)) {
klass->is_byreflike = gklass->is_byreflike;
}
if (gclass->is_dynamic) {
/*
* We don't need to do any init workf with unbaked typebuilders. Generic instances created at this point will be later unregistered and/or fixed.
* This is to avoid work that would probably give wrong results as fields change as we build the TypeBuilder.
* See remove_instantiations_of_and_ensure_contents in reflection.c and its usage in reflection.c to understand the fixup stage of SRE banking.
*/
if (!gklass->wastypebuilder)
klass->inited = 1;
if (klass->enumtype) {
/*
* For enums, gklass->fields might not been set, but instance_size etc. is
* already set in mono_reflection_create_internal_class (). For non-enums,
* these will be computed normally in mono_class_layout_fields ().
*/
klass->instance_size = gklass->instance_size;
klass->sizes.class_size = gklass->sizes.class_size;
klass->size_inited = 1;
}
}
{
ERROR_DECL (error_inst);
if (!check_valid_generic_inst_arguments (gclass->context.class_inst, error_inst)) {
char *gklass_name = mono_type_get_full_name (gklass);
mono_class_set_type_load_failure (klass, "Could not instantiate %s due to %s", gklass_name, mono_error_get_message (error_inst));
g_free (gklass_name);
mono_error_cleanup (error_inst);
}
}
mono_loader_lock ();
if (gclass->cached_class) {
mono_loader_unlock ();
return gclass->cached_class;
}
if (record_gclass_instantiation > 0)
gclass_recorded_list = g_slist_append (gclass_recorded_list, klass);
if (mono_class_is_nullable (klass))
klass->cast_class = klass->element_class = mono_class_get_nullable_param_internal (klass);
MONO_PROFILER_RAISE (class_loading, (klass));
mono_generic_class_setup_parent (klass, gklass);
if (gclass->is_dynamic)
mono_class_setup_supertypes (klass);
mono_memory_barrier ();
gclass->cached_class = klass;
MONO_PROFILER_RAISE (class_loaded, (klass));
++class_ginst_count;
inflated_classes_size += sizeof (MonoClassGenericInst);
mono_loader_unlock ();
return klass;
}
/*
* For a composite class like uint32[], uint32*, set MonoClass:cast_class to the corresponding "intermediate type" (for
* arrays) or "verification type" (for pointers) in the sense of ECMA I.8.7.3. This will be used by
* mono_class_is_assignable_from.
*
* Assumes MonoClass:cast_class is already set (for example if it's an array of
* some enum) and adjusts it.
*/
static void
class_composite_fixup_cast_class (MonoClass *klass, gboolean for_ptr)
{
switch (m_class_get_byval_arg (m_class_get_cast_class (klass))->type) {
case MONO_TYPE_BOOLEAN:
if (!for_ptr)
break;
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_I1:
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_U2:
klass->cast_class = mono_defaults.int16_class;
break;
case MONO_TYPE_U4:
#if TARGET_SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
klass->cast_class = mono_defaults.int32_class;
break;
case MONO_TYPE_U8:
#if TARGET_SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
klass->cast_class = mono_defaults.int64_class;
break;
default:
break;
}
}
static gboolean
class_kind_may_contain_generic_instances (MonoTypeKind kind)
{
/* classes of type generic inst may contain generic arguments from other images,
* as well as arrays and pointers whose element types (recursively) may be a generic inst */
return (kind == MONO_CLASS_GINST || kind == MONO_CLASS_ARRAY || kind == MONO_CLASS_POINTER);
}
/**
* mono_class_create_bounded_array:
* \param element_class element class
* \param rank the dimension of the array class
* \param bounded whenever the array has non-zero bounds
* \returns A class object describing the array with element type \p element_type and
* dimension \p rank.
*/
MonoClass *
mono_class_create_bounded_array (MonoClass *eclass, guint32 rank, gboolean bounded)
{
MonoImage *image;
MonoClass *klass, *cached, *k;
MonoClass *parent = NULL;
GSList *list, *rootlist = NULL;
int nsize;
char *name;
MonoMemoryManager *mm;
if (rank > 1)
/* bounded only matters for one-dimensional arrays */
bounded = FALSE;
image = eclass->image;
// FIXME: Optimize this
mm = class_kind_may_contain_generic_instances ((MonoTypeKind)eclass->class_kind) ? mono_metadata_get_mem_manager_for_class (eclass) : NULL;
/* Check cache */
cached = NULL;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->szarray_cache)
mm->szarray_cache = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, NULL);
cached = (MonoClass *)g_hash_table_lookup (mm->szarray_cache, eclass);
mono_mem_manager_unlock (mm);
} else {
/*
* This case is very frequent not just during compilation because of calls
* from mono_class_from_mono_type_internal (), mono_array_new (),
* Array:CreateInstance (), etc, so use a separate cache + a separate lock.
*/
mono_os_mutex_lock (&image->szarray_cache_lock);
if (!image->szarray_cache)
image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
cached = (MonoClass *)g_hash_table_lookup (image->szarray_cache, eclass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->array_cache)
mm->array_cache = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, NULL);
rootlist = (GSList *)g_hash_table_lookup (mm->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_mem_manager_unlock (mm);
} else {
mono_loader_lock ();
if (!image->array_cache)
image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
rootlist = (GSList *)g_hash_table_lookup (image->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_loader_unlock ();
}
}
if (cached)
return cached;
parent = mono_defaults.array_class;
if (!parent->inited)
mono_class_init_internal (parent);
klass = mm ? (MonoClass *)mono_mem_manager_alloc0 (mm, sizeof (MonoClassArray)) : (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassArray));
klass->image = image;
klass->name_space = eclass->name_space;
klass->class_kind = MONO_CLASS_ARRAY;
nsize = strlen (eclass->name);
int maxrank = MIN (rank, 32);
name = (char *)g_malloc (nsize + 2 + maxrank + 1);
memcpy (name, eclass->name, nsize);
name [nsize] = '[';
if (maxrank > 1)
memset (name + nsize + 1, ',', maxrank - 1);
if (bounded)
name [nsize + maxrank] = '*';
name [nsize + maxrank + bounded] = ']';
name [nsize + maxrank + bounded + 1] = 0;
klass->name = mm ? mono_mem_manager_strdup (mm, name) : mono_image_strdup (image, name);
g_free (name);
klass->type_token = 0;
klass->parent = parent;
klass->instance_size = mono_class_instance_size (klass->parent);
klass->rank = rank;
klass->element_class = eclass;
if (m_class_get_byval_arg (eclass)->type == MONO_TYPE_TYPEDBYREF) {
/*Arrays of those two types are invalid.*/
ERROR_DECL (prepared_error);
mono_error_set_invalid_program (prepared_error, "Arrays of System.TypedReference types are invalid.");
mono_class_set_failure (klass, mono_error_box (prepared_error, klass->image));
mono_error_cleanup (prepared_error);
} else if (m_class_is_byreflike (eclass)) {
/* .NET Core throws a type load exception: "Could not create array type 'fullname[]'" */
char *full_name = mono_type_get_full_name (eclass);
mono_class_set_type_load_failure (klass, "Could not create array type '%s[]'", full_name);
g_free (full_name);
} else if (eclass->enumtype && !mono_class_enum_basetype_internal (eclass)) {
MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (eclass);
if (!ref_info_handle || eclass->wastypebuilder) {
g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
g_assert (ref_info_handle && !eclass->wastypebuilder);
}
/* element_size -1 is ok as this is not an instantitable type*/
klass->sizes.element_size = -1;
} else
klass->sizes.element_size = -1;
mono_class_setup_supertypes (klass);
if (mono_class_is_ginst (eclass))
mono_class_init_internal (eclass);
if (!eclass->size_inited)
mono_class_setup_fields (eclass);
mono_class_set_type_load_failure_causedby_class (klass, eclass, "Could not load array element type");
/*FIXME we fail the array type, but we have to let other fields be set.*/
klass->has_references = MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (eclass)) || m_class_has_references (eclass)? TRUE: FALSE;
if (eclass->enumtype)
klass->cast_class = eclass->element_class;
else
klass->cast_class = eclass;
class_composite_fixup_cast_class (klass, FALSE);
if ((rank > 1) || bounded) {
MonoArrayType *at = mm ? (MonoArrayType *)mono_mem_manager_alloc0 (mm, sizeof (MonoArrayType)) : (MonoArrayType *)mono_image_alloc0 (image, sizeof (MonoArrayType));
klass->_byval_arg.type = MONO_TYPE_ARRAY;
klass->_byval_arg.data.array = at;
at->eklass = eclass;
at->rank = rank;
/* FIXME: complete.... */
} else {
klass->_byval_arg.type = MONO_TYPE_SZARRAY;
klass->_byval_arg.data.klass = eclass;
}
klass->this_arg = klass->_byval_arg;
klass->this_arg.byref__ = 1;
if (rank > 32) {
ERROR_DECL (prepared_error);
name = mono_type_get_full_name (klass);
mono_error_set_type_load_class (prepared_error, klass, "%s has too many dimensions.", name);
mono_class_set_failure (klass, mono_error_box (prepared_error, klass->image));
mono_error_cleanup (prepared_error);
g_free (name);
}
mono_loader_lock ();
/* Check cache again */
cached = NULL;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
cached = (MonoClass *)g_hash_table_lookup (mm->szarray_cache, eclass);
mono_mem_manager_unlock (mm);
} else {
mono_os_mutex_lock (&image->szarray_cache_lock);
cached = (MonoClass *)g_hash_table_lookup (image->szarray_cache, eclass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
rootlist = (GSList *)g_hash_table_lookup (mm->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_mem_manager_unlock (mm);
} else {
rootlist = (GSList *)g_hash_table_lookup (image->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
}
}
if (cached) {
mono_loader_unlock ();
return cached;
}
MONO_PROFILER_RAISE (class_loading, (klass));
UnlockedAdd (&classes_size, sizeof (MonoClassArray));
++class_array_count;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
g_hash_table_insert (mm->szarray_cache, eclass, klass);
mono_mem_manager_unlock (mm);
} else {
mono_os_mutex_lock (&image->szarray_cache_lock);
g_hash_table_insert (image->szarray_cache, eclass, klass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
list = g_slist_append (rootlist, klass);
g_hash_table_insert (mm->array_cache, eclass, list);
mono_mem_manager_unlock (mm);
} else {
list = g_slist_append (rootlist, klass);
g_hash_table_insert (image->array_cache, eclass, list);
}
}
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
}
/**
* mono_class_create_array:
* \param element_class element class
* \param rank the dimension of the array class
* \returns A class object describing the array with element type \p element_type and
* dimension \p rank.
*/
MonoClass *
mono_class_create_array (MonoClass *eclass, guint32 rank)
{
return mono_class_create_bounded_array (eclass, rank, FALSE);
}
// This is called by mono_class_create_generic_parameter when a new class must be created.
static MonoClass*
make_generic_param_class (MonoGenericParam *param)
{
MonoClass *klass, **ptr;
int count, pos, i, min_align;
MonoGenericParamInfo *pinfo = mono_generic_param_info (param);
MonoGenericContainer *container = mono_generic_param_owner (param);
g_assert_checked (container);
MonoImage *image = mono_get_image_for_generic_param (param);
gboolean is_mvar = container->is_method;
gboolean is_anonymous = container->is_anonymous;
klass = (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassGenericParam));
klass->class_kind = MONO_CLASS_GPARAM;
UnlockedAdd (&classes_size, sizeof (MonoClassGenericParam));
UnlockedIncrement (&class_gparam_count);
if (!is_anonymous) {
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name , pinfo->name );
} else {
int n = mono_generic_param_num (param);
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->name , mono_make_generic_name_string (image, n) );
}
if (is_anonymous) {
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , "" );
} else if (is_mvar) {
MonoMethod *omethod = container->owner.method;
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , (omethod && omethod->klass) ? omethod->klass->name_space : "" );
} else {
MonoClass *oklass = container->owner.klass;
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , oklass ? oklass->name_space : "" );
}
MONO_PROFILER_RAISE (class_loading, (klass));
// Count non-NULL items in pinfo->constraints
count = 0;
if (!is_anonymous)
for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
;
pos = 0;
if ((count > 0) && !MONO_CLASS_IS_INTERFACE_INTERNAL (pinfo->constraints [0])) {
CHECKED_METADATA_WRITE_PTR ( klass->parent , pinfo->constraints [0] );
pos++;
} else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) {
CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_class_load_from_name (mono_defaults.corlib, "System", "ValueType") );
} else {
CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_defaults.object_class );
}
if (count - pos > 0) {
klass->interface_count = count - pos;
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->interfaces , (MonoClass **)mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos)) );
klass->interfaces_inited = TRUE;
for (i = pos; i < count; i++)
CHECKED_METADATA_WRITE_PTR ( klass->interfaces [i - pos] , pinfo->constraints [i] );
}
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->image , image );
klass->inited = TRUE;
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->cast_class , klass );
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->element_class , klass );
MonoTypeEnum t = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
klass->_byval_arg.type = t;
klass->this_arg.type = t;
CHECKED_METADATA_WRITE_PTR ( klass->this_arg.data.generic_param , param );
CHECKED_METADATA_WRITE_PTR ( klass->_byval_arg.data.generic_param , param );
klass->this_arg.byref__ = TRUE;
/* We don't use type_token for VAR since only classes can use it (not arrays, pointer, VARs, etc) */
klass->sizes.generic_param_token = !is_anonymous ? pinfo->token : 0;
if (param->gshared_constraint) {
MonoClass *constraint_class = mono_class_from_mono_type_internal (param->gshared_constraint);
mono_class_init_sizes (constraint_class);
klass->has_references = m_class_has_references (constraint_class);
}
/*
* This makes sure the the value size of this class is equal to the size of the types the gparam is
* constrained to, the JIT depends on this.
*/
klass->instance_size = MONO_ABI_SIZEOF (MonoObject) + mono_type_size (m_class_get_byval_arg (klass), &min_align);
klass->min_align = min_align;
mono_memory_barrier ();
klass->size_inited = 1;
mono_class_setup_supertypes (klass);
if (count - pos > 0) {
mono_class_setup_vtable (klass->parent);
if (mono_class_has_failure (klass->parent))
mono_class_set_type_load_failure (klass, "Failed to setup parent interfaces");
else
mono_class_setup_interface_offsets_internal (klass, klass->parent->vtable_size, TRUE);
}
return klass;
}
/*
* LOCKING: Acquires the image lock (@image).
*/
MonoClass *
mono_class_create_generic_parameter (MonoGenericParam *param)
{
MonoImage *image = mono_get_image_for_generic_param (param);
MonoGenericParamInfo *pinfo = mono_generic_param_info (param);
MonoClass *klass, *klass2;
// If a klass already exists for this object and is cached, return it.
klass = pinfo->pklass;
if (klass)
return klass;
// Create a new klass
klass = make_generic_param_class (param);
// Now we need to cache the klass we created.
// But since we wait to grab the lock until after creating the klass, we need to check to make sure
// another thread did not get in and cache a klass ahead of us. In that case, return their klass
// and allow our newly-created klass object to just leak.
mono_memory_barrier ();
mono_image_lock (image);
// Here "klass2" refers to the klass potentially created by the other thread.
klass2 = pinfo->pklass;
if (klass2) {
klass = klass2;
} else {
pinfo->pklass = klass;
}
mono_image_unlock (image);
/* FIXME: Should this go inside 'make_generic_param_klass'? */
if (klass2)
MONO_PROFILER_RAISE (class_failed, (klass2));
else
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
}
/**
* mono_class_create_ptr:
*/
MonoClass *
mono_class_create_ptr (MonoType *type)
{
MonoClass *result;
MonoClass *el_class;
MonoImage *image;
char *name;
MonoMemoryManager *mm;
el_class = mono_class_from_mono_type_internal (type);
image = el_class->image;
// FIXME: Optimize this
mm = class_kind_may_contain_generic_instances ((MonoTypeKind)el_class->class_kind) ? mono_metadata_get_mem_manager_for_class (el_class) : NULL;
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->ptr_cache)
mm->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
result = (MonoClass *)g_hash_table_lookup (mm->ptr_cache, el_class);
mono_mem_manager_unlock (mm);
if (result)
return result;
} else {
mono_image_lock (image);
if (image->ptr_cache) {
if ((result = (MonoClass *)g_hash_table_lookup (image->ptr_cache, el_class))) {
mono_image_unlock (image);
return result;
}
}
mono_image_unlock (image);
}
result = mm ? (MonoClass *)mono_mem_manager_alloc0 (mm, sizeof (MonoClassPointer)) : (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassPointer));
UnlockedAdd (&classes_size, sizeof (MonoClassPointer));
++class_pointer_count;
result->parent = NULL; /* no parent for PTR types */
result->name_space = el_class->name_space;
name = g_strdup_printf ("%s*", el_class->name);
result->name = mm ? mono_mem_manager_strdup (mm, name) : mono_image_strdup (image, name);
result->class_kind = MONO_CLASS_POINTER;
g_free (name);
MONO_PROFILER_RAISE (class_loading, (result));
result->image = el_class->image;
result->inited = TRUE;
result->instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
result->min_align = sizeof (gpointer);
result->element_class = el_class;
result->blittable = TRUE;
if (el_class->enumtype)
result->cast_class = el_class->element_class;
else
result->cast_class = el_class;
class_composite_fixup_cast_class (result, TRUE);
result->this_arg.type = result->_byval_arg.type = MONO_TYPE_PTR;
result->this_arg.data.type = result->_byval_arg.data.type = m_class_get_byval_arg (el_class);
result->this_arg.byref__ = TRUE;
mono_class_setup_supertypes (result);
if (mm) {
mono_mem_manager_lock (mm);
MonoClass *result2;
result2 = (MonoClass *)g_hash_table_lookup (mm->ptr_cache, el_class);
if (!result2)
g_hash_table_insert (mm->ptr_cache, el_class, result);
mono_mem_manager_unlock (mm);
if (result2) {
MONO_PROFILER_RAISE (class_failed, (result));
return result2;
}
} else {
mono_image_lock (image);
if (image->ptr_cache) {
MonoClass *result2;
if ((result2 = (MonoClass *)g_hash_table_lookup (image->ptr_cache, el_class))) {
mono_image_unlock (image);
MONO_PROFILER_RAISE (class_failed, (result));
return result2;
}
} else {
image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
}
g_hash_table_insert (image->ptr_cache, el_class, result);
mono_image_unlock (image);
}
MONO_PROFILER_RAISE (class_loaded, (result));
return result;
}
MonoClass *
mono_class_create_fnptr (MonoMethodSignature *sig)
{
MonoClass *result, *cached;
static GHashTable *ptr_hash = NULL;
/* FIXME: These should be allocate from a mempool as well, but which one ? */
mono_loader_lock ();
if (!ptr_hash)
ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
cached = (MonoClass *)g_hash_table_lookup (ptr_hash, sig);
mono_loader_unlock ();
if (cached)
return cached;
result = g_new0 (MonoClass, 1);
result->parent = NULL; /* no parent for PTR types */
result->name_space = "System";
result->name = "MonoFNPtrFakeClass";
result->class_kind = MONO_CLASS_POINTER;
result->image = mono_defaults.corlib; /* need to fix... */
result->instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
result->min_align = sizeof (gpointer);
result->cast_class = result->element_class = result;
result->this_arg.type = result->_byval_arg.type = MONO_TYPE_FNPTR;
result->this_arg.data.method = result->_byval_arg.data.method = sig;
result->this_arg.byref__ = TRUE;
result->blittable = TRUE;
result->inited = TRUE;
mono_class_setup_supertypes (result);
mono_loader_lock ();
cached = (MonoClass *)g_hash_table_lookup (ptr_hash, sig);
if (cached) {
g_free (result);
mono_loader_unlock ();
return cached;
}
MONO_PROFILER_RAISE (class_loading, (result));
UnlockedAdd (&classes_size, sizeof (MonoClassPointer));
++class_pointer_count;
g_hash_table_insert (ptr_hash, sig, result);
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (result));
return result;
}
static gboolean
method_is_reabstracted (guint16 flags)
{
if ((flags & METHOD_ATTRIBUTE_ABSTRACT && flags & METHOD_ATTRIBUTE_FINAL))
return TRUE;
return FALSE;
}
/**
* mono_class_setup_count_virtual_methods:
*
* Return the number of virtual methods.
* Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
* Return -1 on failure.
* FIXME It would be nice if this information could be cached somewhere.
*/
int
mono_class_setup_count_virtual_methods (MonoClass *klass)
{
int i, mcount, vcount = 0;
guint32 flags;
klass = mono_class_get_generic_type_definition (klass); /*We can find this information by looking at the GTD*/
if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return -1;
mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
flags = klass->methods [i]->flags;
if ((flags & METHOD_ATTRIBUTE_VIRTUAL)) {
if (method_is_reabstracted (flags))
continue;
++vcount;
}
}
} else {
int first_idx = mono_class_get_first_method_idx (klass);
mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, first_idx + i, MONO_METHOD_FLAGS);
if ((flags & METHOD_ATTRIBUTE_VIRTUAL)) {
if (method_is_reabstracted (flags))
continue;
++vcount;
}
}
}
return vcount;
}
#ifdef COMPRESSED_INTERFACE_BITMAP
/*
* Compressed interface bitmap design.
*
* Interface bitmaps take a large amount of memory, because their size is
* linear with the maximum interface id assigned in the process (each interface
* is assigned a unique id as it is loaded). The number of interface classes
* is high because of the many implicit interfaces implemented by arrays (we'll
* need to lazy-load them in the future).
* Most classes implement a very small number of interfaces, so the bitmap is
* sparse. This bitmap needs to be checked by interface casts, so access to the
* needed bit must be fast and doable with few jit instructions.
*
* The current compression format is as follows:
* *) it is a sequence of one or more two-byte elements
* *) the first byte in the element is the count of empty bitmap bytes
* at the current bitmap position
* *) the second byte in the element is an actual bitmap byte at the current
* bitmap position
*
* As an example, the following compressed bitmap bytes:
* 0x07 0x01 0x00 0x7
* correspond to the following bitmap:
* 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
*
* Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
* bitmap byte for non-sparse sequences. In practice the interface bitmaps created
* during a gmcs bootstrap are reduced to less tha 5% of the original size.
*/
/**
* mono_compress_bitmap:
* \param dest destination buffer
* \param bitmap bitmap buffer
* \param size size of \p bitmap in bytes
*
* This is a mono internal function.
* The \p bitmap data is compressed into a format that is small but
* still searchable in few instructions by the JIT and runtime.
* The compressed data is stored in the buffer pointed to by the
* \p dest array. Passing a NULL value for \p dest allows to just compute
* the size of the buffer.
* This compression algorithm assumes the bits set in the bitmap are
* few and far between, like in interface bitmaps.
* \returns The size of the compressed bitmap in bytes.
*/
int
mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
{
int numz = 0;
int res = 0;
const uint8_t *end = bitmap + size;
while (bitmap < end) {
if (*bitmap || numz == 255) {
if (dest) {
*dest++ = numz;
*dest++ = *bitmap;
}
res += 2;
numz = 0;
bitmap++;
continue;
}
bitmap++;
numz++;
}
if (numz) {
res += 2;
if (dest) {
*dest++ = numz;
*dest++ = 0;
}
}
return res;
}
/**
* mono_class_interface_match:
* \param bitmap a compressed bitmap buffer
* \param id the index to check in the bitmap
*
* This is a mono internal function.
* Checks if a bit is set in a compressed interface bitmap. \p id must
* be already checked for being smaller than the maximum id encoded in the
* bitmap.
*
* \returns A non-zero value if bit \p id is set in the bitmap \p bitmap,
* FALSE otherwise.
*/
int
mono_class_interface_match (const uint8_t *bitmap, int id)
{
while (TRUE) {
id -= bitmap [0] * 8;
if (id < 8) {
if (id < 0)
return 0;
return bitmap [1] & (1 << id);
}
bitmap += 2;
id -= 8;
}
}
#endif
static char*
concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
{
int null_length = strlen ("(null)");
int len = (s1 ? strlen (s1) : null_length) + (s2 ? strlen (s2) : null_length) + 2;
char *s = (char *)mono_image_alloc (image, len);
int result;
result = g_snprintf (s, len, "%s%c%s", s1 ? s1 : "(null)", '\0', s2 ? s2 : "(null)");
g_assert (result == len - 1);
return s;
}
static void
init_sizes_with_info (MonoClass *klass, MonoCachedClassInfo *cached_info)
{
if (cached_info) {
mono_loader_lock ();
klass->instance_size = cached_info->instance_size;
klass->sizes.class_size = cached_info->class_size;
klass->packing_size = cached_info->packing_size;
klass->min_align = cached_info->min_align;
klass->blittable = cached_info->blittable;
klass->has_references = cached_info->has_references;
klass->has_static_refs = cached_info->has_static_refs;
klass->no_special_static_fields = cached_info->no_special_static_fields;
klass->has_weak_fields = cached_info->has_weak_fields;
mono_loader_unlock ();
}
else {
if (!klass->size_inited)
mono_class_setup_fields (klass);
}
}
/*
* mono_class_init_sizes:
*
* Initializes the size related fields of @klass without loading all field data if possible.
* Sets the following fields in @klass:
* - instance_size
* - sizes.class_size
* - packing_size
* - min_align
* - blittable
* - has_references
* - has_static_refs
* - size_inited
* Can fail the class.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_init_sizes (MonoClass *klass)
{
MonoCachedClassInfo cached_info;
gboolean has_cached_info;
if (klass->size_inited)
return;
has_cached_info = mono_class_get_cached_class_info (klass, &cached_info);
init_sizes_with_info (klass, has_cached_info ? &cached_info : NULL);
}
static gboolean
class_has_references (MonoClass *klass)
{
mono_class_init_sizes (klass);
/*
* has_references is not set if this is called recursively, but this is not a problem since this is only used
* during field layout, and instance fields are initialized before static fields, and instance fields can't
* embed themselves.
*/
return klass->has_references;
}
static gboolean
type_has_references (MonoClass *klass, MonoType *ftype)
{
if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (klass, ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && class_has_references (mono_class_from_mono_type_internal (ftype)))))
return TRUE;
if (!m_type_is_byref (ftype) && (ftype->type == MONO_TYPE_VAR || ftype->type == MONO_TYPE_MVAR)) {
MonoGenericParam *gparam = ftype->data.generic_param;
if (gparam->gshared_constraint)
return class_has_references (mono_class_from_mono_type_internal (gparam->gshared_constraint));
}
return FALSE;
}
static gboolean
class_has_ref_fields (MonoClass *klass)
{
/*
* has_ref_fields is not set if this is called recursively, but this is not a problem since this is only used
* during field layout, and instance fields are initialized before static fields, and instance fields can't
* embed themselves.
*/
return klass->has_ref_fields;
}
static gboolean
class_is_byreference (MonoClass* klass)
{
const char* klass_name_space = m_class_get_name_space (klass);
const char* klass_name = m_class_get_name (klass);
MonoImage* klass_image = m_class_get_image (klass);
gboolean in_corlib = klass_image == mono_defaults.corlib;
if (in_corlib &&
!strcmp (klass_name_space, "System") &&
!strcmp (klass_name, "ByReference`1")) {
return TRUE;
}
return FALSE;
}
static gboolean
type_has_ref_fields (MonoType *ftype)
{
if (m_type_is_byref (ftype) || (MONO_TYPE_ISSTRUCT (ftype) && class_has_ref_fields (mono_class_from_mono_type_internal (ftype))))
return TRUE;
/* Check for the ByReference`1 type */
if (MONO_TYPE_ISSTRUCT (ftype)) {
MonoClass* klass = mono_class_from_mono_type_internal (ftype);
return class_is_byreference (klass);
}
return FALSE;
}
/**
* mono_class_is_gparam_with_nonblittable_parent:
* \param klass a generic parameter
*
* \returns TRUE if \p klass is definitely not blittable.
*
* A parameter is definitely not blittable if it has the IL 'reference'
* constraint, or if it has a class specified as a parent. If it has an IL
* 'valuetype' constraint or no constraint at all or only interfaces as
* constraints, we return FALSE because the parameter may be instantiated both
* with blittable and non-blittable types.
*
* If the paramter is a generic sharing parameter, we look at its gshared_constraint->blittable bit.
*/
static gboolean
mono_class_is_gparam_with_nonblittable_parent (MonoClass *klass)
{
MonoType *type = m_class_get_byval_arg (klass);
g_assert (mono_type_is_generic_parameter (type));
MonoGenericParam *gparam = type->data.generic_param;
if ((mono_generic_param_info (gparam)->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) != 0)
return TRUE;
if ((mono_generic_param_info (gparam)->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) != 0)
return FALSE;
if (gparam->gshared_constraint) {
MonoClass *constraint_class = mono_class_from_mono_type_internal (gparam->gshared_constraint);
return !m_class_is_blittable (constraint_class);
}
if (mono_generic_param_owner (gparam)->is_anonymous)
return FALSE;
/* We could have: T : U, U : Base. So have to follow the constraints. */
MonoClass *parent_class = mono_generic_param_get_base_type (klass);
g_assert (!MONO_CLASS_IS_INTERFACE_INTERNAL (parent_class));
/* Parent can only be: System.Object, System.ValueType or some specific base class.
*
* If the parent_class is ValueType, the valuetype constraint would be set, above, so
* we wouldn't get here.
*
* If there was a reference constraint, the parent_class would be System.Object,
* but we would have returned early above.
*
* So if we get here, there is either no base class constraint at all,
* in which case parent_class would be set to System.Object, or there is none at all.
*/
return parent_class != mono_defaults.object_class;
}
/**
* Checks if there are any overlapping object and non-object fields.
* The alignment of object reference fields is checked elswhere and this function assumes
* that all references are aligned correctly.
*
* \param layout_check A buffer to check which bytes hold object references or values
* \param klass Checked struct
* \param field_offsets Offsets of the klass' fields relative to the start of layout_check
* \param field_count Count of klass fields
* \param invalid_field_offset When the layout is invalid it will be set to the offset of the field which is invalid
*
* \return True if the layout of the struct is valid, otherwise false.
*/
static gboolean
validate_struct_fields_overlaps (guint8 *layout_check, int layout_size, MonoClass *klass, const int *field_offsets, const int field_count, int *invalid_field_offset)
{
MonoClassField *field;
MonoType *ftype;
int field_offset;
for (int i = 0; i < field_count && !mono_class_has_failure (klass); i++) {
// using mono_class_get_fields_internal isn't appropriate here because it will
// try to call mono_class_setup_fields which is what we're doing already
field = &m_class_get_fields (klass) [i];
field_offset = field_offsets [i];
if (!field)
continue;
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (mono_type_is_struct (ftype)) {
// recursively check the layout of the embedded struct
MonoClass *embedded_class = mono_class_from_mono_type_internal (ftype);
mono_class_setup_fields (embedded_class);
const int embedded_fields_count = mono_class_get_field_count (embedded_class);
int *embedded_offsets = g_new0 (int, embedded_fields_count);
for (int j = 0; j < embedded_fields_count; ++j) {
embedded_offsets [j] = field_offset + m_class_get_fields (embedded_class) [j].offset - MONO_ABI_SIZEOF (MonoObject);
}
gboolean is_valid = validate_struct_fields_overlaps (layout_check, layout_size, embedded_class, embedded_offsets, embedded_fields_count, invalid_field_offset);
g_free (embedded_offsets);
if (!is_valid) {
// overwrite whatever was in the invalid_field_offset with the offset of the currently checked field
// we want to return the outer most invalid field
*invalid_field_offset = field_offset;
return FALSE;
}
} else {
int align = 0;
int size = mono_type_size (field->type, &align);
guint8 type = type_has_references (klass, ftype) ? 1 : (m_type_is_byref (ftype) || class_is_byreference (klass)) ? 2 : 3;
// Mark the bytes used by this fields type based on if it contains references or not.
// Make sure there are no overlaps between object and non-object fields.
for (int j = 0; j < size; j++) {
int checked_byte = field_offset + j;
g_assert(checked_byte < layout_size);
if (layout_check [checked_byte] != 0 && layout_check [checked_byte] != type) {
*invalid_field_offset = field_offset;
return FALSE;
}
layout_check [checked_byte] = type;
}
}
}
return TRUE;
}
/*
* mono_class_layout_fields:
* @class: a class
* @base_instance_size: base instance size
* @packing_size:
*
* This contains the common code for computing the layout of classes and sizes.
* This should only be called from mono_class_setup_fields () and
* typebuilder_setup_fields ().
*
* LOCKING: Acquires the loader lock
*/
void
mono_class_layout_fields (MonoClass *klass, int base_instance_size, int packing_size, int explicit_size, gboolean sre)
{
int i;
const int top = mono_class_get_field_count (klass);
guint32 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
guint32 pass, passes, real_size;
gboolean gc_aware_layout = FALSE;
gboolean has_static_fields = FALSE;
gboolean has_references = FALSE;
gboolean has_ref_fields = FALSE;
gboolean has_static_refs = FALSE;
MonoClassField *field;
gboolean blittable;
gboolean any_field_has_auto_layout;
int instance_size = base_instance_size;
int element_size = -1;
int class_size, min_align;
int *field_offsets;
gboolean *fields_has_references;
/*
* We want to avoid doing complicated work inside locks, so we compute all the required
* information and write it to @klass inside a lock.
*/
if (klass->fields_inited)
return;
if ((packing_size & 0xffffff00) != 0) {
mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
return;
}
if (klass->parent) {
min_align = klass->parent->min_align;
/* we use | since it may have been set already */
has_references = klass->has_references | klass->parent->has_references;
has_ref_fields = klass->has_ref_fields | klass->parent->has_ref_fields;
} else {
min_align = 1;
}
/* We can't really enable 16 bytes alignment until the GC supports it.
The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
Bug #506144 is an example of this issue.
if (klass->simd_type)
min_align = 16;
*/
/* Respect the specified packing size at least to the extent necessary to align double variables.
* This should avoid any GC problems, and will allow packing_size to be respected to support
* CreateSpan<T>
*/
min_align = MIN (MONO_ABI_ALIGNOF (double), MAX (min_align, packing_size));
/*
* When we do generic sharing we need to have layout
* information for open generic classes (either with a generic
* context containing type variables or with a generic
* container), so we don't return in that case anymore.
*/
if (klass->enumtype) {
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
klass->cast_class = klass->element_class = mono_class_from_mono_type_internal (field->type);
break;
}
}
if (!mono_class_enum_basetype_internal (klass)) {
mono_class_set_type_load_failure (klass, "The enumeration's base type is invalid.");
return;
}
}
/*
* Enable GC aware auto layout: in this mode, reference
* fields are grouped together inside objects, increasing collector
* performance.
* Requires that all classes whose layout is known to native code be annotated
* with [StructLayout (LayoutKind.Sequential)]
* Value types have gc_aware_layout disabled by default, as per
* what the default is for other runtimes.
*/
/* corlib is missing [StructLayout] directives in many places */
if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
if (!klass->valuetype)
gc_aware_layout = TRUE;
}
/* Compute klass->blittable and klass->any_field_has_auto_layout */
blittable = TRUE;
any_field_has_auto_layout = FALSE;
if (klass->parent) {
blittable = klass->parent->blittable;
any_field_has_auto_layout = klass->parent->any_field_has_auto_layout;
}
if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT && !(mono_is_corlib_image (klass->image) && !strcmp (klass->name_space, "System") && !strcmp (klass->name, "ValueType")) && top) {
blittable = FALSE;
any_field_has_auto_layout = TRUE; // If a type is auto-layout, treat it as having an auto-layout field in its layout.
}
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
if (blittable) {
if (m_type_is_byref (field->type) || MONO_TYPE_IS_REFERENCE (field->type)) {
blittable = FALSE;
} else if (mono_type_is_generic_parameter (field->type) &&
mono_class_is_gparam_with_nonblittable_parent (mono_class_from_mono_type_internal (field->type))) {
blittable = FALSE;
} else {
MonoClass *field_class = mono_class_from_mono_type_internal (field->type);
if (field_class) {
mono_class_setup_fields (field_class);
if (mono_class_has_failure (field_class)) {
ERROR_DECL (field_error);
mono_error_set_for_class_failure (field_error, field_class);
mono_class_set_type_load_failure (klass, "Could not set up field '%s' due to: %s", field->name, mono_error_get_message (field_error));
mono_error_cleanup (field_error);
break;
}
}
if (!field_class || !field_class->blittable)
blittable = FALSE;
}
}
if (!any_field_has_auto_layout && field->type->type == MONO_TYPE_VALUETYPE && m_class_any_field_has_auto_layout (mono_class_from_mono_type_internal (field->type)))
any_field_has_auto_layout = TRUE;
}
if (klass->enumtype) {
blittable = klass->element_class->blittable;
any_field_has_auto_layout = klass->element_class->any_field_has_auto_layout;
}
if (mono_class_has_failure (klass))
return;
if (klass == mono_defaults.string_class)
blittable = FALSE;
/* Compute klass->has_references and klass->has_ref_fields */
/*
* Process non-static fields first, since static fields might recursively
* refer to the class itself.
*/
for (i = 0; i < top; i++) {
MonoType *ftype;
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype))
has_references = TRUE;
if (type_has_ref_fields (ftype))
has_ref_fields = TRUE;
}
}
/*
* Compute field layout and total size (not considering static fields)
*/
field_offsets = g_new0 (int, top);
fields_has_references = g_new0 (gboolean, top);
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
switch (layout) {
case TYPE_ATTRIBUTE_AUTO_LAYOUT:
case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
if (gc_aware_layout)
passes = 2;
else
passes = 1;
if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
passes = 1;
if (klass->parent) {
mono_class_setup_fields (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Cannot initialize parent class"))
return;
real_size = klass->parent->instance_size;
} else {
real_size = MONO_ABI_SIZEOF (MonoObject);
}
for (pass = 0; pass < passes; ++pass) {
for (i = 0; i < top; i++){
gint32 align;
guint32 size;
MonoType *ftype;
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (gc_aware_layout) {
fields_has_references [i] = type_has_references (klass, ftype);
if (fields_has_references [i]) {
if (pass == 1)
continue;
} else {
if (pass == 0)
continue;
}
}
if ((top == 1) && (instance_size == MONO_ABI_SIZEOF (MonoObject)) &&
(strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
/* This field is a hack inserted by MCS to empty structures */
continue;
}
size = mono_type_size (field->type, &align);
/* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
align = packing_size ? MIN (packing_size, align): align;
/* if the field has managed references, we need to force-align it
* see bug #77788
*/
if (type_has_references (klass, ftype))
align = MAX (align, TARGET_SIZEOF_VOID_P);
min_align = MAX (align, min_align);
field_offsets [i] = real_size;
if (align) {
field_offsets [i] += align - 1;
field_offsets [i] &= ~(align - 1);
}
/*TypeBuilders produce all sort of weird things*/
g_assert (image_is_dynamic (klass->image) || field_offsets [i] > 0);
real_size = field_offsets [i] + size;
}
instance_size = MAX (real_size, instance_size);
if (instance_size & (min_align - 1)) {
instance_size += min_align - 1;
instance_size &= ~(min_align - 1);
}
}
break;
case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT: {
real_size = 0;
for (i = 0; i < top; i++) {
gint32 align;
guint32 size;
MonoType *ftype;
field = &klass->fields [i];
/*
* There must be info about all the fields in a type if it
* uses explicit layout.
*/
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
size = mono_type_size (field->type, &align);
align = packing_size ? MIN (packing_size, align): align;
min_align = MAX (align, min_align);
if (sre) {
/* Already set by typebuilder_setup_fields () */
field_offsets [i] = field->offset + MONO_ABI_SIZEOF (MonoObject);
} else {
int idx = first_field_idx + i;
guint32 offset;
mono_metadata_field_info (klass->image, idx, &offset, NULL, NULL);
field_offsets [i] = offset + MONO_ABI_SIZEOF (MonoObject);
}
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype) || m_type_is_byref (ftype)) {
if (field_offsets [i] % TARGET_SIZEOF_VOID_P) {
mono_class_set_type_load_failure (klass, "Reference typed field '%s' has explicit offset that is not pointer-size aligned.", field->name);
}
}
/*
* Calc max size.
*/
real_size = MAX (real_size, size + field_offsets [i]);
}
/* check for incorrectly aligned or overlapped by a non-object field */
guint8 *layout_check;
if (has_references || has_ref_fields) {
layout_check = g_new0 (guint8, real_size);
int invalid_field_offset;
if (!validate_struct_fields_overlaps (layout_check, real_size, klass, field_offsets, top, &invalid_field_offset)) {
mono_class_set_type_load_failure (klass, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, invalid_field_offset);
}
g_free (layout_check);
}
instance_size = MAX (real_size, instance_size);
if (!((layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) && explicit_size)) {
if (instance_size & (min_align - 1)) {
instance_size += min_align - 1;
instance_size &= ~(min_align - 1);
}
}
break;
}
}
if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
/*
* This leads to all kinds of problems with nested structs, so only
* enable it when a MONO_DEBUG property is set.
*
* For small structs, set min_align to at least the struct size to improve
* performance, and since the JIT memset/memcpy code assumes this and generates
* unaligned accesses otherwise. See #78990 for a testcase.
*/
if (mono_align_small_structs && top) {
if (instance_size <= MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer))
min_align = MAX (min_align, instance_size - MONO_ABI_SIZEOF (MonoObject));
}
}
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_VAR || klass_byval_arg->type == MONO_TYPE_MVAR)
instance_size = MONO_ABI_SIZEOF (MonoObject) + mono_type_size (klass_byval_arg, &min_align);
else if (klass_byval_arg->type == MONO_TYPE_PTR)
instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
if (klass_byval_arg->type == MONO_TYPE_SZARRAY || klass_byval_arg->type == MONO_TYPE_ARRAY)
element_size = mono_class_array_element_size (klass->element_class);
/* Publish the data */
mono_loader_lock ();
if (klass->instance_size && !klass->image->dynamic && klass_byval_arg->type != MONO_TYPE_FNPTR) {
/* Might be already set using cached info */
if (klass->instance_size != instance_size) {
/* Emit info to help debugging */
g_print ("%s\n", mono_class_full_name (klass));
g_print ("%d %d %d %d\n", klass->instance_size, instance_size, klass->blittable, blittable);
g_print ("%d %d %d %d\n", klass->has_references, has_references, klass->has_ref_fields, has_ref_fields);
g_print ("%d %d %d %d\n", klass->packing_size, packing_size, klass->min_align, min_align);
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
printf (" %s %d %d %d\n", klass->fields [i].name, klass->fields [i].offset, field_offsets [i], fields_has_references [i]);
}
}
g_assert (klass->instance_size == instance_size);
} else {
klass->instance_size = instance_size;
}
klass->blittable = blittable;
klass->has_references = has_references;
klass->has_ref_fields = has_ref_fields;
klass->packing_size = packing_size;
klass->min_align = min_align;
klass->any_field_has_auto_layout = any_field_has_auto_layout;
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
klass->fields [i].offset = field_offsets [i];
}
if (klass_byval_arg->type == MONO_TYPE_SZARRAY || klass_byval_arg->type == MONO_TYPE_ARRAY)
klass->sizes.element_size = element_size;
mono_memory_barrier ();
klass->size_inited = 1;
mono_loader_unlock ();
/*
* Compute static field layout and size
* Static fields can reference the class itself, so this has to be
* done after instance_size etc. are initialized.
*/
class_size = 0;
for (i = 0; i < top; i++) {
gint32 align;
guint32 size;
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
continue;
if (mono_field_is_deleted (field))
continue;
/* Type may not be initialized yet. Don't initialize it. If
it's a reference type we can get the size without
recursing */
if (mono_type_has_exceptions (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
break;
}
has_static_fields = TRUE;
size = mono_type_size (field->type, &align);
/* Check again in case initializing the field's type caused a failure */
if (mono_type_has_exceptions (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
break;
}
field_offsets [i] = class_size;
/*align is always non-zero here*/
field_offsets [i] += align - 1;
field_offsets [i] &= ~(align - 1);
class_size = field_offsets [i] + size;
}
if (has_static_fields && class_size == 0)
/* Simplify code which depends on class_size != 0 if the class has static fields */
class_size = 8;
/* Compute klass->has_static_refs */
has_static_refs = FALSE;
for (i = 0; i < top; i++) {
MonoType *ftype;
field = &klass->fields [i];
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype))
has_static_refs = TRUE;
}
}
/*valuetypes can't be neither bigger than 1Mb or empty. */
if (klass->valuetype && (klass->instance_size <= 0 || klass->instance_size > (0x100000 + MONO_ABI_SIZEOF (MonoObject)))) {
/* Special case compiler generated types */
/* Hard to check for [CompilerGenerated] here */
if (!strstr (klass->name, "StaticArrayInitTypeSize") && !strstr (klass->name, "$ArrayType"))
mono_class_set_type_load_failure (klass, "Value type instance size (%d) cannot be zero, negative, or bigger than 1Mb", klass->instance_size);
}
// Weak field support
//
// FIXME:
// - generic instances
// - Disallow on structs/static fields/nonref fields
gboolean has_weak_fields = FALSE;
if (mono_class_has_static_metadata (klass)) {
for (MonoClass *p = klass; p != NULL; p = p->parent) {
gpointer iter = NULL;
guint32 first_field_idx = mono_class_get_first_field_idx (p);
while ((field = mono_class_get_fields_internal (p, &iter))) {
guint32 field_idx = first_field_idx + (field - p->fields);
if (MONO_TYPE_IS_REFERENCE (field->type) && mono_assembly_is_weak_field (p->image, field_idx + 1)) {
has_weak_fields = TRUE;
mono_trace_message (MONO_TRACE_TYPE, "Field %s:%s at offset %x is weak.", m_field_get_parent (field)->name, field->name, field->offset);
}
}
}
}
/*
* Check that any fields of IsByRefLike type are instance
* fields and only inside other IsByRefLike structs.
*
* (Has to be done late because we call
* mono_class_from_mono_type_internal which may recursively
* refer to the current class)
*/
gboolean allow_isbyreflike_fields = m_class_is_byreflike (klass);
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if ((field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
continue;
MonoClass *field_class = NULL;
/* have to be careful not to recursively invoke mono_class_init on a static field.
* for example - if the field is an array of a subclass of klass, we can loop.
*/
switch (field->type->type) {
case MONO_TYPE_TYPEDBYREF:
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_GENERICINST:
field_class = mono_class_from_mono_type_internal (field->type);
break;
default:
break;
}
if (!field_class || !m_class_is_byreflike (field_class))
continue;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
mono_class_set_type_load_failure (klass, "Static ByRefLike field '%s' is not allowed", field->name);
return;
} else {
/* instance field */
if (allow_isbyreflike_fields)
continue;
mono_class_set_type_load_failure (klass, "Instance ByRefLike field '%s' not in a ref struct", field->name);
return;
}
}
/* Publish the data */
mono_loader_lock ();
if (!klass->rank)
klass->sizes.class_size = class_size;
klass->has_static_refs = has_static_refs;
klass->has_weak_fields = has_weak_fields;
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
field->offset = field_offsets [i];
}
mono_memory_barrier ();
klass->fields_inited = 1;
mono_loader_unlock ();
g_free (field_offsets);
g_free (fields_has_references);
}
static int finalize_slot = -1;
static void
initialize_object_slots (MonoClass *klass)
{
int i;
if (klass != mono_defaults.object_class || finalize_slot >= 0)
return;
mono_class_setup_vtable (klass);
for (i = 0; i < klass->vtable_size; ++i) {
if (!strcmp (klass->vtable [i]->name, "Finalize")) {
int const j = finalize_slot;
g_assert (j == -1 || j == i);
finalize_slot = i;
}
}
g_assert (finalize_slot >= 0);
}
int
mono_class_get_object_finalize_slot ()
{
return finalize_slot;
}
MonoMethod *
mono_class_get_default_finalize_method ()
{
int const i = finalize_slot;
return (i < 0) ? NULL : mono_defaults.object_class->vtable [i];
}
typedef struct {
MonoMethod *array_method;
char *name;
} GenericArrayMethodInfo;
static int generic_array_method_num = 0;
static GenericArrayMethodInfo *generic_array_method_info = NULL;
static void
setup_generic_array_ifaces (MonoClass *klass, MonoClass *iface, MonoMethod **methods, int pos, GHashTable *cache)
{
MonoGenericContext tmp_context;
MonoGenericClass *gclass;
int i;
// The interface can sometimes be a GTD in cases like IList
// See: https://github.com/mono/mono/issues/7095#issuecomment-470465597
if (mono_class_is_gtd (iface)) {
MonoType *ty = mono_class_gtd_get_canonical_inst (iface);
g_assert (ty->type == MONO_TYPE_GENERICINST);
gclass = ty->data.generic_class;
} else
gclass = mono_class_get_generic_class (iface);
tmp_context.class_inst = NULL;
tmp_context.method_inst = gclass->context.class_inst;
//g_print ("setting up array interface: %s\n", mono_type_get_name_full (m_class_get_byval_arg (iface), 0));
for (i = 0; i < generic_array_method_num; i++) {
ERROR_DECL (error);
MonoMethod *m = generic_array_method_info [i].array_method;
MonoMethod *inflated, *helper;
inflated = mono_class_inflate_generic_method_checked (m, &tmp_context, error);
mono_error_assert_ok (error);
helper = (MonoMethod*)g_hash_table_lookup (cache, inflated);
if (!helper) {
helper = mono_marshal_get_generic_array_helper (klass, generic_array_method_info [i].name, inflated);
g_hash_table_insert (cache, inflated, helper);
}
methods [pos ++] = helper;
}
}
static gboolean
check_method_exists (MonoClass *iface, const char *method_name)
{
g_assert (iface != NULL);
ERROR_DECL (method_lookup_error);
gboolean found = NULL != mono_class_get_method_from_name_checked (iface, method_name, -1, 0, method_lookup_error);
mono_error_cleanup (method_lookup_error);
return found;
}
static int
generic_array_methods (MonoClass *klass)
{
int i, count_generic = 0, mcount;
GList *list = NULL, *tmp;
if (generic_array_method_num)
return generic_array_method_num;
mono_class_setup_methods (klass->parent); /*This is setting up System.Array*/
g_assert (!mono_class_has_failure (klass->parent)); /*So hitting this assert is a huge problem*/
mcount = mono_class_get_method_count (klass->parent);
for (i = 0; i < mcount; i++) {
MonoMethod *m = klass->parent->methods [i];
if (!strncmp (m->name, "InternalArray__", 15)) {
count_generic++;
list = g_list_prepend (list, m);
}
}
list = g_list_reverse (list);
generic_array_method_info = (GenericArrayMethodInfo *)mono_image_alloc (mono_defaults.corlib, sizeof (GenericArrayMethodInfo) * count_generic);
i = 0;
for (tmp = list; tmp; tmp = tmp->next) {
const char *mname, *iname;
gchar *name;
MonoMethod *m = (MonoMethod *)tmp->data;
const char *ireadonlylist_prefix = "InternalArray__IReadOnlyList_";
const char *ireadonlycollection_prefix = "InternalArray__IReadOnlyCollection_";
MonoClass *iface = NULL;
if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
iname = "System.Collections.Generic.ICollection`1.";
mname = m->name + 27;
iface = mono_class_try_get_icollection_class ();
} else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
iname = "System.Collections.Generic.IEnumerable`1.";
mname = m->name + 27;
iface = mono_class_try_get_ienumerable_class ();
} else if (!strncmp (m->name, ireadonlylist_prefix, strlen (ireadonlylist_prefix))) {
iname = "System.Collections.Generic.IReadOnlyList`1.";
mname = m->name + strlen (ireadonlylist_prefix);
iface = mono_defaults.generic_ireadonlylist_class;
} else if (!strncmp (m->name, ireadonlycollection_prefix, strlen (ireadonlycollection_prefix))) {
iname = "System.Collections.Generic.IReadOnlyCollection`1.";
mname = m->name + strlen (ireadonlycollection_prefix);
iface = mono_class_try_get_ireadonlycollection_class ();
} else if (!strncmp (m->name, "InternalArray__", 15)) {
iname = "System.Collections.Generic.IList`1.";
mname = m->name + 15;
iface = mono_defaults.generic_ilist_class;
} else {
g_assert_not_reached ();
}
if (!iface || !check_method_exists (iface, mname))
continue;
generic_array_method_info [i].array_method = m;
name = (gchar *)mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
strcpy (name, iname);
strcpy (name + strlen (iname), mname);
generic_array_method_info [i].name = name;
i++;
}
/*g_print ("array generic methods: %d\n", count_generic);*/
/* only count the methods we actually added, not the ones that we
* skipped if they implement an interface method that was trimmed.
*/
generic_array_method_num = i;
g_list_free (list);
return generic_array_method_num;
}
static int array_get_method_count (MonoClass *klass)
{
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY)
/* Regular array */
/* ctor([int32]*rank) */
/* ctor([int32]*rank*2) */
/* Get */
/* Set */
/* Address */
return 5;
else if (klass_byval_arg->type == MONO_TYPE_SZARRAY && klass->rank == 1 && klass->element_class->rank)
/* Jagged arrays are typed as MONO_TYPE_SZARRAY but have an extra ctor in .net which creates an array of arrays */
/* ctor([int32]) */
/* ctor([int32], [int32]) */
/* Get */
/* Set */
/* Address */
return 5;
else
/* Vectors don't have additional constructor since a zero lower bound is assumed */
/* ctor([int32]*rank) */
/* Get */
/* Set */
/* Address */
return 4;
}
static gboolean array_supports_additional_ctor_method (MonoClass *klass)
{
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY)
/* Regular array */
return TRUE;
else if (klass_byval_arg->type == MONO_TYPE_SZARRAY && klass->rank == 1 && klass->element_class->rank)
/* Jagged array */
return TRUE;
else
/* Vector */
return FALSE;
}
/*
* Global pool of interface IDs, represented as a bitset.
* LOCKING: Protected by the classes lock.
*/
static MonoBitSet *global_interface_bitset = NULL;
/*
* mono_unload_interface_ids:
* @bitset: bit set of interface IDs
*
* When an image is unloaded, the interface IDs associated with
* the image are put back in the global pool of IDs so the numbers
* can be reused.
*/
void
mono_unload_interface_ids (MonoBitSet *bitset)
{
classes_lock ();
mono_bitset_sub (global_interface_bitset, bitset);
classes_unlock ();
}
void
mono_unload_interface_id (MonoClass *klass)
{
if (global_interface_bitset && klass->interface_id) {
classes_lock ();
mono_bitset_clear (global_interface_bitset, klass->interface_id);
classes_unlock ();
}
}
/**
* mono_get_unique_iid:
* \param klass interface
*
* Assign a unique integer ID to the interface represented by \p klass.
* The ID will positive and as small as possible.
* LOCKING: Acquires the classes lock.
* \returns The new ID.
*/
static guint32
mono_get_unique_iid (MonoClass *klass)
{
int iid;
g_assert (MONO_CLASS_IS_INTERFACE_INTERNAL (klass));
classes_lock ();
if (!global_interface_bitset) {
global_interface_bitset = mono_bitset_new (128, 0);
mono_bitset_set (global_interface_bitset, 0); //don't let 0 be a valid iid
}
iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
if (iid < 0) {
int old_size = mono_bitset_size (global_interface_bitset);
MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
mono_bitset_free (global_interface_bitset);
global_interface_bitset = new_set;
iid = old_size;
}
mono_bitset_set (global_interface_bitset, iid);
/* set the bit also in the per-image set */
if (!mono_class_is_ginst (klass)) {
if (klass->image->interface_bitset) {
if (iid >= mono_bitset_size (klass->image->interface_bitset)) {
MonoBitSet *new_set = mono_bitset_clone (klass->image->interface_bitset, iid + 1);
mono_bitset_free (klass->image->interface_bitset);
klass->image->interface_bitset = new_set;
}
} else {
klass->image->interface_bitset = mono_bitset_new (iid + 1, 0);
}
mono_bitset_set (klass->image->interface_bitset, iid);
}
classes_unlock ();
#ifndef MONO_SMALL_CONFIG
if (mono_print_vtable) {
int generic_id;
char *type_name = mono_type_full_name (m_class_get_byval_arg (klass));
MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
if (gklass && !gklass->context.class_inst->is_open) {
generic_id = gklass->context.class_inst->id;
g_assert (generic_id != 0);
} else {
generic_id = 0;
}
printf ("Interface: assigned id %d to %s|%s|%d\n", iid, klass->image->assembly_name, type_name, generic_id);
g_free (type_name);
}
#endif
/* I've confirmed iids safe past 16 bits, however bitset code uses a signed int while testing.
* Once this changes, it should be safe for us to allow 2^32-1 interfaces, until then 2^31-2 is the max. */
g_assert (iid < INT_MAX);
return iid;
}
/**
* mono_class_init_internal:
* \param klass the class to initialize
*
* Compute the \c instance_size, \c class_size and other infos that cannot be
* computed at \c mono_class_get time. Also compute vtable_size if possible.
* Initializes the following fields in \p klass:
* - all the fields initialized by \c mono_class_init_sizes
* - has_cctor
* - ghcimpl
* - inited
*
* LOCKING: Acquires the loader lock.
*
* \returns TRUE on success or FALSE if there was a problem in loading
* the type (incorrect assemblies, missing assemblies, methods, etc).
*/
gboolean
mono_class_init_internal (MonoClass *klass)
{
int i, vtable_size = 0, array_method_count = 0;
MonoCachedClassInfo cached_info;
gboolean has_cached_info;
gboolean locked = FALSE;
gboolean ghcimpl = FALSE;
gboolean has_cctor = FALSE;
int first_iface_slot = 0;
g_assert (klass);
/* Double-checking locking pattern */
if (klass->inited || mono_class_has_failure (klass))
return !mono_class_has_failure (klass);
/*g_print ("Init class %s\n", mono_type_get_full_name (klass));*/
/*
* This function can recursively call itself.
*/
GSList *init_list = (GSList *)mono_native_tls_get_value (init_pending_tls_id);
if (g_slist_find (init_list, klass)) {
mono_class_set_type_load_failure (klass, "Recursive type definition detected %s.%s", klass->name_space, klass->name);
goto leave_no_init_pending;
}
init_list = g_slist_prepend (init_list, klass);
mono_native_tls_set_value (init_pending_tls_id, init_list);
/*
* We want to avoid doing complicated work inside locks, so we compute all the required
* information and write it to @klass inside a lock.
*/
MonoType *klass_byval_arg;
klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY || klass_byval_arg->type == MONO_TYPE_SZARRAY) {
MonoClass *element_class = klass->element_class;
MonoClass *cast_class = klass->cast_class;
if (!element_class->inited)
mono_class_init_internal (element_class);
if (mono_class_set_type_load_failure_causedby_class (klass, element_class, "Could not load array element class"))
goto leave;
if (!cast_class->inited)
mono_class_init_internal (cast_class);
if (mono_class_set_type_load_failure_causedby_class (klass, cast_class, "Could not load array cast class"))
goto leave;
}
UnlockedIncrement (&mono_stats.initialized_class_count);
if (mono_class_is_ginst (klass) && !mono_class_get_generic_class (klass)->is_dynamic) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic Type Definition failed to init"))
goto leave;
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
mono_class_setup_interface_id (klass);
}
if (klass->parent && !klass->parent->inited)
mono_class_init_internal (klass->parent);
has_cached_info = mono_class_get_cached_class_info (klass, &cached_info);
/* Compute instance size etc. */
init_sizes_with_info (klass, has_cached_info ? &cached_info : NULL);
if (mono_class_has_failure (klass))
goto leave;
mono_class_setup_supertypes (klass);
initialize_object_slots (klass);
/*
* Initialize the rest of the data without creating a generic vtable if possible.
* If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
* also avoid computing a generic vtable.
*/
if (has_cached_info) {
/* AOT case */
vtable_size = cached_info.vtable_size;
ghcimpl = cached_info.ghcimpl;
has_cctor = cached_info.has_cctor;
} else if (klass->rank == 1 && klass_byval_arg->type == MONO_TYPE_SZARRAY) {
/* SZARRAY can have 3 vtable layouts, with and without the stelemref method and enum element type
* The first slot if for array with.
*/
static int szarray_vtable_size[3] = { 0 };
int slot;
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (klass))))
slot = 0;
else if (klass->element_class->enumtype)
slot = 1;
else
slot = 2;
/* SZARRAY case */
if (!szarray_vtable_size [slot]) {
mono_class_setup_vtable (klass);
szarray_vtable_size [slot] = klass->vtable_size;
vtable_size = klass->vtable_size;
} else {
vtable_size = szarray_vtable_size[slot];
}
} else if (mono_class_is_ginst (klass) && !MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
/* Generic instance case */
ghcimpl = gklass->ghcimpl;
has_cctor = gklass->has_cctor;
mono_class_setup_vtable (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to init"))
goto leave;
vtable_size = gklass->vtable_size;
} else {
/* General case */
/* C# doesn't allow interfaces to have cctors */
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || klass->image != mono_defaults.corlib) {
MonoMethod *cmethod = NULL;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
/* Generic instance case */
ghcimpl = gklass->ghcimpl;
has_cctor = gklass->has_cctor;
} else if (klass->type_token && !image_is_dynamic(klass->image)) {
cmethod = mono_find_method_in_metadata (klass, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
/* The find_method function ignores the 'flags' argument */
if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
has_cctor = 1;
} else {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
goto leave;
int mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
MonoMethod *method = klass->methods [i];
if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
(strcmp (".cctor", method->name) == 0)) {
has_cctor = 1;
break;
}
}
}
}
}
if (klass->rank) {
array_method_count = array_get_method_count (klass);
if (klass->interface_count) {
int count_generic = generic_array_methods (klass);
array_method_count += klass->interface_count * count_generic;
}
}
if (klass->parent) {
if (!klass->parent->vtable_size)
mono_class_setup_vtable (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class vtable failed to initialize"))
goto leave;
g_assert (klass->parent->vtable_size);
first_iface_slot = klass->parent->vtable_size;
if (mono_class_setup_need_stelemref_method (klass))
++first_iface_slot;
}
/*
* Do the actual changes to @klass inside the loader lock
*/
mono_loader_lock ();
locked = TRUE;
if (klass->inited || mono_class_has_failure (klass)) {
/* Somebody might have gotten in before us */
goto leave;
}
UnlockedIncrement (&mono_stats.initialized_class_count);
if (mono_class_is_ginst (klass) && !mono_class_get_generic_class (klass)->is_dynamic)
UnlockedIncrement (&mono_stats.generic_class_count);
if (mono_class_is_ginst (klass) || image_is_dynamic (klass->image) || !klass->type_token || (has_cached_info && !cached_info.has_nested_classes))
klass->nested_classes_inited = TRUE;
klass->ghcimpl = ghcimpl;
klass->has_cctor = has_cctor;
if (vtable_size)
klass->vtable_size = vtable_size;
if (has_cached_info) {
klass->has_finalize = cached_info.has_finalize;
klass->has_finalize_inited = TRUE;
}
if (klass->rank)
mono_class_set_method_count (klass, array_method_count);
mono_loader_unlock ();
locked = FALSE;
mono_class_setup_interface_offsets_internal (klass, first_iface_slot, TRUE);
if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass))
mono_class_set_type_load_failure (klass, "Invalid generic instantiation");
goto leave;
leave:
init_list = (GSList*)mono_native_tls_get_value (init_pending_tls_id);
init_list = g_slist_remove (init_list, klass);
mono_native_tls_set_value (init_pending_tls_id, init_list);
leave_no_init_pending:
if (locked)
mono_loader_unlock ();
/* Leave this for last */
mono_loader_lock ();
klass->inited = 1;
mono_loader_unlock ();
return !mono_class_has_failure (klass);
}
gboolean
mono_class_init_checked (MonoClass *klass, MonoError *error)
{
error_init (error);
gboolean const success = mono_class_init_internal (klass);
if (!success)
mono_error_set_for_class_failure (error, klass);
return success;
}
#ifndef DISABLE_COM
/*
* COM initialization is delayed until needed.
* However when a [ComImport] attribute is present on a type it will trigger
* the initialization. This is not a problem unless the BCL being executed
* lacks the types that COM depends on (e.g. Variant on Silverlight).
*/
static void
init_com_from_comimport (MonoClass *klass)
{
/* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
}
#endif /*DISABLE_COM*/
/*
* LOCKING: this assumes the loader lock is held
*/
void
mono_class_setup_parent (MonoClass *klass, MonoClass *parent)
{
gboolean system_namespace;
gboolean is_corlib = mono_is_corlib_image (klass->image);
system_namespace = !strcmp (klass->name_space, "System") && is_corlib;
/* if root of the hierarchy */
if (system_namespace && !strcmp (klass->name, "Object")) {
klass->parent = NULL;
klass->instance_size = MONO_ABI_SIZEOF (MonoObject);
return;
}
if (!strcmp (klass->name, "<Module>")) {
klass->parent = NULL;
klass->instance_size = 0;
return;
}
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
/* Imported COM Objects always derive from __ComObject. */
#ifndef DISABLE_COM
if (MONO_CLASS_IS_IMPORT (klass)) {
init_com_from_comimport (klass);
if (parent == mono_defaults.object_class)
parent = mono_class_get_com_object_class ();
}
#endif
if (!parent) {
/* set the parent to something useful and safe, but mark the type as broken */
parent = mono_defaults.object_class;
mono_class_set_type_load_failure (klass, "");
g_assert (parent);
}
klass->parent = parent;
if (mono_class_is_ginst (parent) && !parent->name) {
/*
* If the parent is a generic instance, we may get
* called before it is fully initialized, especially
* before it has its name.
*/
return;
}
klass->delegate = parent->delegate;
if (MONO_CLASS_IS_IMPORT (klass) || mono_class_is_com_object (parent))
mono_class_set_is_com_object (klass);
if (system_namespace) {
if (klass->name [0] == 'D' && !strcmp (klass->name, "Delegate"))
klass->delegate = 1;
}
if (klass->parent->enumtype || (mono_is_corlib_image (klass->parent->image) && (strcmp (klass->parent->name, "ValueType") == 0) &&
(strcmp (klass->parent->name_space, "System") == 0)))
klass->valuetype = 1;
if (mono_is_corlib_image (klass->parent->image) && ((strcmp (klass->parent->name, "Enum") == 0) && (strcmp (klass->parent->name_space, "System") == 0))) {
klass->valuetype = klass->enumtype = 1;
}
/*klass->enumtype = klass->parent->enumtype; */
} else {
/* initialize com types if COM interfaces are present */
#ifndef DISABLE_COM
if (MONO_CLASS_IS_IMPORT (klass))
init_com_from_comimport (klass);
#endif
klass->parent = NULL;
}
}
/* Locking: must be called with the loader lock held. */
void
mono_class_setup_interface_id_nolock (MonoClass *klass)
{
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || klass->interface_id)
return;
klass->interface_id = mono_get_unique_iid (klass);
if (mono_is_corlib_image (klass->image) && !strcmp (m_class_get_name_space (klass), "System.Collections.Generic")) {
//FIXME IEnumerator needs to be special because GetEnumerator uses magic under the hood
/* FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
* MS returns diferrent types based on which instance is called. For example:
* object obj = new byte[10][];
* Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
* Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
* a != b ==> true
*/
const char *name = m_class_get_name (klass);
if (!strcmp (name, "IList`1") || !strcmp (name, "ICollection`1") || !strcmp (name, "IEnumerable`1") || !strcmp (name, "IEnumerator`1"))
klass->is_array_special_interface = 1;
}
}
/*
* LOCKING: this assumes the loader lock is held
*/
void
mono_class_setup_mono_type (MonoClass *klass)
{
const char *name = klass->name;
const char *nspace = klass->name_space;
gboolean is_corlib = mono_is_corlib_image (klass->image);
klass->this_arg.byref__ = 1;
klass->this_arg.data.klass = klass;
klass->this_arg.type = MONO_TYPE_CLASS;
klass->_byval_arg.data.klass = klass;
klass->_byval_arg.type = MONO_TYPE_CLASS;
if (is_corlib && !strcmp (nspace, "System")) {
if (!strcmp (name, "ValueType")) {
/*
* do not set the valuetype bit for System.ValueType.
* klass->valuetype = 1;
*/
klass->blittable = TRUE;
} else if (!strcmp (name, "Enum")) {
/*
* do not set the valuetype bit for System.Enum.
* klass->valuetype = 1;
*/
klass->valuetype = 0;
klass->enumtype = 0;
} else if (!strcmp (name, "Object")) {
klass->_byval_arg.type = MONO_TYPE_OBJECT;
klass->this_arg.type = MONO_TYPE_OBJECT;
} else if (!strcmp (name, "String")) {
klass->_byval_arg.type = MONO_TYPE_STRING;
klass->this_arg.type = MONO_TYPE_STRING;
} else if (!strcmp (name, "TypedReference")) {
klass->_byval_arg.type = MONO_TYPE_TYPEDBYREF;
klass->this_arg.type = MONO_TYPE_TYPEDBYREF;
}
}
if (klass->valuetype) {
int t = MONO_TYPE_VALUETYPE;
if (is_corlib && !strcmp (nspace, "System")) {
switch (*name) {
case 'B':
if (!strcmp (name, "Boolean")) {
t = MONO_TYPE_BOOLEAN;
} else if (!strcmp(name, "Byte")) {
t = MONO_TYPE_U1;
klass->blittable = TRUE;
}
break;
case 'C':
if (!strcmp (name, "Char")) {
t = MONO_TYPE_CHAR;
}
break;
case 'D':
if (!strcmp (name, "Double")) {
t = MONO_TYPE_R8;
klass->blittable = TRUE;
}
break;
case 'I':
if (!strcmp (name, "Int32")) {
t = MONO_TYPE_I4;
klass->blittable = TRUE;
} else if (!strcmp(name, "Int16")) {
t = MONO_TYPE_I2;
klass->blittable = TRUE;
} else if (!strcmp(name, "Int64")) {
t = MONO_TYPE_I8;
klass->blittable = TRUE;
} else if (!strcmp(name, "IntPtr")) {
t = MONO_TYPE_I;
klass->blittable = TRUE;
}
break;
case 'S':
if (!strcmp (name, "Single")) {
t = MONO_TYPE_R4;
klass->blittable = TRUE;
} else if (!strcmp(name, "SByte")) {
t = MONO_TYPE_I1;
klass->blittable = TRUE;
}
break;
case 'U':
if (!strcmp (name, "UInt32")) {
t = MONO_TYPE_U4;
klass->blittable = TRUE;
} else if (!strcmp(name, "UInt16")) {
t = MONO_TYPE_U2;
klass->blittable = TRUE;
} else if (!strcmp(name, "UInt64")) {
t = MONO_TYPE_U8;
klass->blittable = TRUE;
} else if (!strcmp(name, "UIntPtr")) {
t = MONO_TYPE_U;
klass->blittable = TRUE;
}
break;
case 'T':
if (!strcmp (name, "TypedReference")) {
t = MONO_TYPE_TYPEDBYREF;
klass->blittable = TRUE;
}
break;
case 'V':
if (!strcmp (name, "Void")) {
t = MONO_TYPE_VOID;
}
break;
default:
break;
}
}
klass->_byval_arg.type = (MonoTypeEnum)t;
klass->this_arg.type = (MonoTypeEnum)t;
}
mono_class_setup_interface_id_nolock (klass);
}
static MonoMethod*
create_array_method (MonoClass *klass, const char *name, MonoMethodSignature *sig)
{
MonoMethod *method;
method = (MonoMethod *) mono_image_alloc0 (klass->image, sizeof (MonoMethodPInvoke));
method->klass = klass;
method->flags = METHOD_ATTRIBUTE_PUBLIC;
method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
method->signature = sig;
method->name = name;
method->slot = -1;
/* .ctor */
if (name [0] == '.') {
method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
} else {
method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
}
return method;
}
/*
* mono_class_setup_methods:
* @class: a class
*
* Initializes the 'methods' array in CLASS.
* Calling this method should be avoided if possible since it allocates a lot
* of long-living MonoMethod structures.
* Methods belonging to an interface are assigned a sequential slot starting
* from 0.
*
* On failure this function sets klass->has_failure and stores a MonoErrorBoxed with details
*/
void
mono_class_setup_methods (MonoClass *klass)
{
int i, count;
MonoMethod **methods;
if (klass->methods)
return;
if (mono_class_is_ginst (klass)) {
ERROR_DECL (error);
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
if (!mono_class_has_failure (gklass))
mono_class_setup_methods (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
/* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
count = mono_class_get_method_count (gklass);
methods = (MonoMethod **)mono_class_alloc0 (klass, sizeof (MonoMethod*) * (count + 1));
for (i = 0; i < count; i++) {
methods [i] = mono_class_inflate_generic_method_full_checked (
gklass->methods [i], klass, mono_class_get_context (klass), error);
if (!is_ok (error)) {
char *method = mono_method_full_name (gklass->methods [i], TRUE);
mono_class_set_type_load_failure (klass, "Could not inflate method %s due to %s", method, mono_error_get_message (error));
g_free (method);
mono_error_cleanup (error);
return;
}
}
} else if (klass->rank) {
ERROR_DECL (error);
MonoMethod *amethod;
MonoMethodSignature *sig;
int count_generic = 0, first_generic = 0;
int method_num = 0;
count = array_get_method_count (klass);
mono_class_setup_interfaces (klass, error);
g_assert (is_ok (error)); /*FIXME can this fail for array types?*/
if (klass->interface_count) {
count_generic = generic_array_methods (klass);
first_generic = count;
count += klass->interface_count * count_generic;
}
methods = (MonoMethod **)mono_class_alloc0 (klass, sizeof (MonoMethod*) * count);
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, ".ctor", sig);
methods [method_num++] = amethod;
if (array_supports_additional_ctor_method (klass)) {
sig = mono_metadata_signature_alloc (klass->image, klass->rank * 2);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank * 2; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, ".ctor", sig);
methods [method_num++] = amethod;
}
/* element Get (idx11, [idx2, ...]) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = m_class_get_byval_arg (m_class_get_element_class (klass));
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, "Get", sig);
methods [method_num++] = amethod;
/* element& Address (idx11, [idx2, ...]) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = &klass->element_class->this_arg;
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, "Address", sig);
methods [method_num++] = amethod;
/* void Set (idx11, [idx2, ...], element) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank + 1);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
sig->params [i] = m_class_get_byval_arg (m_class_get_element_class (klass));
amethod = create_array_method (klass, "Set", sig);
methods [method_num++] = amethod;
GHashTable *cache = g_hash_table_new (NULL, NULL);
for (i = 0; i < klass->interface_count; i++)
setup_generic_array_ifaces (klass, klass->interfaces [i], methods, first_generic + i * count_generic, cache);
g_hash_table_destroy (cache);
} else if (mono_class_has_static_metadata (klass)) {
ERROR_DECL (error);
int first_idx = mono_class_get_first_method_idx (klass);
count = mono_class_get_method_count (klass);
methods = (MonoMethod **)mono_class_alloc (klass, sizeof (MonoMethod*) * count);
for (i = 0; i < count; ++i) {
int idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, first_idx + i + 1);
methods [i] = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, error);
if (!methods [i]) {
mono_class_set_type_load_failure (klass, "Could not load method %d due to %s", i, mono_error_get_message (error));
mono_error_cleanup (error);
}
}
} else {
methods = (MonoMethod **)mono_class_alloc (klass, sizeof (MonoMethod*) * 1);
count = 0;
}
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
int slot = 0;
/*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
for (i = 0; i < count; ++i) {
if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
{
if (method_is_reabstracted (methods[i]->flags)) {
if (!methods [i]->is_inflated)
mono_method_set_is_reabstracted (methods [i]);
continue;
}
methods [i]->slot = slot++;
}
}
}
mono_image_lock (klass->image);
if (!klass->methods) {
mono_class_set_method_count (klass, count);
/* Needed because of the double-checking locking pattern */
mono_memory_barrier ();
klass->methods = methods;
}
mono_image_unlock (klass->image);
}
/*
* mono_class_setup_properties:
*
* Initialize klass->ext.property and klass->ext.properties.
*
* This method can fail the class.
*/
void
mono_class_setup_properties (MonoClass *klass)
{
guint startm, endm, i, j;
guint32 cols [MONO_PROPERTY_SIZE];
MonoTableInfo *msemt = &klass->image->tables [MONO_TABLE_METHODSEMANTICS];
MonoProperty *properties;
guint32 last;
int first, count;
MonoClassPropertyInfo *info;
info = mono_class_get_property_info (klass);
if (info)
return;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
mono_class_setup_properties (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
MonoClassPropertyInfo *ginfo = mono_class_get_property_info (gklass);
properties = mono_class_new0 (klass, MonoProperty, ginfo->count + 1);
for (i = 0; i < ginfo->count; i++) {
ERROR_DECL (error);
MonoProperty *prop = &properties [i];
*prop = ginfo->properties [i];
if (prop->get)
prop->get = mono_class_inflate_generic_method_full_checked (
prop->get, klass, mono_class_get_context (klass), error);
if (prop->set)
prop->set = mono_class_inflate_generic_method_full_checked (
prop->set, klass, mono_class_get_context (klass), error);
g_assert (is_ok (error)); /*FIXME proper error handling*/
prop->parent = klass;
}
first = ginfo->first;
count = ginfo->count;
} else {
first = mono_metadata_properties_from_typedef (klass->image, mono_metadata_token_index (klass->type_token) - 1, &last);
count = last - first;
if (count) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return;
}
properties = (MonoProperty *)mono_class_alloc0 (klass, sizeof (MonoProperty) * count);
for (i = first; i < last; ++i) {
mono_metadata_decode_table_row (klass->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
properties [i - first].parent = klass;
properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
properties [i - first].name = mono_metadata_string_heap (klass->image, cols [MONO_PROPERTY_NAME]);
startm = mono_metadata_methods_from_property (klass->image, i, &endm);
int first_idx = mono_class_get_first_method_idx (klass);
for (j = startm; j < endm; ++j) {
MonoMethod *method;
mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
if (klass->image->uncompressed_metadata) {
ERROR_DECL (error);
/* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], klass, NULL, error);
mono_error_cleanup (error); /* FIXME don't swallow this error */
} else {
method = klass->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - first_idx];
}
switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
case METHOD_SEMANTIC_SETTER:
properties [i - first].set = method;
break;
case METHOD_SEMANTIC_GETTER:
properties [i - first].get = method;
break;
default:
break;
}
}
}
}
info = (MonoClassPropertyInfo*)mono_class_alloc0 (klass, sizeof (MonoClassPropertyInfo));
info->first = first;
info->count = count;
info->properties = properties;
mono_memory_barrier ();
/* This might leak 'info' which was allocated from the image mempool */
mono_class_set_property_info (klass, info);
}
static MonoMethod**
inflate_method_listz (MonoMethod **methods, MonoClass *klass, MonoGenericContext *context)
{
MonoMethod **om, **retval;
int count;
for (om = methods, count = 0; *om; ++om, ++count)
;
retval = g_new0 (MonoMethod*, count + 1);
count = 0;
for (om = methods, count = 0; *om; ++om, ++count) {
ERROR_DECL (error);
retval [count] = mono_class_inflate_generic_method_full_checked (*om, klass, context, error);
g_assert (is_ok (error)); /*FIXME proper error handling*/
}
return retval;
}
/*This method can fail the class.*/
void
mono_class_setup_events (MonoClass *klass)
{
int first, count;
guint startm, endm, i, j;
guint32 cols [MONO_EVENT_SIZE];
MonoTableInfo *msemt = &klass->image->tables [MONO_TABLE_METHODSEMANTICS];
guint32 last;
MonoEvent *events;
MonoClassEventInfo *info = mono_class_get_event_info (klass);
if (info)
return;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
MonoGenericContext *context = NULL;
mono_class_setup_events (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
MonoClassEventInfo *ginfo = mono_class_get_event_info (gklass);
first = ginfo->first;
count = ginfo->count;
events = mono_class_new0 (klass, MonoEvent, count);
if (count)
context = mono_class_get_context (klass);
for (i = 0; i < count; i++) {
ERROR_DECL (error);
MonoEvent *event = &events [i];
MonoEvent *gevent = &ginfo->events [i];
event->parent = klass;
event->name = gevent->name;
event->add = gevent->add ? mono_class_inflate_generic_method_full_checked (gevent->add, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
event->remove = gevent->remove ? mono_class_inflate_generic_method_full_checked (gevent->remove, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
event->raise = gevent->raise ? mono_class_inflate_generic_method_full_checked (gevent->raise, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
#ifndef MONO_SMALL_CONFIG
event->other = gevent->other ? inflate_method_listz (gevent->other, klass, context) : NULL;
#endif
event->attrs = gevent->attrs;
}
} else {
first = mono_metadata_events_from_typedef (klass->image, mono_metadata_token_index (klass->type_token) - 1, &last);
count = last - first;
if (count) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass)) {
return;
}
}
events = (MonoEvent *)mono_class_alloc0 (klass, sizeof (MonoEvent) * count);
for (i = first; i < last; ++i) {
MonoEvent *event = &events [i - first];
mono_metadata_decode_table_row (klass->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
event->parent = klass;
event->attrs = cols [MONO_EVENT_FLAGS];
event->name = mono_metadata_string_heap (klass->image, cols [MONO_EVENT_NAME]);
startm = mono_metadata_methods_from_event (klass->image, i, &endm);
int first_idx = mono_class_get_first_method_idx (klass);
for (j = startm; j < endm; ++j) {
MonoMethod *method;
mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
if (klass->image->uncompressed_metadata) {
ERROR_DECL (error);
/* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], klass, NULL, error);
mono_error_cleanup (error); /* FIXME don't swallow this error */
} else {
method = klass->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - first_idx];
}
switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
case METHOD_SEMANTIC_ADD_ON:
event->add = method;
break;
case METHOD_SEMANTIC_REMOVE_ON:
event->remove = method;
break;
case METHOD_SEMANTIC_FIRE:
event->raise = method;
break;
case METHOD_SEMANTIC_OTHER: {
#ifndef MONO_SMALL_CONFIG
int n = 0;
if (event->other == NULL) {
event->other = g_new0 (MonoMethod*, 2);
} else {
while (event->other [n])
n++;
event->other = (MonoMethod **)g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
}
event->other [n] = method;
/* NULL terminated */
event->other [n + 1] = NULL;
#endif
break;
}
default:
break;
}
}
}
}
info = (MonoClassEventInfo*)mono_class_alloc0 (klass, sizeof (MonoClassEventInfo));
info->events = events;
info->first = first;
info->count = count;
mono_memory_barrier ();
mono_class_set_event_info (klass, info);
}
/*
* mono_class_setup_interface_id:
*
* Initializes MonoClass::interface_id if required.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_interface_id (MonoClass *klass)
{
g_assert (MONO_CLASS_IS_INTERFACE_INTERNAL (klass));
mono_loader_lock ();
mono_class_setup_interface_id_nolock (klass);
mono_loader_unlock ();
}
/*
* mono_class_setup_interfaces:
*
* Initialize klass->interfaces/interfaces_count.
* LOCKING: Acquires the loader lock.
* This function can fail the type.
*/
void
mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
{
int i, interface_count;
MonoClass *iface, **interfaces;
error_init (error);
if (klass->interfaces_inited)
return;
if (klass->rank == 1 && m_class_get_byval_arg (klass)->type != MONO_TYPE_ARRAY) {
MonoType *args [1];
MonoClass *array_ifaces [16];
/*
* Arrays implement IList and IReadOnlyList or their base interfaces if they are not linked out.
* For arrays of enums, they implement the interfaces for the base type as well.
*/
interface_count = 0;
if (mono_defaults.generic_ilist_class) {
array_ifaces [interface_count ++] = mono_defaults.generic_ilist_class;
} else {
iface = mono_class_try_get_icollection_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
if (mono_defaults.generic_ireadonlylist_class) {
array_ifaces [interface_count ++] = mono_defaults.generic_ireadonlylist_class;
} else {
iface = mono_class_try_get_ireadonlycollection_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
if (!mono_defaults.generic_ilist_class && !mono_defaults.generic_ireadonlylist_class) {
iface = mono_class_try_get_ienumerable_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
int mult = klass->element_class->enumtype ? 2 : 1;
interfaces = (MonoClass **)mono_image_alloc0 (klass->image, sizeof (MonoClass*) * interface_count * mult);
int itf_idx = 0;
args [0] = m_class_get_byval_arg (m_class_get_element_class (klass));
for (int i = 0; i < interface_count; ++i)
interfaces [itf_idx++] = mono_class_bind_generic_parameters (array_ifaces [i], 1, args, FALSE);
if (klass->element_class->enumtype) {
args [0] = mono_class_enum_basetype_internal (klass->element_class);
for (int i = 0; i < interface_count; ++i)
interfaces [itf_idx++] = mono_class_bind_generic_parameters (array_ifaces [i], 1, args, FALSE);
}
interface_count *= mult;
g_assert (itf_idx == interface_count);
} else if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_setup_interfaces (gklass, error);
if (!is_ok (error)) {
mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
interface_count = gklass->interface_count;
interfaces = mono_class_new0 (klass, MonoClass *, interface_count);
for (i = 0; i < interface_count; i++) {
interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
if (!is_ok (error)) {
mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
}
} else {
interface_count = 0;
interfaces = NULL;
}
mono_loader_lock ();
if (!klass->interfaces_inited) {
klass->interface_count = interface_count;
klass->interfaces = interfaces;
mono_memory_barrier ();
klass->interfaces_inited = TRUE;
}
mono_loader_unlock ();
}
/*
* mono_class_setup_has_finalizer:
*
* Initialize klass->has_finalizer if it isn't already initialized.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_has_finalizer (MonoClass *klass)
{
gboolean has_finalize = FALSE;
if (m_class_is_has_finalize_inited (klass))
return;
/* Interfaces and valuetypes are not supposed to have finalizers */
if (!(MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || m_class_is_valuetype (klass))) {
MonoMethod *cmethod = NULL;
if (m_class_get_rank (klass) == 1 && m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY) {
} else if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
has_finalize = mono_class_has_finalizer (gklass);
} else if (m_class_get_parent (klass) && m_class_has_finalize (m_class_get_parent (klass))) {
has_finalize = TRUE;
} else {
if (m_class_get_parent (klass)) {
/*
* Can't search in metadata for a method named Finalize, because that
* ignores overrides.
*/
mono_class_setup_vtable (klass);
if (mono_class_has_failure (klass))
cmethod = NULL;
else
cmethod = m_class_get_vtable (klass) [mono_class_get_object_finalize_slot ()];
}
if (cmethod) {
g_assert (m_class_get_vtable_size (klass) > mono_class_get_object_finalize_slot ());
if (m_class_get_parent (klass)) {
if (cmethod->is_inflated)
cmethod = ((MonoMethodInflated*)cmethod)->declaring;
if (cmethod != mono_class_get_default_finalize_method ())
has_finalize = TRUE;
}
}
}
}
mono_loader_lock ();
if (!m_class_is_has_finalize_inited (klass)) {
klass->has_finalize = has_finalize ? 1 : 0;
mono_memory_barrier ();
klass->has_finalize_inited = TRUE;
}
mono_loader_unlock ();
}
/*
* mono_class_setup_supertypes:
* @class: a class
*
* Build the data structure needed to make fast type checks work.
* This currently sets two fields in @class:
* - idepth: distance between @class and System.Object in the type
* hierarchy + 1
* - supertypes: array of classes: each element has a class in the hierarchy
* starting from @class up to System.Object
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_supertypes (MonoClass *klass)
{
int ms, idepth;
MonoClass **supertypes;
mono_atomic_load_acquire (supertypes, MonoClass **, &klass->supertypes);
if (supertypes)
return;
if (klass->parent && !klass->parent->supertypes)
mono_class_setup_supertypes (klass->parent);
if (klass->parent)
idepth = klass->parent->idepth + 1;
else
idepth = 1;
ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, idepth);
supertypes = (MonoClass **)mono_class_alloc0 (klass, sizeof (MonoClass *) * ms);
if (klass->parent) {
CHECKED_METADATA_WRITE_PTR ( supertypes [idepth - 1] , klass );
int supertype_idx;
for (supertype_idx = 0; supertype_idx < klass->parent->idepth; supertype_idx++)
CHECKED_METADATA_WRITE_PTR ( supertypes [supertype_idx] , klass->parent->supertypes [supertype_idx] );
} else {
CHECKED_METADATA_WRITE_PTR ( supertypes [0] , klass );
}
mono_memory_barrier ();
mono_loader_lock ();
klass->idepth = idepth;
/* Needed so idepth is visible before supertypes is set */
mono_memory_barrier ();
klass->supertypes = supertypes;
mono_loader_unlock ();
}
/* mono_class_setup_nested_types:
*
* Initialize the nested_classes property for the given MonoClass if it hasn't already been initialized.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_nested_types (MonoClass *klass)
{
ERROR_DECL (error);
GList *classes, *nested_classes, *l;
int i;
if (klass->nested_classes_inited)
return;
if (!klass->type_token) {
mono_loader_lock ();
klass->nested_classes_inited = TRUE;
mono_loader_unlock ();
return;
}
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
classes = NULL;
while (i) {
MonoClass* nclass;
guint32 cols [MONO_NESTED_CLASS_SIZE];
mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED], error);
if (!is_ok (error)) {
/*FIXME don't swallow the error message*/
mono_error_cleanup (error);
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
continue;
}
classes = g_list_prepend (classes, nclass);
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
}
nested_classes = NULL;
for (l = classes; l; l = l->next)
nested_classes = mono_g_list_prepend_image (klass->image, nested_classes, l->data);
g_list_free (classes);
mono_loader_lock ();
if (!klass->nested_classes_inited) {
mono_class_set_nested_classes_property (klass, nested_classes);
mono_memory_barrier ();
klass->nested_classes_inited = TRUE;
}
mono_loader_unlock ();
}
/**
* mono_class_create_array_fill_type:
*
* Returns a \c MonoClass that is used by SGen to fill out nursery fragments before a collection.
*/
MonoClass *
mono_class_create_array_fill_type (void)
{
static MonoClassArray aklass;
aklass.klass.class_kind = MONO_CLASS_GC_FILLER;
aklass.klass.element_class = mono_defaults.int64_class;
aklass.klass.rank = 1;
aklass.klass.instance_size = MONO_SIZEOF_MONO_ARRAY;
aklass.klass.sizes.element_size = 8;
aklass.klass.size_inited = 1;
aklass.klass.name = "array_filler_type";
return &aklass.klass;
}
void
mono_class_set_runtime_vtable (MonoClass *klass, MonoVTable *vtable)
{
klass->runtime_vtable = vtable;
}
/**
* mono_classes_init:
*
* Initialize the resources used by this module.
* Known racy counters: `class_gparam_count`, `classes_size` and `mono_inflated_methods_size`
*/
MONO_NO_SANITIZE_THREAD
void
mono_classes_init (void)
{
mono_os_mutex_init (&classes_mutex);
mono_native_tls_alloc (&setup_fields_tls_id, NULL);
mono_native_tls_alloc (&init_pending_tls_id, NULL);
mono_counters_register ("MonoClassDef count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_def_count);
mono_counters_register ("MonoClassGtd count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_gtd_count);
mono_counters_register ("MonoClassGenericInst count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ginst_count);
mono_counters_register ("MonoClassGenericParam count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_gparam_count);
mono_counters_register ("MonoClassArray count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_array_count);
mono_counters_register ("MonoClassPointer count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_pointer_count);
mono_counters_register ("Inflated methods size",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &mono_inflated_methods_size);
mono_counters_register ("Inflated classes size",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
mono_counters_register ("MonoClass size",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
}
| /**
* \file MonoClass construction and initialization
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2012 Xamarin Inc (http://www.xamarin.com)
* Copyright 2018 Microsoft
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include <config.h>
#include <mono/metadata/class-init.h>
#include <mono/metadata/class-init-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/marshal.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/unlocked.h>
#ifdef MONO_CLASS_DEF_PRIVATE
/* Class initialization gets to see the fields of MonoClass */
#define REALLY_INCLUDE_CLASS_DEF 1
#include <mono/metadata/class-private-definition.h>
#undef REALLY_INCLUDE_CLASS_DEF
#endif
#define FEATURE_COVARIANT_RETURNS
gboolean mono_print_vtable = FALSE;
gboolean mono_align_small_structs = FALSE;
/* Set by the EE */
gint32 mono_simd_register_size;
/* Statistics */
static gint32 classes_size;
static gint32 inflated_classes_size;
gint32 mono_inflated_methods_size;
static gint32 class_def_count, class_gtd_count, class_ginst_count, class_gparam_count, class_array_count, class_pointer_count;
/* Low level lock which protects data structures in this module */
static mono_mutex_t classes_mutex;
static gboolean class_kind_may_contain_generic_instances (MonoTypeKind kind);
static void mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd);
static int generic_array_methods (MonoClass *klass);
static void setup_generic_array_ifaces (MonoClass *klass, MonoClass *iface, MonoMethod **methods, int pos, GHashTable *cache);
static gboolean class_has_isbyreflike_attribute (MonoClass *klass);
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(icollection, "System.Collections.Generic", "ICollection`1");
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(ienumerable, "System.Collections.Generic", "IEnumerable`1");
static
GENERATE_TRY_GET_CLASS_WITH_CACHE(ireadonlycollection, "System.Collections.Generic", "IReadOnlyCollection`1");
/* This TLS variable points to a GSList of classes which have setup_fields () executing */
static MonoNativeTlsKey setup_fields_tls_id;
static MonoNativeTlsKey init_pending_tls_id;
static void
classes_lock (void)
{
mono_locks_os_acquire (&classes_mutex, ClassesLock);
}
static void
classes_unlock (void)
{
mono_locks_os_release (&classes_mutex, ClassesLock);
}
/*
We use gclass recording to allow recursive system f types to be referenced by a parent.
Given the following type hierarchy:
class TextBox : TextBoxBase<TextBox> {}
class TextBoxBase<T> : TextInput<TextBox> where T : TextBoxBase<T> {}
class TextInput<T> : Input<T> where T: TextInput<T> {}
class Input<T> {}
The runtime tries to load TextBoxBase<>.
To load TextBoxBase<> to do so it must resolve the parent which is TextInput<TextBox>.
To instantiate TextInput<TextBox> it must resolve TextInput<> and TextBox.
To load TextBox it must resolve the parent which is TextBoxBase<TextBox>.
At this point the runtime must instantiate TextBoxBase<TextBox>. Both types are partially loaded
at this point, iow, both are registered in the type map and both and a NULL parent. This means
that the resulting generic instance will have a NULL parent, which is wrong and will cause breakage.
To fix that what we do is to record all generic instantes created while resolving the parent of
any generic type definition and, after resolved, correct the parent field if needed.
*/
static int record_gclass_instantiation;
static GSList *gclass_recorded_list;
typedef gboolean (*gclass_record_func) (MonoClass*, void*);
/*
* LOCKING: loader lock must be held until pairing disable_gclass_recording is called.
*/
static void
enable_gclass_recording (void)
{
++record_gclass_instantiation;
}
/*
* LOCKING: loader lock must be held since pairing enable_gclass_recording was called.
*/
static void
disable_gclass_recording (gclass_record_func func, void *user_data)
{
GSList **head = &gclass_recorded_list;
g_assert (record_gclass_instantiation > 0);
--record_gclass_instantiation;
while (*head) {
GSList *node = *head;
if (func ((MonoClass*)node->data, user_data)) {
*head = node->next;
g_slist_free_1 (node);
} else {
head = &node->next;
}
}
/* We automatically discard all recorded gclasses when disabled. */
if (!record_gclass_instantiation && gclass_recorded_list) {
g_slist_free (gclass_recorded_list);
gclass_recorded_list = NULL;
}
}
#define mono_class_new0(klass,struct_type, n_structs) \
((struct_type *) mono_class_alloc0 ((klass), ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
/**
* mono_class_setup_basic_field_info:
* \param class The class to initialize
*
* Initializes the following fields in MonoClass:
* * klass->fields (only field->parent and field->name)
* * klass->field.count
* * klass->first_field_idx
* LOCKING: Acquires the loader lock
*/
void
mono_class_setup_basic_field_info (MonoClass *klass)
{
MonoGenericClass *gklass;
MonoClassField *field;
MonoClassField *fields;
MonoClass *gtd;
MonoImage *image;
int i, top;
if (klass->fields)
return;
gklass = mono_class_try_get_generic_class (klass);
gtd = gklass ? mono_class_get_generic_type_definition (klass) : NULL;
image = klass->image;
if (gklass && image_is_dynamic (gklass->container_class->image) && !gklass->container_class->wastypebuilder) {
/*
* This happens when a generic instance of an unfinished generic typebuilder
* is used as an element type for creating an array type. We can't initialize
* the fields of this class using the fields of gklass, since gklass is not
* finished yet, fields could be added to it later.
*/
return;
}
if (gtd) {
mono_class_setup_basic_field_info (gtd);
mono_loader_lock ();
mono_class_set_field_count (klass, mono_class_get_field_count (gtd));
mono_loader_unlock ();
}
top = mono_class_get_field_count (klass);
fields = (MonoClassField *)mono_class_alloc0 (klass, sizeof (MonoClassField) * top);
/*
* Fetch all the field information.
*/
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
for (i = 0; i < top; i++) {
field = &fields [i];
m_field_set_parent (field, klass);
if (gtd) {
field->name = mono_field_get_name (>d->fields [i]);
} else {
int idx = first_field_idx + i;
/* first_field_idx and idx points into the fieldptr table */
guint32 name_idx = mono_metadata_decode_table_row_col (image, MONO_TABLE_FIELD, idx, MONO_FIELD_NAME);
/* The name is needed for fieldrefs */
field->name = mono_metadata_string_heap (image, name_idx);
}
}
mono_memory_barrier ();
mono_loader_lock ();
if (!klass->fields)
klass->fields = fields;
mono_loader_unlock ();
}
/**
* mono_class_setup_fields:
* \p klass The class to initialize
*
* Initializes klass->fields, computes class layout and sizes.
* typebuilder_setup_fields () is the corresponding function for dynamic classes.
* Sets the following fields in \p klass:
* - all the fields initialized by mono_class_init_sizes ()
* - element_class/cast_class (for enums)
* - sizes:element_size (for arrays)
* - field->type/offset for all fields
* - fields_inited
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_fields (MonoClass *klass)
{
ERROR_DECL (error);
MonoImage *m = klass->image;
int top;
guint32 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
int i;
guint32 real_size = 0;
guint32 packing_size = 0;
int instance_size;
gboolean explicit_size;
MonoClassField *field;
MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
MonoClass *gtd = gklass ? mono_class_get_generic_type_definition (klass) : NULL;
if (klass->fields_inited)
return;
if (gklass && image_is_dynamic (gklass->container_class->image) && !gklass->container_class->wastypebuilder) {
/*
* This happens when a generic instance of an unfinished generic typebuilder
* is used as an element type for creating an array type. We can't initialize
* the fields of this class using the fields of gklass, since gklass is not
* finished yet, fields could be added to it later.
*/
return;
}
mono_class_setup_basic_field_info (klass);
top = mono_class_get_field_count (klass);
if (gtd) {
mono_class_setup_fields (gtd);
if (mono_class_set_type_load_failure_causedby_class (klass, gtd, "Generic type definition failed"))
return;
}
instance_size = 0;
if (klass->parent) {
/* For generic instances, klass->parent might not have been initialized */
mono_class_init_internal (klass->parent);
mono_class_setup_fields (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Could not set up parent class"))
return;
instance_size = klass->parent->instance_size;
} else {
instance_size = MONO_ABI_SIZEOF (MonoObject);
}
/* Get the real size */
explicit_size = mono_metadata_packing_from_typedef (klass->image, klass->type_token, &packing_size, &real_size);
if (explicit_size)
instance_size += real_size;
if (mono_is_corlib_image (klass->image) && !strcmp (klass->name_space, "System.Numerics") && !strcmp (klass->name, "Register")) {
if (mono_simd_register_size)
instance_size += mono_simd_register_size;
}
/*
* This function can recursively call itself.
* Prevent infinite recursion by using a list in TLS.
*/
GSList *init_list = (GSList *)mono_native_tls_get_value (setup_fields_tls_id);
if (g_slist_find (init_list, klass))
return;
init_list = g_slist_prepend (init_list, klass);
mono_native_tls_set_value (setup_fields_tls_id, init_list);
/*
* Fetch all the field information.
*/
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
for (i = 0; i < top; i++) {
int idx = first_field_idx + i;
field = &klass->fields [i];
if (!field->type) {
mono_field_resolve_type (field, error);
if (!is_ok (error)) {
/*mono_field_resolve_type already failed class*/
mono_error_cleanup (error);
break;
}
if (!field->type)
g_error ("could not resolve %s:%s\n", mono_type_get_full_name(klass), field->name);
g_assert (field->type);
}
if (!mono_type_get_underlying_type (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' is an enum type with a bad underlying type", field->name);
break;
}
if (mono_field_is_deleted (field))
continue;
if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
guint32 uoffset;
mono_metadata_field_info (m, idx, &uoffset, NULL, NULL);
int offset = uoffset;
if (offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
mono_class_set_type_load_failure (klass, "Missing field layout info for %s", field->name);
break;
}
if (m_type_is_byref (field->type) && (offset % MONO_ABI_ALIGNOF (gpointer) != 0)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid offset", field->name);
break;
}
if (offset < -1) { /*-1 is used to encode special static fields */
mono_class_set_type_load_failure (klass, "Field '%s' has a negative offset %d", field->name, offset);
break;
}
if (mono_class_is_gtd (klass)) {
mono_class_set_type_load_failure (klass, "Generic class cannot have explicit layout.");
break;
}
}
if (mono_type_has_exceptions (field->type)) {
char *class_name = mono_type_get_full_name (klass);
char *type_name = mono_type_full_name (field->type);
mono_class_set_type_load_failure (klass, "Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
g_free (class_name);
g_free (type_name);
break;
}
if (m_type_is_byref (field->type)) {
if (!m_class_is_byreflike (klass)) {
char *class_name = mono_type_get_full_name (klass);
mono_class_set_type_load_failure (klass, "Type %s is not a ByRefLike type so ref field, '%s', is invalid", class_name, field->name);
g_free (class_name);
break;
}
}
/* The def_value of fields is compute lazily during vtable creation */
}
if (!mono_class_has_failure (klass)) {
mono_loader_lock ();
mono_class_layout_fields (klass, instance_size, packing_size, real_size, FALSE);
mono_loader_unlock ();
}
init_list = g_slist_remove (init_list, klass);
mono_native_tls_set_value (setup_fields_tls_id, init_list);
}
static gboolean
discard_gclass_due_to_failure (MonoClass *gclass, void *user_data)
{
return mono_class_get_generic_class (gclass)->container_class == user_data;
}
static gboolean
fix_gclass_incomplete_instantiation (MonoClass *gclass, void *user_data)
{
MonoClass *gtd = (MonoClass*)user_data;
/* Only try to fix generic instances of @gtd */
if (mono_class_get_generic_class (gclass)->container_class != gtd)
return FALSE;
/* Check if the generic instance has no parent. */
if (gtd->parent && !gclass->parent)
mono_generic_class_setup_parent (gclass, gtd);
return TRUE;
}
static void
mono_class_set_failure_and_error (MonoClass *klass, MonoError *error, const char *msg)
{
mono_class_set_type_load_failure (klass, "%s", msg);
mono_error_set_type_load_class (error, klass, "%s", msg);
}
/**
* mono_class_create_from_typedef:
* \param image: image where the token is valid
* \param type_token: typedef token
* \param error: used to return any error found while creating the type
*
* Create the MonoClass* representing the specified type token.
* \p type_token must be a TypeDef token.
*
* FIXME: don't return NULL on failure, just let the caller figure it out.
*/
MonoClass *
mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError *error)
{
MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
MonoClass *klass, *parent = NULL;
guint32 cols [MONO_TYPEDEF_SIZE];
guint32 cols_next [MONO_TYPEDEF_SIZE];
guint tidx = mono_metadata_token_index (type_token);
MonoGenericContext *context = NULL;
const char *name, *nspace;
guint icount = 0;
MonoClass **interfaces;
guint32 field_last, method_last;
guint32 nesting_tokeen;
error_init (error);
/* FIXME: metadata-update - this function needs extensive work */
if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || mono_metadata_table_bounds_check (image, MONO_TABLE_TYPEDEF, tidx)) {
mono_error_set_bad_image (error, image, "Invalid typedef token %x", type_token);
return NULL;
}
mono_loader_lock ();
if ((klass = (MonoClass *)mono_internal_hash_table_lookup (&image->class_cache, GUINT_TO_POINTER (type_token)))) {
mono_loader_unlock ();
return klass;
}
mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
if (mono_metadata_has_generic_params (image, type_token)) {
klass = (MonoClass*)mono_image_alloc0 (image, sizeof (MonoClassGtd));
klass->class_kind = MONO_CLASS_GTD;
UnlockedAdd (&classes_size, sizeof (MonoClassGtd));
++class_gtd_count;
} else {
klass = (MonoClass*)mono_image_alloc0 (image, sizeof (MonoClassDef));
klass->class_kind = MONO_CLASS_DEF;
UnlockedAdd (&classes_size, sizeof (MonoClassDef));
++class_def_count;
}
klass->name = name;
klass->name_space = nspace;
MONO_PROFILER_RAISE (class_loading, (klass));
klass->image = image;
klass->type_token = type_token;
mono_class_set_flags (klass, cols [MONO_TYPEDEF_FLAGS]);
mono_internal_hash_table_insert (&image->class_cache, GUINT_TO_POINTER (type_token), klass);
/*
* Check whether we're a generic type definition.
*/
if (mono_class_is_gtd (klass)) {
MonoGenericContainer *generic_container = mono_metadata_load_generic_params (image, klass->type_token, NULL, klass);
context = &generic_container->context;
mono_class_set_generic_container (klass, generic_container);
MonoType *canonical_inst = &((MonoClassGtd*)klass)->canonical_inst;
canonical_inst->type = MONO_TYPE_GENERICINST;
canonical_inst->data.generic_class = mono_metadata_lookup_generic_class (klass, context->class_inst, FALSE);
enable_gclass_recording ();
}
if (cols [MONO_TYPEDEF_EXTENDS]) {
MonoClass *tmp;
guint32 parent_token = mono_metadata_token_from_dor (cols [MONO_TYPEDEF_EXTENDS]);
if (mono_metadata_token_table (parent_token) == MONO_TABLE_TYPESPEC) {
/*WARNING: this must satisfy mono_metadata_type_hash*/
klass->this_arg.byref__ = 1;
klass->this_arg.data.klass = klass;
klass->this_arg.type = MONO_TYPE_CLASS;
klass->_byval_arg.data.klass = klass;
klass->_byval_arg.type = MONO_TYPE_CLASS;
}
parent = mono_class_get_checked (image, parent_token, error);
if (parent && context) /* Always inflate */
parent = mono_class_inflate_generic_class_checked (parent, context, error);
if (parent == NULL) {
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
goto parent_failure;
}
for (tmp = parent; tmp; tmp = tmp->parent) {
if (tmp == klass) {
mono_class_set_failure_and_error (klass, error, "Cycle found while resolving parent");
goto parent_failure;
}
if (mono_class_is_gtd (klass) && mono_class_is_ginst (tmp) && mono_class_get_generic_class (tmp)->container_class == klass) {
mono_class_set_failure_and_error (klass, error, "Parent extends generic instance of this type");
goto parent_failure;
}
}
}
mono_class_setup_parent (klass, parent);
/* uses ->valuetype, which is initialized by mono_class_setup_parent above */
mono_class_setup_mono_type (klass);
if (mono_class_is_gtd (klass))
disable_gclass_recording (fix_gclass_incomplete_instantiation, klass);
/*
* This might access klass->_byval_arg for recursion generated by generic constraints,
* so it has to come after setup_mono_type ().
*/
if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
klass->nested_in = mono_class_create_from_typedef (image, nesting_tokeen, error);
if (!is_ok (error)) {
/*FIXME implement a mono_class_set_failure_from_mono_error */
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
}
if ((mono_class_get_flags (klass) & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
klass->unicode = 1;
#ifdef HOST_WIN32
if ((mono_class_get_flags (klass) & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_AUTO_CLASS)
klass->unicode = 1;
#endif
klass->cast_class = klass->element_class = klass;
if (mono_is_corlib_image (klass->image)) {
switch (m_class_get_byval_arg (klass)->type) {
case MONO_TYPE_I1:
if (mono_defaults.byte_class)
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_U1:
if (mono_defaults.sbyte_class)
mono_defaults.sbyte_class = klass;
break;
case MONO_TYPE_I2:
if (mono_defaults.uint16_class)
mono_defaults.uint16_class = klass;
break;
case MONO_TYPE_U2:
if (mono_defaults.int16_class)
klass->cast_class = mono_defaults.int16_class;
break;
case MONO_TYPE_I4:
if (mono_defaults.uint32_class)
mono_defaults.uint32_class = klass;
break;
case MONO_TYPE_U4:
if (mono_defaults.int32_class)
klass->cast_class = mono_defaults.int32_class;
break;
case MONO_TYPE_I8:
if (mono_defaults.uint64_class)
mono_defaults.uint64_class = klass;
break;
case MONO_TYPE_U8:
if (mono_defaults.int64_class)
klass->cast_class = mono_defaults.int64_class;
break;
default:
break;
}
}
if (!klass->enumtype) {
if (!mono_metadata_interfaces_from_typedef_full (
image, type_token, &interfaces, &icount, FALSE, context, error)){
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
/* This is required now that it is possible for more than 2^16 interfaces to exist. */
g_assert(icount <= 65535);
klass->interfaces = interfaces;
klass->interface_count = icount;
klass->interfaces_inited = 1;
}
/*g_print ("Load class %s\n", name);*/
/*
* Compute the field and method lists
*/
/*
* EnC metadata-update: new classes are added with method and field indices set to 0, new
* methods are added using the EnCLog AddMethod or AddField functions that will be added to
* MonoClassMetadataUpdateInfo
*/
if (G_LIKELY (cols [MONO_TYPEDEF_FIELD_LIST] != 0 || cols [MONO_TYPEDEF_METHOD_LIST] != 0)) {
int first_field_idx;
first_field_idx = cols [MONO_TYPEDEF_FIELD_LIST] - 1;
mono_class_set_first_field_idx (klass, first_field_idx);
int first_method_idx;
first_method_idx = cols [MONO_TYPEDEF_METHOD_LIST] - 1;
mono_class_set_first_method_idx (klass, first_method_idx);
if (table_info_get_rows (tt) > tidx) {
mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE);
field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1;
method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1;
} else {
field_last = table_info_get_rows (&image->tables [MONO_TABLE_FIELD]);
method_last = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
}
if (cols [MONO_TYPEDEF_FIELD_LIST] &&
cols [MONO_TYPEDEF_FIELD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_FIELD]))
mono_class_set_field_count (klass, field_last - first_field_idx);
if (cols [MONO_TYPEDEF_METHOD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_METHOD]))
mono_class_set_method_count (klass, method_last - first_method_idx);
}
/* reserve space to store vector pointer in arrays */
if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) {
klass->instance_size += 2 * TARGET_SIZEOF_VOID_P;
/* TODO: check that array has 0 non-const fields */
}
if (klass->enumtype) {
MonoType *enum_basetype = mono_class_find_enum_basetype (klass, error);
if (!enum_basetype) {
/*set it to a default value as the whole runtime can't handle this to be null*/
klass->cast_class = klass->element_class = mono_defaults.int32_class;
mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
klass->cast_class = klass->element_class = mono_class_from_mono_type_internal (enum_basetype);
}
/*
* If we're a generic type definition, load the constraints.
* We must do this after the class has been constructed to make certain recursive scenarios
* work.
*/
if (mono_class_is_gtd (klass) && !mono_metadata_load_generic_param_constraints_checked (image, type_token, mono_class_get_generic_container (klass), error)) {
mono_class_set_type_load_failure (klass, "Could not load generic parameter constrains due to %s", mono_error_get_message (error));
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
if (klass->image->assembly_name && !strcmp (klass->image->assembly_name, "Mono.Simd") && !strcmp (nspace, "Mono.Simd")) {
if (!strncmp (name, "Vector", 6))
klass->simd_type = !strcmp (name + 6, "2d") || !strcmp (name + 6, "2ul") || !strcmp (name + 6, "2l") || !strcmp (name + 6, "4f") || !strcmp (name + 6, "4ui") || !strcmp (name + 6, "4i") || !strcmp (name + 6, "8s") || !strcmp (name + 6, "8us") || !strcmp (name + 6, "16b") || !strcmp (name + 6, "16sb");
} else if (klass->image->assembly_name && !strcmp (klass->image->assembly_name, "System.Numerics") && !strcmp (nspace, "System.Numerics")) {
/* The JIT can't handle SIMD types with != 16 size yet */
//if (!strcmp (name, "Vector2") || !strcmp (name, "Vector3") || !strcmp (name, "Vector4"))
if (!strcmp (name, "Vector4"))
klass->simd_type = 1;
}
// compute is_byreflike
if (m_class_is_valuetype (klass))
if (class_has_isbyreflike_attribute (klass))
klass->is_byreflike = 1;
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
parent_failure:
if (mono_class_is_gtd (klass))
disable_gclass_recording (discard_gclass_due_to_failure, klass);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_failed, (klass));
return NULL;
}
static void
mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd)
{
if (gtd->parent) {
ERROR_DECL (error);
MonoGenericClass *gclass = mono_class_get_generic_class (klass);
klass->parent = mono_class_inflate_generic_class_checked (gtd->parent, mono_generic_class_get_context (gclass), error);
if (!is_ok (error)) {
/*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
klass->parent = mono_defaults.object_class;
mono_class_set_type_load_failure (klass, "Parent is a generic type instantiation that failed due to: %s", mono_error_get_message (error));
mono_error_cleanup (error);
}
}
mono_loader_lock ();
if (klass->parent)
mono_class_setup_parent (klass, klass->parent);
if (klass->enumtype) {
klass->cast_class = gtd->cast_class;
klass->element_class = gtd->element_class;
}
mono_loader_unlock ();
}
struct FoundAttrUD {
/* inputs */
const char *nspace;
const char *name;
gboolean in_corlib;
/* output */
gboolean has_attr;
};
static gboolean
has_wellknown_attribute_func (MonoImage *image, guint32 typeref_scope_token, const char *nspace, const char *name, guint32 method_token, gpointer user_data)
{
struct FoundAttrUD *has_attr = (struct FoundAttrUD *)user_data;
if (!strcmp (name, has_attr->name) && !strcmp (nspace, has_attr->nspace)) {
has_attr->has_attr = TRUE;
return TRUE;
}
/* TODO: use typeref_scope_token to check that attribute comes from
* corlib if in_corlib is TRUE, without triggering an assembly load.
* If we're inside corlib, expect the scope to be
* MONO_RESOLUTION_SCOPE_MODULE I think, if we're outside it'll be an
* MONO_RESOLUTION_SCOPE_ASSEMBLYREF and we'll need to check the
* name.*/
return FALSE;
}
static gboolean
class_has_wellknown_attribute (MonoClass *klass, const char *nspace, const char *name, gboolean in_corlib)
{
struct FoundAttrUD has_attr;
has_attr.nspace = nspace;
has_attr.name = name;
has_attr.in_corlib = in_corlib;
has_attr.has_attr = FALSE;
mono_class_metadata_foreach_custom_attr (klass, has_wellknown_attribute_func, &has_attr);
return has_attr.has_attr;
}
static gboolean
method_has_wellknown_attribute (MonoMethod *method, const char *nspace, const char *name, gboolean in_corlib)
{
struct FoundAttrUD has_attr;
has_attr.nspace = nspace;
has_attr.name = name;
has_attr.in_corlib = in_corlib;
has_attr.has_attr = FALSE;
mono_method_metadata_foreach_custom_attr (method, has_wellknown_attribute_func, &has_attr);
return has_attr.has_attr;
}
static gboolean
class_has_isbyreflike_attribute (MonoClass *klass)
{
return class_has_wellknown_attribute (klass, "System.Runtime.CompilerServices", "IsByRefLikeAttribute", TRUE);
}
gboolean
mono_class_setup_method_has_preserve_base_overrides_attribute (MonoMethod *method)
{
MonoImage *image = m_class_get_image (method->klass);
/* FIXME: implement well known attribute check for dynamic images */
if (image_is_dynamic (image))
return FALSE;
return method_has_wellknown_attribute (method, "System.Runtime.CompilerServices", "PreserveBaseOverridesAttribute", TRUE);
}
static gboolean
check_valid_generic_inst_arguments (MonoGenericInst *inst, MonoError *error)
{
for (int i = 0; i < inst->type_argc; i++) {
if (!mono_type_is_valid_generic_argument (inst->type_argv [i])) {
char *type_name = mono_type_full_name (inst->type_argv [i]);
mono_error_set_invalid_program (error, "generic type cannot be instantiated with type '%s'", type_name);
g_free (type_name);
return FALSE;
}
}
return TRUE;
}
/*
* Create the `MonoClass' for an instantiation of a generic type.
* We only do this if we actually need it.
* This will sometimes return a GTD due to checking the cached_class.
*/
MonoClass*
mono_class_create_generic_inst (MonoGenericClass *gclass)
{
MonoClass *klass, *gklass;
if (gclass->cached_class)
return gclass->cached_class;
klass = (MonoClass *)mono_mem_manager_alloc0 ((MonoMemoryManager*)gclass->owner, sizeof (MonoClassGenericInst));
gklass = gclass->container_class;
if (gklass->nested_in) {
/* The nested_in type should not be inflated since it's possible to produce a nested type with less generic arguments*/
klass->nested_in = gklass->nested_in;
}
klass->name = gklass->name;
klass->name_space = gklass->name_space;
klass->image = gklass->image;
klass->type_token = gklass->type_token;
klass->class_kind = MONO_CLASS_GINST;
//FIXME add setter
((MonoClassGenericInst*)klass)->generic_class = gclass;
klass->_byval_arg.type = MONO_TYPE_GENERICINST;
klass->this_arg.type = m_class_get_byval_arg (klass)->type;
klass->this_arg.data.generic_class = klass->_byval_arg.data.generic_class = gclass;
klass->this_arg.byref__ = TRUE;
klass->enumtype = gklass->enumtype;
klass->valuetype = gklass->valuetype;
if (gklass->image->assembly_name && !strcmp (gklass->image->assembly_name, "System.Numerics.Vectors") && !strcmp (gklass->name_space, "System.Numerics") && !strcmp (gklass->name, "Vector`1")) {
g_assert (gclass->context.class_inst);
g_assert (gclass->context.class_inst->type_argc > 0);
if (mono_type_is_primitive (gclass->context.class_inst->type_argv [0]))
klass->simd_type = 1;
}
if (mono_is_corlib_image (gklass->image) &&
(!strcmp (gklass->name, "Vector`1") || !strcmp (gklass->name, "Vector64`1") || !strcmp (gklass->name, "Vector128`1") || !strcmp (gklass->name, "Vector256`1"))) {
MonoType *etype = gclass->context.class_inst->type_argv [0];
if (mono_type_is_primitive (etype) && etype->type != MONO_TYPE_CHAR && etype->type != MONO_TYPE_BOOLEAN)
klass->simd_type = 1;
}
klass->is_array_special_interface = gklass->is_array_special_interface;
klass->cast_class = klass->element_class = klass;
if (m_class_is_valuetype (klass)) {
klass->is_byreflike = gklass->is_byreflike;
}
if (gclass->is_dynamic) {
/*
* We don't need to do any init workf with unbaked typebuilders. Generic instances created at this point will be later unregistered and/or fixed.
* This is to avoid work that would probably give wrong results as fields change as we build the TypeBuilder.
* See remove_instantiations_of_and_ensure_contents in reflection.c and its usage in reflection.c to understand the fixup stage of SRE banking.
*/
if (!gklass->wastypebuilder)
klass->inited = 1;
if (klass->enumtype) {
/*
* For enums, gklass->fields might not been set, but instance_size etc. is
* already set in mono_reflection_create_internal_class (). For non-enums,
* these will be computed normally in mono_class_layout_fields ().
*/
klass->instance_size = gklass->instance_size;
klass->sizes.class_size = gklass->sizes.class_size;
klass->size_inited = 1;
}
}
{
ERROR_DECL (error_inst);
if (!check_valid_generic_inst_arguments (gclass->context.class_inst, error_inst)) {
char *gklass_name = mono_type_get_full_name (gklass);
mono_class_set_type_load_failure (klass, "Could not instantiate %s due to %s", gklass_name, mono_error_get_message (error_inst));
g_free (gklass_name);
mono_error_cleanup (error_inst);
}
}
mono_loader_lock ();
if (gclass->cached_class) {
mono_loader_unlock ();
return gclass->cached_class;
}
if (record_gclass_instantiation > 0)
gclass_recorded_list = g_slist_append (gclass_recorded_list, klass);
if (mono_class_is_nullable (klass))
klass->cast_class = klass->element_class = mono_class_get_nullable_param_internal (klass);
MONO_PROFILER_RAISE (class_loading, (klass));
mono_generic_class_setup_parent (klass, gklass);
if (gclass->is_dynamic)
mono_class_setup_supertypes (klass);
mono_memory_barrier ();
gclass->cached_class = klass;
MONO_PROFILER_RAISE (class_loaded, (klass));
++class_ginst_count;
inflated_classes_size += sizeof (MonoClassGenericInst);
mono_loader_unlock ();
return klass;
}
/*
* For a composite class like uint32[], uint32*, set MonoClass:cast_class to the corresponding "intermediate type" (for
* arrays) or "verification type" (for pointers) in the sense of ECMA I.8.7.3. This will be used by
* mono_class_is_assignable_from.
*
* Assumes MonoClass:cast_class is already set (for example if it's an array of
* some enum) and adjusts it.
*/
static void
class_composite_fixup_cast_class (MonoClass *klass, gboolean for_ptr)
{
switch (m_class_get_byval_arg (m_class_get_cast_class (klass))->type) {
case MONO_TYPE_BOOLEAN:
if (!for_ptr)
break;
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_I1:
klass->cast_class = mono_defaults.byte_class;
break;
case MONO_TYPE_U2:
klass->cast_class = mono_defaults.int16_class;
break;
case MONO_TYPE_U4:
#if TARGET_SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
klass->cast_class = mono_defaults.int32_class;
break;
case MONO_TYPE_U8:
#if TARGET_SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
klass->cast_class = mono_defaults.int64_class;
break;
default:
break;
}
}
static gboolean
class_kind_may_contain_generic_instances (MonoTypeKind kind)
{
/* classes of type generic inst may contain generic arguments from other images,
* as well as arrays and pointers whose element types (recursively) may be a generic inst */
return (kind == MONO_CLASS_GINST || kind == MONO_CLASS_ARRAY || kind == MONO_CLASS_POINTER);
}
/**
* mono_class_create_bounded_array:
* \param element_class element class
* \param rank the dimension of the array class
* \param bounded whenever the array has non-zero bounds
* \returns A class object describing the array with element type \p element_type and
* dimension \p rank.
*/
MonoClass *
mono_class_create_bounded_array (MonoClass *eclass, guint32 rank, gboolean bounded)
{
MonoImage *image;
MonoClass *klass, *cached, *k;
MonoClass *parent = NULL;
GSList *list, *rootlist = NULL;
int nsize;
char *name;
MonoMemoryManager *mm;
if (rank > 1)
/* bounded only matters for one-dimensional arrays */
bounded = FALSE;
image = eclass->image;
// FIXME: Optimize this
mm = class_kind_may_contain_generic_instances ((MonoTypeKind)eclass->class_kind) ? mono_metadata_get_mem_manager_for_class (eclass) : NULL;
/* Check cache */
cached = NULL;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->szarray_cache)
mm->szarray_cache = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, NULL);
cached = (MonoClass *)g_hash_table_lookup (mm->szarray_cache, eclass);
mono_mem_manager_unlock (mm);
} else {
/*
* This case is very frequent not just during compilation because of calls
* from mono_class_from_mono_type_internal (), mono_array_new (),
* Array:CreateInstance (), etc, so use a separate cache + a separate lock.
*/
mono_os_mutex_lock (&image->szarray_cache_lock);
if (!image->szarray_cache)
image->szarray_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
cached = (MonoClass *)g_hash_table_lookup (image->szarray_cache, eclass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->array_cache)
mm->array_cache = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, NULL);
rootlist = (GSList *)g_hash_table_lookup (mm->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_mem_manager_unlock (mm);
} else {
mono_loader_lock ();
if (!image->array_cache)
image->array_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
rootlist = (GSList *)g_hash_table_lookup (image->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_loader_unlock ();
}
}
if (cached)
return cached;
parent = mono_defaults.array_class;
if (!parent->inited)
mono_class_init_internal (parent);
klass = mm ? (MonoClass *)mono_mem_manager_alloc0 (mm, sizeof (MonoClassArray)) : (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassArray));
klass->image = image;
klass->name_space = eclass->name_space;
klass->class_kind = MONO_CLASS_ARRAY;
nsize = strlen (eclass->name);
int maxrank = MIN (rank, 32);
name = (char *)g_malloc (nsize + 2 + maxrank + 1);
memcpy (name, eclass->name, nsize);
name [nsize] = '[';
if (maxrank > 1)
memset (name + nsize + 1, ',', maxrank - 1);
if (bounded)
name [nsize + maxrank] = '*';
name [nsize + maxrank + bounded] = ']';
name [nsize + maxrank + bounded + 1] = 0;
klass->name = mm ? mono_mem_manager_strdup (mm, name) : mono_image_strdup (image, name);
g_free (name);
klass->type_token = 0;
klass->parent = parent;
klass->instance_size = mono_class_instance_size (klass->parent);
klass->rank = rank;
klass->element_class = eclass;
if (m_class_get_byval_arg (eclass)->type == MONO_TYPE_TYPEDBYREF) {
/*Arrays of those two types are invalid.*/
ERROR_DECL (prepared_error);
mono_error_set_invalid_program (prepared_error, "Arrays of System.TypedReference types are invalid.");
mono_class_set_failure (klass, mono_error_box (prepared_error, klass->image));
mono_error_cleanup (prepared_error);
} else if (m_class_is_byreflike (eclass)) {
/* .NET Core throws a type load exception: "Could not create array type 'fullname[]'" */
char *full_name = mono_type_get_full_name (eclass);
mono_class_set_type_load_failure (klass, "Could not create array type '%s[]'", full_name);
g_free (full_name);
} else if (eclass->enumtype && !mono_class_enum_basetype_internal (eclass)) {
MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (eclass);
if (!ref_info_handle || eclass->wastypebuilder) {
g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
g_assert (ref_info_handle && !eclass->wastypebuilder);
}
/* element_size -1 is ok as this is not an instantitable type*/
klass->sizes.element_size = -1;
} else
klass->sizes.element_size = -1;
mono_class_setup_supertypes (klass);
if (mono_class_is_ginst (eclass))
mono_class_init_internal (eclass);
if (!eclass->size_inited)
mono_class_setup_fields (eclass);
mono_class_set_type_load_failure_causedby_class (klass, eclass, "Could not load array element type");
/*FIXME we fail the array type, but we have to let other fields be set.*/
klass->has_references = MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (eclass)) || m_class_has_references (eclass)? TRUE: FALSE;
if (eclass->enumtype)
klass->cast_class = eclass->element_class;
else
klass->cast_class = eclass;
class_composite_fixup_cast_class (klass, FALSE);
if ((rank > 1) || bounded) {
MonoArrayType *at = mm ? (MonoArrayType *)mono_mem_manager_alloc0 (mm, sizeof (MonoArrayType)) : (MonoArrayType *)mono_image_alloc0 (image, sizeof (MonoArrayType));
klass->_byval_arg.type = MONO_TYPE_ARRAY;
klass->_byval_arg.data.array = at;
at->eklass = eclass;
at->rank = rank;
/* FIXME: complete.... */
} else {
klass->_byval_arg.type = MONO_TYPE_SZARRAY;
klass->_byval_arg.data.klass = eclass;
}
klass->this_arg = klass->_byval_arg;
klass->this_arg.byref__ = 1;
if (rank > 32) {
ERROR_DECL (prepared_error);
name = mono_type_get_full_name (klass);
mono_error_set_type_load_class (prepared_error, klass, "%s has too many dimensions.", name);
mono_class_set_failure (klass, mono_error_box (prepared_error, klass->image));
mono_error_cleanup (prepared_error);
g_free (name);
}
mono_loader_lock ();
/* Check cache again */
cached = NULL;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
cached = (MonoClass *)g_hash_table_lookup (mm->szarray_cache, eclass);
mono_mem_manager_unlock (mm);
} else {
mono_os_mutex_lock (&image->szarray_cache_lock);
cached = (MonoClass *)g_hash_table_lookup (image->szarray_cache, eclass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
rootlist = (GSList *)g_hash_table_lookup (mm->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
mono_mem_manager_unlock (mm);
} else {
rootlist = (GSList *)g_hash_table_lookup (image->array_cache, eclass);
for (list = rootlist; list; list = list->next) {
k = (MonoClass *)list->data;
if ((m_class_get_rank (k) == rank) && (m_class_get_byval_arg (k)->type == (((rank > 1) || bounded) ? MONO_TYPE_ARRAY : MONO_TYPE_SZARRAY))) {
cached = k;
break;
}
}
}
}
if (cached) {
mono_loader_unlock ();
return cached;
}
MONO_PROFILER_RAISE (class_loading, (klass));
UnlockedAdd (&classes_size, sizeof (MonoClassArray));
++class_array_count;
if (rank == 1 && !bounded) {
if (mm) {
mono_mem_manager_lock (mm);
g_hash_table_insert (mm->szarray_cache, eclass, klass);
mono_mem_manager_unlock (mm);
} else {
mono_os_mutex_lock (&image->szarray_cache_lock);
g_hash_table_insert (image->szarray_cache, eclass, klass);
mono_os_mutex_unlock (&image->szarray_cache_lock);
}
} else {
if (mm) {
mono_mem_manager_lock (mm);
list = g_slist_append (rootlist, klass);
g_hash_table_insert (mm->array_cache, eclass, list);
mono_mem_manager_unlock (mm);
} else {
list = g_slist_append (rootlist, klass);
g_hash_table_insert (image->array_cache, eclass, list);
}
}
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
}
/**
* mono_class_create_array:
* \param element_class element class
* \param rank the dimension of the array class
* \returns A class object describing the array with element type \p element_type and
* dimension \p rank.
*/
MonoClass *
mono_class_create_array (MonoClass *eclass, guint32 rank)
{
return mono_class_create_bounded_array (eclass, rank, FALSE);
}
// This is called by mono_class_create_generic_parameter when a new class must be created.
static MonoClass*
make_generic_param_class (MonoGenericParam *param)
{
MonoClass *klass, **ptr;
int count, pos, i, min_align;
MonoGenericParamInfo *pinfo = mono_generic_param_info (param);
MonoGenericContainer *container = mono_generic_param_owner (param);
g_assert_checked (container);
MonoImage *image = mono_get_image_for_generic_param (param);
gboolean is_mvar = container->is_method;
gboolean is_anonymous = container->is_anonymous;
klass = (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassGenericParam));
klass->class_kind = MONO_CLASS_GPARAM;
UnlockedAdd (&classes_size, sizeof (MonoClassGenericParam));
UnlockedIncrement (&class_gparam_count);
if (!is_anonymous) {
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name , pinfo->name );
} else {
int n = mono_generic_param_num (param);
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->name , mono_make_generic_name_string (image, n) );
}
if (is_anonymous) {
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , "" );
} else if (is_mvar) {
MonoMethod *omethod = container->owner.method;
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , (omethod && omethod->klass) ? omethod->klass->name_space : "" );
} else {
MonoClass *oklass = container->owner.klass;
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->name_space , oklass ? oklass->name_space : "" );
}
MONO_PROFILER_RAISE (class_loading, (klass));
// Count non-NULL items in pinfo->constraints
count = 0;
if (!is_anonymous)
for (ptr = pinfo->constraints; ptr && *ptr; ptr++, count++)
;
pos = 0;
if ((count > 0) && !MONO_CLASS_IS_INTERFACE_INTERNAL (pinfo->constraints [0])) {
CHECKED_METADATA_WRITE_PTR ( klass->parent , pinfo->constraints [0] );
pos++;
} else if (pinfo && pinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) {
CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_class_load_from_name (mono_defaults.corlib, "System", "ValueType") );
} else {
CHECKED_METADATA_WRITE_PTR ( klass->parent , mono_defaults.object_class );
}
if (count - pos > 0) {
klass->interface_count = count - pos;
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->interfaces , (MonoClass **)mono_image_alloc0 (image, sizeof (MonoClass *) * (count - pos)) );
klass->interfaces_inited = TRUE;
for (i = pos; i < count; i++)
CHECKED_METADATA_WRITE_PTR ( klass->interfaces [i - pos] , pinfo->constraints [i] );
}
CHECKED_METADATA_WRITE_PTR_EXEMPT ( klass->image , image );
klass->inited = TRUE;
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->cast_class , klass );
CHECKED_METADATA_WRITE_PTR_LOCAL ( klass->element_class , klass );
MonoTypeEnum t = is_mvar ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
klass->_byval_arg.type = t;
klass->this_arg.type = t;
CHECKED_METADATA_WRITE_PTR ( klass->this_arg.data.generic_param , param );
CHECKED_METADATA_WRITE_PTR ( klass->_byval_arg.data.generic_param , param );
klass->this_arg.byref__ = TRUE;
/* We don't use type_token for VAR since only classes can use it (not arrays, pointer, VARs, etc) */
klass->sizes.generic_param_token = !is_anonymous ? pinfo->token : 0;
if (param->gshared_constraint) {
MonoClass *constraint_class = mono_class_from_mono_type_internal (param->gshared_constraint);
mono_class_init_sizes (constraint_class);
klass->has_references = m_class_has_references (constraint_class);
}
/*
* This makes sure the the value size of this class is equal to the size of the types the gparam is
* constrained to, the JIT depends on this.
*/
klass->instance_size = MONO_ABI_SIZEOF (MonoObject) + mono_type_size (m_class_get_byval_arg (klass), &min_align);
klass->min_align = min_align;
mono_memory_barrier ();
klass->size_inited = 1;
mono_class_setup_supertypes (klass);
if (count - pos > 0) {
mono_class_setup_vtable (klass->parent);
if (mono_class_has_failure (klass->parent))
mono_class_set_type_load_failure (klass, "Failed to setup parent interfaces");
else
mono_class_setup_interface_offsets_internal (klass, klass->parent->vtable_size, TRUE);
}
return klass;
}
/*
* LOCKING: Acquires the image lock (@image).
*/
MonoClass *
mono_class_create_generic_parameter (MonoGenericParam *param)
{
MonoImage *image = mono_get_image_for_generic_param (param);
MonoGenericParamInfo *pinfo = mono_generic_param_info (param);
MonoClass *klass, *klass2;
// If a klass already exists for this object and is cached, return it.
klass = pinfo->pklass;
if (klass)
return klass;
// Create a new klass
klass = make_generic_param_class (param);
// Now we need to cache the klass we created.
// But since we wait to grab the lock until after creating the klass, we need to check to make sure
// another thread did not get in and cache a klass ahead of us. In that case, return their klass
// and allow our newly-created klass object to just leak.
mono_memory_barrier ();
mono_image_lock (image);
// Here "klass2" refers to the klass potentially created by the other thread.
klass2 = pinfo->pklass;
if (klass2) {
klass = klass2;
} else {
pinfo->pklass = klass;
}
mono_image_unlock (image);
/* FIXME: Should this go inside 'make_generic_param_klass'? */
if (klass2)
MONO_PROFILER_RAISE (class_failed, (klass2));
else
MONO_PROFILER_RAISE (class_loaded, (klass));
return klass;
}
/**
* mono_class_create_ptr:
*/
MonoClass *
mono_class_create_ptr (MonoType *type)
{
MonoClass *result;
MonoClass *el_class;
MonoImage *image;
char *name;
MonoMemoryManager *mm;
el_class = mono_class_from_mono_type_internal (type);
image = el_class->image;
// FIXME: Optimize this
mm = class_kind_may_contain_generic_instances ((MonoTypeKind)el_class->class_kind) ? mono_metadata_get_mem_manager_for_class (el_class) : NULL;
if (mm) {
mono_mem_manager_lock (mm);
if (!mm->ptr_cache)
mm->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
result = (MonoClass *)g_hash_table_lookup (mm->ptr_cache, el_class);
mono_mem_manager_unlock (mm);
if (result)
return result;
} else {
mono_image_lock (image);
if (image->ptr_cache) {
if ((result = (MonoClass *)g_hash_table_lookup (image->ptr_cache, el_class))) {
mono_image_unlock (image);
return result;
}
}
mono_image_unlock (image);
}
result = mm ? (MonoClass *)mono_mem_manager_alloc0 (mm, sizeof (MonoClassPointer)) : (MonoClass *)mono_image_alloc0 (image, sizeof (MonoClassPointer));
UnlockedAdd (&classes_size, sizeof (MonoClassPointer));
++class_pointer_count;
result->parent = NULL; /* no parent for PTR types */
result->name_space = el_class->name_space;
name = g_strdup_printf ("%s*", el_class->name);
result->name = mm ? mono_mem_manager_strdup (mm, name) : mono_image_strdup (image, name);
result->class_kind = MONO_CLASS_POINTER;
g_free (name);
MONO_PROFILER_RAISE (class_loading, (result));
result->image = el_class->image;
result->inited = TRUE;
result->instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
result->min_align = sizeof (gpointer);
result->element_class = el_class;
result->blittable = TRUE;
if (el_class->enumtype)
result->cast_class = el_class->element_class;
else
result->cast_class = el_class;
class_composite_fixup_cast_class (result, TRUE);
result->this_arg.type = result->_byval_arg.type = MONO_TYPE_PTR;
result->this_arg.data.type = result->_byval_arg.data.type = m_class_get_byval_arg (el_class);
result->this_arg.byref__ = TRUE;
mono_class_setup_supertypes (result);
if (mm) {
mono_mem_manager_lock (mm);
MonoClass *result2;
result2 = (MonoClass *)g_hash_table_lookup (mm->ptr_cache, el_class);
if (!result2)
g_hash_table_insert (mm->ptr_cache, el_class, result);
mono_mem_manager_unlock (mm);
if (result2) {
MONO_PROFILER_RAISE (class_failed, (result));
return result2;
}
} else {
mono_image_lock (image);
if (image->ptr_cache) {
MonoClass *result2;
if ((result2 = (MonoClass *)g_hash_table_lookup (image->ptr_cache, el_class))) {
mono_image_unlock (image);
MONO_PROFILER_RAISE (class_failed, (result));
return result2;
}
} else {
image->ptr_cache = g_hash_table_new (mono_aligned_addr_hash, NULL);
}
g_hash_table_insert (image->ptr_cache, el_class, result);
mono_image_unlock (image);
}
MONO_PROFILER_RAISE (class_loaded, (result));
return result;
}
MonoClass *
mono_class_create_fnptr (MonoMethodSignature *sig)
{
MonoClass *result, *cached;
static GHashTable *ptr_hash = NULL;
/* FIXME: These should be allocate from a mempool as well, but which one ? */
mono_loader_lock ();
if (!ptr_hash)
ptr_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
cached = (MonoClass *)g_hash_table_lookup (ptr_hash, sig);
mono_loader_unlock ();
if (cached)
return cached;
result = g_new0 (MonoClass, 1);
result->parent = NULL; /* no parent for PTR types */
result->name_space = "System";
result->name = "MonoFNPtrFakeClass";
result->class_kind = MONO_CLASS_POINTER;
result->image = mono_defaults.corlib; /* need to fix... */
result->instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
result->min_align = sizeof (gpointer);
result->cast_class = result->element_class = result;
result->this_arg.type = result->_byval_arg.type = MONO_TYPE_FNPTR;
result->this_arg.data.method = result->_byval_arg.data.method = sig;
result->this_arg.byref__ = TRUE;
result->blittable = TRUE;
result->inited = TRUE;
mono_class_setup_supertypes (result);
mono_loader_lock ();
cached = (MonoClass *)g_hash_table_lookup (ptr_hash, sig);
if (cached) {
g_free (result);
mono_loader_unlock ();
return cached;
}
MONO_PROFILER_RAISE (class_loading, (result));
UnlockedAdd (&classes_size, sizeof (MonoClassPointer));
++class_pointer_count;
g_hash_table_insert (ptr_hash, sig, result);
mono_loader_unlock ();
MONO_PROFILER_RAISE (class_loaded, (result));
return result;
}
static gboolean
method_is_reabstracted (guint16 flags)
{
if ((flags & METHOD_ATTRIBUTE_ABSTRACT && flags & METHOD_ATTRIBUTE_FINAL))
return TRUE;
return FALSE;
}
/**
* mono_class_setup_count_virtual_methods:
*
* Return the number of virtual methods.
* Even for interfaces we can't simply return the number of methods as all CLR types are allowed to have static methods.
* Return -1 on failure.
* FIXME It would be nice if this information could be cached somewhere.
*/
int
mono_class_setup_count_virtual_methods (MonoClass *klass)
{
int i, mcount, vcount = 0;
guint32 flags;
klass = mono_class_get_generic_type_definition (klass); /*We can find this information by looking at the GTD*/
if (klass->methods || !MONO_CLASS_HAS_STATIC_METADATA (klass)) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return -1;
mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
flags = klass->methods [i]->flags;
if ((flags & METHOD_ATTRIBUTE_VIRTUAL)) {
if (method_is_reabstracted (flags))
continue;
++vcount;
}
}
} else {
int first_idx = mono_class_get_first_method_idx (klass);
mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
flags = mono_metadata_decode_table_row_col (klass->image, MONO_TABLE_METHOD, first_idx + i, MONO_METHOD_FLAGS);
if ((flags & METHOD_ATTRIBUTE_VIRTUAL)) {
if (method_is_reabstracted (flags))
continue;
++vcount;
}
}
}
return vcount;
}
#ifdef COMPRESSED_INTERFACE_BITMAP
/*
* Compressed interface bitmap design.
*
* Interface bitmaps take a large amount of memory, because their size is
* linear with the maximum interface id assigned in the process (each interface
* is assigned a unique id as it is loaded). The number of interface classes
* is high because of the many implicit interfaces implemented by arrays (we'll
* need to lazy-load them in the future).
* Most classes implement a very small number of interfaces, so the bitmap is
* sparse. This bitmap needs to be checked by interface casts, so access to the
* needed bit must be fast and doable with few jit instructions.
*
* The current compression format is as follows:
* *) it is a sequence of one or more two-byte elements
* *) the first byte in the element is the count of empty bitmap bytes
* at the current bitmap position
* *) the second byte in the element is an actual bitmap byte at the current
* bitmap position
*
* As an example, the following compressed bitmap bytes:
* 0x07 0x01 0x00 0x7
* correspond to the following bitmap:
* 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
*
* Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
* bitmap byte for non-sparse sequences. In practice the interface bitmaps created
* during a gmcs bootstrap are reduced to less tha 5% of the original size.
*/
/**
* mono_compress_bitmap:
* \param dest destination buffer
* \param bitmap bitmap buffer
* \param size size of \p bitmap in bytes
*
* This is a mono internal function.
* The \p bitmap data is compressed into a format that is small but
* still searchable in few instructions by the JIT and runtime.
* The compressed data is stored in the buffer pointed to by the
* \p dest array. Passing a NULL value for \p dest allows to just compute
* the size of the buffer.
* This compression algorithm assumes the bits set in the bitmap are
* few and far between, like in interface bitmaps.
* \returns The size of the compressed bitmap in bytes.
*/
int
mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
{
int numz = 0;
int res = 0;
const uint8_t *end = bitmap + size;
while (bitmap < end) {
if (*bitmap || numz == 255) {
if (dest) {
*dest++ = numz;
*dest++ = *bitmap;
}
res += 2;
numz = 0;
bitmap++;
continue;
}
bitmap++;
numz++;
}
if (numz) {
res += 2;
if (dest) {
*dest++ = numz;
*dest++ = 0;
}
}
return res;
}
/**
* mono_class_interface_match:
* \param bitmap a compressed bitmap buffer
* \param id the index to check in the bitmap
*
* This is a mono internal function.
* Checks if a bit is set in a compressed interface bitmap. \p id must
* be already checked for being smaller than the maximum id encoded in the
* bitmap.
*
* \returns A non-zero value if bit \p id is set in the bitmap \p bitmap,
* FALSE otherwise.
*/
int
mono_class_interface_match (const uint8_t *bitmap, int id)
{
while (TRUE) {
id -= bitmap [0] * 8;
if (id < 8) {
if (id < 0)
return 0;
return bitmap [1] & (1 << id);
}
bitmap += 2;
id -= 8;
}
}
#endif
static char*
concat_two_strings_with_zero (MonoImage *image, const char *s1, const char *s2)
{
int null_length = strlen ("(null)");
int len = (s1 ? strlen (s1) : null_length) + (s2 ? strlen (s2) : null_length) + 2;
char *s = (char *)mono_image_alloc (image, len);
int result;
result = g_snprintf (s, len, "%s%c%s", s1 ? s1 : "(null)", '\0', s2 ? s2 : "(null)");
g_assert (result == len - 1);
return s;
}
static void
init_sizes_with_info (MonoClass *klass, MonoCachedClassInfo *cached_info)
{
if (cached_info) {
mono_loader_lock ();
klass->instance_size = cached_info->instance_size;
klass->sizes.class_size = cached_info->class_size;
klass->packing_size = cached_info->packing_size;
klass->min_align = cached_info->min_align;
klass->blittable = cached_info->blittable;
klass->has_references = cached_info->has_references;
klass->has_static_refs = cached_info->has_static_refs;
klass->no_special_static_fields = cached_info->no_special_static_fields;
klass->has_weak_fields = cached_info->has_weak_fields;
mono_loader_unlock ();
}
else {
if (!klass->size_inited)
mono_class_setup_fields (klass);
}
}
/*
* mono_class_init_sizes:
*
* Initializes the size related fields of @klass without loading all field data if possible.
* Sets the following fields in @klass:
* - instance_size
* - sizes.class_size
* - packing_size
* - min_align
* - blittable
* - has_references
* - has_static_refs
* - size_inited
* Can fail the class.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_init_sizes (MonoClass *klass)
{
MonoCachedClassInfo cached_info;
gboolean has_cached_info;
if (klass->size_inited)
return;
has_cached_info = mono_class_get_cached_class_info (klass, &cached_info);
init_sizes_with_info (klass, has_cached_info ? &cached_info : NULL);
}
static gboolean
class_has_references (MonoClass *klass)
{
mono_class_init_sizes (klass);
/*
* has_references is not set if this is called recursively, but this is not a problem since this is only used
* during field layout, and instance fields are initialized before static fields, and instance fields can't
* embed themselves.
*/
return klass->has_references;
}
static gboolean
type_has_references (MonoClass *klass, MonoType *ftype)
{
if (MONO_TYPE_IS_REFERENCE (ftype) || IS_GC_REFERENCE (klass, ftype) || ((MONO_TYPE_ISSTRUCT (ftype) && class_has_references (mono_class_from_mono_type_internal (ftype)))))
return TRUE;
if (!m_type_is_byref (ftype) && (ftype->type == MONO_TYPE_VAR || ftype->type == MONO_TYPE_MVAR)) {
MonoGenericParam *gparam = ftype->data.generic_param;
if (gparam->gshared_constraint)
return class_has_references (mono_class_from_mono_type_internal (gparam->gshared_constraint));
}
return FALSE;
}
static gboolean
class_has_ref_fields (MonoClass *klass)
{
/*
* has_ref_fields is not set if this is called recursively, but this is not a problem since this is only used
* during field layout, and instance fields are initialized before static fields, and instance fields can't
* embed themselves.
*/
return klass->has_ref_fields;
}
static gboolean
class_is_byreference (MonoClass* klass)
{
const char* klass_name_space = m_class_get_name_space (klass);
const char* klass_name = m_class_get_name (klass);
MonoImage* klass_image = m_class_get_image (klass);
gboolean in_corlib = klass_image == mono_defaults.corlib;
if (in_corlib &&
!strcmp (klass_name_space, "System") &&
!strcmp (klass_name, "ByReference`1")) {
return TRUE;
}
return FALSE;
}
static gboolean
type_has_ref_fields (MonoType *ftype)
{
if (m_type_is_byref (ftype) || (MONO_TYPE_ISSTRUCT (ftype) && class_has_ref_fields (mono_class_from_mono_type_internal (ftype))))
return TRUE;
/* Check for the ByReference`1 type */
if (MONO_TYPE_ISSTRUCT (ftype)) {
MonoClass* klass = mono_class_from_mono_type_internal (ftype);
return class_is_byreference (klass);
}
return FALSE;
}
/**
* mono_class_is_gparam_with_nonblittable_parent:
* \param klass a generic parameter
*
* \returns TRUE if \p klass is definitely not blittable.
*
* A parameter is definitely not blittable if it has the IL 'reference'
* constraint, or if it has a class specified as a parent. If it has an IL
* 'valuetype' constraint or no constraint at all or only interfaces as
* constraints, we return FALSE because the parameter may be instantiated both
* with blittable and non-blittable types.
*
* If the paramter is a generic sharing parameter, we look at its gshared_constraint->blittable bit.
*/
static gboolean
mono_class_is_gparam_with_nonblittable_parent (MonoClass *klass)
{
MonoType *type = m_class_get_byval_arg (klass);
g_assert (mono_type_is_generic_parameter (type));
MonoGenericParam *gparam = type->data.generic_param;
if ((mono_generic_param_info (gparam)->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) != 0)
return TRUE;
if ((mono_generic_param_info (gparam)->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) != 0)
return FALSE;
if (gparam->gshared_constraint) {
MonoClass *constraint_class = mono_class_from_mono_type_internal (gparam->gshared_constraint);
return !m_class_is_blittable (constraint_class);
}
if (mono_generic_param_owner (gparam)->is_anonymous)
return FALSE;
/* We could have: T : U, U : Base. So have to follow the constraints. */
MonoClass *parent_class = mono_generic_param_get_base_type (klass);
g_assert (!MONO_CLASS_IS_INTERFACE_INTERNAL (parent_class));
/* Parent can only be: System.Object, System.ValueType or some specific base class.
*
* If the parent_class is ValueType, the valuetype constraint would be set, above, so
* we wouldn't get here.
*
* If there was a reference constraint, the parent_class would be System.Object,
* but we would have returned early above.
*
* So if we get here, there is either no base class constraint at all,
* in which case parent_class would be set to System.Object, or there is none at all.
*/
return parent_class != mono_defaults.object_class;
}
/**
* Checks if there are any overlapping object and non-object fields.
* The alignment of object reference fields is checked elswhere and this function assumes
* that all references are aligned correctly.
*
* \param layout_check A buffer to check which bytes hold object references or values
* \param klass Checked struct
* \param field_offsets Offsets of the klass' fields relative to the start of layout_check
* \param field_count Count of klass fields
* \param invalid_field_offset When the layout is invalid it will be set to the offset of the field which is invalid
*
* \return True if the layout of the struct is valid, otherwise false.
*/
static gboolean
validate_struct_fields_overlaps (guint8 *layout_check, int layout_size, MonoClass *klass, const int *field_offsets, const int field_count, int *invalid_field_offset)
{
MonoClassField *field;
MonoType *ftype;
int field_offset;
for (int i = 0; i < field_count && !mono_class_has_failure (klass); i++) {
// using mono_class_get_fields_internal isn't appropriate here because it will
// try to call mono_class_setup_fields which is what we're doing already
field = &m_class_get_fields (klass) [i];
field_offset = field_offsets [i];
if (!field)
continue;
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (mono_type_is_struct (ftype)) {
// recursively check the layout of the embedded struct
MonoClass *embedded_class = mono_class_from_mono_type_internal (ftype);
mono_class_setup_fields (embedded_class);
const int embedded_fields_count = mono_class_get_field_count (embedded_class);
int *embedded_offsets = g_new0 (int, embedded_fields_count);
for (int j = 0; j < embedded_fields_count; ++j) {
embedded_offsets [j] = field_offset + m_class_get_fields (embedded_class) [j].offset - MONO_ABI_SIZEOF (MonoObject);
}
gboolean is_valid = validate_struct_fields_overlaps (layout_check, layout_size, embedded_class, embedded_offsets, embedded_fields_count, invalid_field_offset);
g_free (embedded_offsets);
if (!is_valid) {
// overwrite whatever was in the invalid_field_offset with the offset of the currently checked field
// we want to return the outer most invalid field
*invalid_field_offset = field_offset;
return FALSE;
}
} else {
int align = 0;
int size = mono_type_size (field->type, &align);
guint8 type = type_has_references (klass, ftype) ? 1 : (m_type_is_byref (ftype) || class_is_byreference (klass)) ? 2 : 3;
// Mark the bytes used by this fields type based on if it contains references or not.
// Make sure there are no overlaps between object and non-object fields.
for (int j = 0; j < size; j++) {
int checked_byte = field_offset + j;
g_assert(checked_byte < layout_size);
if (layout_check [checked_byte] != 0 && layout_check [checked_byte] != type) {
*invalid_field_offset = field_offset;
return FALSE;
}
layout_check [checked_byte] = type;
}
}
}
return TRUE;
}
/*
* mono_class_layout_fields:
* @class: a class
* @base_instance_size: base instance size
* @packing_size:
*
* This contains the common code for computing the layout of classes and sizes.
* This should only be called from mono_class_setup_fields () and
* typebuilder_setup_fields ().
*
* LOCKING: Acquires the loader lock
*/
void
mono_class_layout_fields (MonoClass *klass, int base_instance_size, int packing_size, int explicit_size, gboolean sre)
{
int i;
const int top = mono_class_get_field_count (klass);
guint32 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
guint32 pass, passes, real_size;
gboolean gc_aware_layout = FALSE;
gboolean has_static_fields = FALSE;
gboolean has_references = FALSE;
gboolean has_ref_fields = FALSE;
gboolean has_static_refs = FALSE;
MonoClassField *field;
gboolean blittable;
gboolean any_field_has_auto_layout;
int instance_size = base_instance_size;
int element_size = -1;
int class_size, min_align;
int *field_offsets;
gboolean *fields_has_references;
/*
* We want to avoid doing complicated work inside locks, so we compute all the required
* information and write it to @klass inside a lock.
*/
if (klass->fields_inited)
return;
if ((packing_size & 0xffffff00) != 0) {
mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
return;
}
if (klass->parent) {
min_align = klass->parent->min_align;
/* we use | since it may have been set already */
has_references = klass->has_references | klass->parent->has_references;
has_ref_fields = klass->has_ref_fields | klass->parent->has_ref_fields;
} else {
min_align = 1;
}
/* We can't really enable 16 bytes alignment until the GC supports it.
The whole layout/instance size code must be reviewed because we do alignment calculation in terms of the
boxed instance, which leads to unexplainable holes at the beginning of an object embedding a simd type.
Bug #506144 is an example of this issue.
if (klass->simd_type)
min_align = 16;
*/
/* Respect the specified packing size at least to the extent necessary to align double variables.
* This should avoid any GC problems, and will allow packing_size to be respected to support
* CreateSpan<T>
*/
min_align = MIN (MONO_ABI_ALIGNOF (double), MAX (min_align, packing_size));
/*
* When we do generic sharing we need to have layout
* information for open generic classes (either with a generic
* context containing type variables or with a generic
* container), so we don't return in that case anymore.
*/
if (klass->enumtype) {
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
klass->cast_class = klass->element_class = mono_class_from_mono_type_internal (field->type);
break;
}
}
if (!mono_class_enum_basetype_internal (klass)) {
mono_class_set_type_load_failure (klass, "The enumeration's base type is invalid.");
return;
}
}
/*
* Enable GC aware auto layout: in this mode, reference
* fields are grouped together inside objects, increasing collector
* performance.
* Requires that all classes whose layout is known to native code be annotated
* with [StructLayout (LayoutKind.Sequential)]
* Value types have gc_aware_layout disabled by default, as per
* what the default is for other runtimes.
*/
/* corlib is missing [StructLayout] directives in many places */
if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
if (!klass->valuetype)
gc_aware_layout = TRUE;
}
/* Compute klass->blittable and klass->any_field_has_auto_layout */
blittable = TRUE;
any_field_has_auto_layout = FALSE;
if (klass->parent) {
blittable = klass->parent->blittable;
any_field_has_auto_layout = klass->parent->any_field_has_auto_layout;
}
if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT && !(mono_is_corlib_image (klass->image) && !strcmp (klass->name_space, "System") && !strcmp (klass->name, "ValueType")) && top) {
blittable = FALSE;
any_field_has_auto_layout = TRUE; // If a type is auto-layout, treat it as having an auto-layout field in its layout.
}
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
if (blittable) {
if (m_type_is_byref (field->type) || MONO_TYPE_IS_REFERENCE (field->type)) {
blittable = FALSE;
} else if (mono_type_is_generic_parameter (field->type) &&
mono_class_is_gparam_with_nonblittable_parent (mono_class_from_mono_type_internal (field->type))) {
blittable = FALSE;
} else {
MonoClass *field_class = mono_class_from_mono_type_internal (field->type);
if (field_class) {
mono_class_setup_fields (field_class);
if (mono_class_has_failure (field_class)) {
ERROR_DECL (field_error);
mono_error_set_for_class_failure (field_error, field_class);
mono_class_set_type_load_failure (klass, "Could not set up field '%s' due to: %s", field->name, mono_error_get_message (field_error));
mono_error_cleanup (field_error);
break;
}
}
if (!field_class || !field_class->blittable)
blittable = FALSE;
}
}
if (!any_field_has_auto_layout && field->type->type == MONO_TYPE_VALUETYPE && m_class_any_field_has_auto_layout (mono_class_from_mono_type_internal (field->type)))
any_field_has_auto_layout = TRUE;
}
if (klass->enumtype) {
blittable = klass->element_class->blittable;
any_field_has_auto_layout = klass->element_class->any_field_has_auto_layout;
}
if (mono_class_has_failure (klass))
return;
if (klass == mono_defaults.string_class)
blittable = FALSE;
/* Compute klass->has_references and klass->has_ref_fields */
/*
* Process non-static fields first, since static fields might recursively
* refer to the class itself.
*/
for (i = 0; i < top; i++) {
MonoType *ftype;
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype))
has_references = TRUE;
if (type_has_ref_fields (ftype))
has_ref_fields = TRUE;
}
}
/*
* Compute field layout and total size (not considering static fields)
*/
field_offsets = g_new0 (int, top);
fields_has_references = g_new0 (gboolean, top);
int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0;
switch (layout) {
case TYPE_ATTRIBUTE_AUTO_LAYOUT:
case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
if (gc_aware_layout)
passes = 2;
else
passes = 1;
if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT)
passes = 1;
if (klass->parent) {
mono_class_setup_fields (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Cannot initialize parent class"))
return;
real_size = klass->parent->instance_size;
} else {
real_size = MONO_ABI_SIZEOF (MonoObject);
}
for (pass = 0; pass < passes; ++pass) {
for (i = 0; i < top; i++){
gint32 align;
guint32 size;
MonoType *ftype;
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (gc_aware_layout) {
fields_has_references [i] = type_has_references (klass, ftype);
if (fields_has_references [i]) {
if (pass == 1)
continue;
} else {
if (pass == 0)
continue;
}
}
if ((top == 1) && (instance_size == MONO_ABI_SIZEOF (MonoObject)) &&
(strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
/* This field is a hack inserted by MCS to empty structures */
continue;
}
size = mono_type_size (field->type, &align);
/* FIXME (LAMESPEC): should we also change the min alignment according to pack? */
align = packing_size ? MIN (packing_size, align): align;
/* if the field has managed references, we need to force-align it
* see bug #77788
*/
if (type_has_references (klass, ftype))
align = MAX (align, TARGET_SIZEOF_VOID_P);
min_align = MAX (align, min_align);
field_offsets [i] = real_size;
if (align) {
field_offsets [i] += align - 1;
field_offsets [i] &= ~(align - 1);
}
/*TypeBuilders produce all sort of weird things*/
g_assert (image_is_dynamic (klass->image) || field_offsets [i] > 0);
real_size = field_offsets [i] + size;
}
instance_size = MAX (real_size, instance_size);
if (instance_size & (min_align - 1)) {
instance_size += min_align - 1;
instance_size &= ~(min_align - 1);
}
}
break;
case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT: {
real_size = 0;
for (i = 0; i < top; i++) {
gint32 align;
guint32 size;
MonoType *ftype;
field = &klass->fields [i];
/*
* There must be info about all the fields in a type if it
* uses explicit layout.
*/
if (mono_field_is_deleted (field))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
size = mono_type_size (field->type, &align);
align = packing_size ? MIN (packing_size, align): align;
min_align = MAX (align, min_align);
if (sre) {
/* Already set by typebuilder_setup_fields () */
field_offsets [i] = field->offset + MONO_ABI_SIZEOF (MonoObject);
} else {
int idx = first_field_idx + i;
guint32 offset;
mono_metadata_field_info (klass->image, idx, &offset, NULL, NULL);
field_offsets [i] = offset + MONO_ABI_SIZEOF (MonoObject);
}
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype) || m_type_is_byref (ftype)) {
if (field_offsets [i] % TARGET_SIZEOF_VOID_P) {
mono_class_set_type_load_failure (klass, "Reference typed field '%s' has explicit offset that is not pointer-size aligned.", field->name);
}
}
/*
* Calc max size.
*/
real_size = MAX (real_size, size + field_offsets [i]);
}
/* check for incorrectly aligned or overlapped by a non-object field */
guint8 *layout_check;
if (has_references || has_ref_fields) {
layout_check = g_new0 (guint8, real_size);
int invalid_field_offset;
if (!validate_struct_fields_overlaps (layout_check, real_size, klass, field_offsets, top, &invalid_field_offset)) {
mono_class_set_type_load_failure (klass, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, invalid_field_offset);
}
g_free (layout_check);
}
instance_size = MAX (real_size, instance_size);
if (!((layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) && explicit_size)) {
if (instance_size & (min_align - 1)) {
instance_size += min_align - 1;
instance_size &= ~(min_align - 1);
}
}
break;
}
}
if (layout != TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
/*
* This leads to all kinds of problems with nested structs, so only
* enable it when a MONO_DEBUG property is set.
*
* For small structs, set min_align to at least the struct size to improve
* performance, and since the JIT memset/memcpy code assumes this and generates
* unaligned accesses otherwise. See #78990 for a testcase.
*/
if (mono_align_small_structs && top) {
if (instance_size <= MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer))
min_align = MAX (min_align, instance_size - MONO_ABI_SIZEOF (MonoObject));
}
}
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_VAR || klass_byval_arg->type == MONO_TYPE_MVAR)
instance_size = MONO_ABI_SIZEOF (MonoObject) + mono_type_size (klass_byval_arg, &min_align);
else if (klass_byval_arg->type == MONO_TYPE_PTR)
instance_size = MONO_ABI_SIZEOF (MonoObject) + MONO_ABI_SIZEOF (gpointer);
if (klass_byval_arg->type == MONO_TYPE_SZARRAY || klass_byval_arg->type == MONO_TYPE_ARRAY)
element_size = mono_class_array_element_size (klass->element_class);
/* Publish the data */
mono_loader_lock ();
if (klass->instance_size && !klass->image->dynamic && klass_byval_arg->type != MONO_TYPE_FNPTR) {
/* Might be already set using cached info */
if (klass->instance_size != instance_size) {
/* Emit info to help debugging */
g_print ("%s\n", mono_class_full_name (klass));
g_print ("%d %d %d %d\n", klass->instance_size, instance_size, klass->blittable, blittable);
g_print ("%d %d %d %d\n", klass->has_references, has_references, klass->has_ref_fields, has_ref_fields);
g_print ("%d %d %d %d\n", klass->packing_size, packing_size, klass->min_align, min_align);
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
printf (" %s %d %d %d\n", klass->fields [i].name, klass->fields [i].offset, field_offsets [i], fields_has_references [i]);
}
}
g_assert (klass->instance_size == instance_size);
} else {
klass->instance_size = instance_size;
}
klass->blittable = blittable;
klass->has_references = has_references;
klass->has_ref_fields = has_ref_fields;
klass->packing_size = packing_size;
klass->min_align = min_align;
klass->any_field_has_auto_layout = any_field_has_auto_layout;
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
klass->fields [i].offset = field_offsets [i];
}
if (klass_byval_arg->type == MONO_TYPE_SZARRAY || klass_byval_arg->type == MONO_TYPE_ARRAY)
klass->sizes.element_size = element_size;
mono_memory_barrier ();
klass->size_inited = 1;
mono_loader_unlock ();
/*
* Compute static field layout and size
* Static fields can reference the class itself, so this has to be
* done after instance_size etc. are initialized.
*/
class_size = 0;
for (i = 0; i < top; i++) {
gint32 align;
guint32 size;
field = &klass->fields [i];
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC) || field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
continue;
if (mono_field_is_deleted (field))
continue;
/* Type may not be initialized yet. Don't initialize it. If
it's a reference type we can get the size without
recursing */
if (mono_type_has_exceptions (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
break;
}
has_static_fields = TRUE;
size = mono_type_size (field->type, &align);
/* Check again in case initializing the field's type caused a failure */
if (mono_type_has_exceptions (field->type)) {
mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
break;
}
field_offsets [i] = class_size;
/*align is always non-zero here*/
field_offsets [i] += align - 1;
field_offsets [i] &= ~(align - 1);
class_size = field_offsets [i] + size;
}
if (has_static_fields && class_size == 0)
/* Simplify code which depends on class_size != 0 if the class has static fields */
class_size = 8;
/* Compute klass->has_static_refs */
has_static_refs = FALSE;
for (i = 0; i < top; i++) {
MonoType *ftype;
field = &klass->fields [i];
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
ftype = mono_type_get_underlying_type (field->type);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype))
has_static_refs = TRUE;
}
}
/*valuetypes can't be neither bigger than 1Mb or empty. */
if (klass->valuetype && (klass->instance_size <= 0 || klass->instance_size > (0x100000 + MONO_ABI_SIZEOF (MonoObject)))) {
/* Special case compiler generated types */
/* Hard to check for [CompilerGenerated] here */
if (!strstr (klass->name, "StaticArrayInitTypeSize") && !strstr (klass->name, "$ArrayType"))
mono_class_set_type_load_failure (klass, "Value type instance size (%d) cannot be zero, negative, or bigger than 1Mb", klass->instance_size);
}
// Weak field support
//
// FIXME:
// - generic instances
// - Disallow on structs/static fields/nonref fields
gboolean has_weak_fields = FALSE;
#ifdef ENABLE_WEAK_ATTR
if (mono_class_has_static_metadata (klass)) {
for (MonoClass *p = klass; p != NULL; p = p->parent) {
gpointer iter = NULL;
guint32 first_field_idx = mono_class_get_first_field_idx (p);
while ((field = mono_class_get_fields_internal (p, &iter))) {
guint32 field_idx = first_field_idx + (field - p->fields);
if (MONO_TYPE_IS_REFERENCE (field->type) && mono_assembly_is_weak_field (p->image, field_idx + 1)) {
has_weak_fields = TRUE;
mono_trace_message (MONO_TRACE_TYPE, "Field %s:%s at offset %x is weak.", m_field_get_parent (field)->name, field->name, field->offset);
}
}
}
}
#endif
/*
* Check that any fields of IsByRefLike type are instance
* fields and only inside other IsByRefLike structs.
*
* (Has to be done late because we call
* mono_class_from_mono_type_internal which may recursively
* refer to the current class)
*/
gboolean allow_isbyreflike_fields = m_class_is_byreflike (klass);
for (i = 0; i < top; i++) {
field = &klass->fields [i];
if (mono_field_is_deleted (field))
continue;
if ((field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
continue;
MonoClass *field_class = NULL;
/* have to be careful not to recursively invoke mono_class_init on a static field.
* for example - if the field is an array of a subclass of klass, we can loop.
*/
switch (field->type->type) {
case MONO_TYPE_TYPEDBYREF:
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_GENERICINST:
field_class = mono_class_from_mono_type_internal (field->type);
break;
default:
break;
}
if (!field_class || !m_class_is_byreflike (field_class))
continue;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
mono_class_set_type_load_failure (klass, "Static ByRefLike field '%s' is not allowed", field->name);
return;
} else {
/* instance field */
if (allow_isbyreflike_fields)
continue;
mono_class_set_type_load_failure (klass, "Instance ByRefLike field '%s' not in a ref struct", field->name);
return;
}
}
/* Publish the data */
mono_loader_lock ();
if (!klass->rank)
klass->sizes.class_size = class_size;
klass->has_static_refs = has_static_refs;
klass->has_weak_fields = has_weak_fields;
for (i = 0; i < top; ++i) {
field = &klass->fields [i];
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
field->offset = field_offsets [i];
}
mono_memory_barrier ();
klass->fields_inited = 1;
mono_loader_unlock ();
g_free (field_offsets);
g_free (fields_has_references);
}
static int finalize_slot = -1;
static void
initialize_object_slots (MonoClass *klass)
{
int i;
if (klass != mono_defaults.object_class || finalize_slot >= 0)
return;
mono_class_setup_vtable (klass);
for (i = 0; i < klass->vtable_size; ++i) {
if (!strcmp (klass->vtable [i]->name, "Finalize")) {
int const j = finalize_slot;
g_assert (j == -1 || j == i);
finalize_slot = i;
}
}
g_assert (finalize_slot >= 0);
}
int
mono_class_get_object_finalize_slot ()
{
return finalize_slot;
}
MonoMethod *
mono_class_get_default_finalize_method ()
{
int const i = finalize_slot;
return (i < 0) ? NULL : mono_defaults.object_class->vtable [i];
}
typedef struct {
MonoMethod *array_method;
char *name;
} GenericArrayMethodInfo;
static int generic_array_method_num = 0;
static GenericArrayMethodInfo *generic_array_method_info = NULL;
static void
setup_generic_array_ifaces (MonoClass *klass, MonoClass *iface, MonoMethod **methods, int pos, GHashTable *cache)
{
MonoGenericContext tmp_context;
MonoGenericClass *gclass;
int i;
// The interface can sometimes be a GTD in cases like IList
// See: https://github.com/mono/mono/issues/7095#issuecomment-470465597
if (mono_class_is_gtd (iface)) {
MonoType *ty = mono_class_gtd_get_canonical_inst (iface);
g_assert (ty->type == MONO_TYPE_GENERICINST);
gclass = ty->data.generic_class;
} else
gclass = mono_class_get_generic_class (iface);
tmp_context.class_inst = NULL;
tmp_context.method_inst = gclass->context.class_inst;
//g_print ("setting up array interface: %s\n", mono_type_get_name_full (m_class_get_byval_arg (iface), 0));
for (i = 0; i < generic_array_method_num; i++) {
ERROR_DECL (error);
MonoMethod *m = generic_array_method_info [i].array_method;
MonoMethod *inflated, *helper;
inflated = mono_class_inflate_generic_method_checked (m, &tmp_context, error);
mono_error_assert_ok (error);
helper = (MonoMethod*)g_hash_table_lookup (cache, inflated);
if (!helper) {
helper = mono_marshal_get_generic_array_helper (klass, generic_array_method_info [i].name, inflated);
g_hash_table_insert (cache, inflated, helper);
}
methods [pos ++] = helper;
}
}
static gboolean
check_method_exists (MonoClass *iface, const char *method_name)
{
g_assert (iface != NULL);
ERROR_DECL (method_lookup_error);
gboolean found = NULL != mono_class_get_method_from_name_checked (iface, method_name, -1, 0, method_lookup_error);
mono_error_cleanup (method_lookup_error);
return found;
}
static int
generic_array_methods (MonoClass *klass)
{
int i, count_generic = 0, mcount;
GList *list = NULL, *tmp;
if (generic_array_method_num)
return generic_array_method_num;
mono_class_setup_methods (klass->parent); /*This is setting up System.Array*/
g_assert (!mono_class_has_failure (klass->parent)); /*So hitting this assert is a huge problem*/
mcount = mono_class_get_method_count (klass->parent);
for (i = 0; i < mcount; i++) {
MonoMethod *m = klass->parent->methods [i];
if (!strncmp (m->name, "InternalArray__", 15)) {
count_generic++;
list = g_list_prepend (list, m);
}
}
list = g_list_reverse (list);
generic_array_method_info = (GenericArrayMethodInfo *)mono_image_alloc (mono_defaults.corlib, sizeof (GenericArrayMethodInfo) * count_generic);
i = 0;
for (tmp = list; tmp; tmp = tmp->next) {
const char *mname, *iname;
gchar *name;
MonoMethod *m = (MonoMethod *)tmp->data;
const char *ireadonlylist_prefix = "InternalArray__IReadOnlyList_";
const char *ireadonlycollection_prefix = "InternalArray__IReadOnlyCollection_";
MonoClass *iface = NULL;
if (!strncmp (m->name, "InternalArray__ICollection_", 27)) {
iname = "System.Collections.Generic.ICollection`1.";
mname = m->name + 27;
iface = mono_class_try_get_icollection_class ();
} else if (!strncmp (m->name, "InternalArray__IEnumerable_", 27)) {
iname = "System.Collections.Generic.IEnumerable`1.";
mname = m->name + 27;
iface = mono_class_try_get_ienumerable_class ();
} else if (!strncmp (m->name, ireadonlylist_prefix, strlen (ireadonlylist_prefix))) {
iname = "System.Collections.Generic.IReadOnlyList`1.";
mname = m->name + strlen (ireadonlylist_prefix);
iface = mono_defaults.generic_ireadonlylist_class;
} else if (!strncmp (m->name, ireadonlycollection_prefix, strlen (ireadonlycollection_prefix))) {
iname = "System.Collections.Generic.IReadOnlyCollection`1.";
mname = m->name + strlen (ireadonlycollection_prefix);
iface = mono_class_try_get_ireadonlycollection_class ();
} else if (!strncmp (m->name, "InternalArray__", 15)) {
iname = "System.Collections.Generic.IList`1.";
mname = m->name + 15;
iface = mono_defaults.generic_ilist_class;
} else {
g_assert_not_reached ();
}
if (!iface || !check_method_exists (iface, mname))
continue;
generic_array_method_info [i].array_method = m;
name = (gchar *)mono_image_alloc (mono_defaults.corlib, strlen (iname) + strlen (mname) + 1);
strcpy (name, iname);
strcpy (name + strlen (iname), mname);
generic_array_method_info [i].name = name;
i++;
}
/*g_print ("array generic methods: %d\n", count_generic);*/
/* only count the methods we actually added, not the ones that we
* skipped if they implement an interface method that was trimmed.
*/
generic_array_method_num = i;
g_list_free (list);
return generic_array_method_num;
}
static int array_get_method_count (MonoClass *klass)
{
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY)
/* Regular array */
/* ctor([int32]*rank) */
/* ctor([int32]*rank*2) */
/* Get */
/* Set */
/* Address */
return 5;
else if (klass_byval_arg->type == MONO_TYPE_SZARRAY && klass->rank == 1 && klass->element_class->rank)
/* Jagged arrays are typed as MONO_TYPE_SZARRAY but have an extra ctor in .net which creates an array of arrays */
/* ctor([int32]) */
/* ctor([int32], [int32]) */
/* Get */
/* Set */
/* Address */
return 5;
else
/* Vectors don't have additional constructor since a zero lower bound is assumed */
/* ctor([int32]*rank) */
/* Get */
/* Set */
/* Address */
return 4;
}
static gboolean array_supports_additional_ctor_method (MonoClass *klass)
{
MonoType *klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY)
/* Regular array */
return TRUE;
else if (klass_byval_arg->type == MONO_TYPE_SZARRAY && klass->rank == 1 && klass->element_class->rank)
/* Jagged array */
return TRUE;
else
/* Vector */
return FALSE;
}
/*
* Global pool of interface IDs, represented as a bitset.
* LOCKING: Protected by the classes lock.
*/
static MonoBitSet *global_interface_bitset = NULL;
/*
* mono_unload_interface_ids:
* @bitset: bit set of interface IDs
*
* When an image is unloaded, the interface IDs associated with
* the image are put back in the global pool of IDs so the numbers
* can be reused.
*/
void
mono_unload_interface_ids (MonoBitSet *bitset)
{
classes_lock ();
mono_bitset_sub (global_interface_bitset, bitset);
classes_unlock ();
}
void
mono_unload_interface_id (MonoClass *klass)
{
if (global_interface_bitset && klass->interface_id) {
classes_lock ();
mono_bitset_clear (global_interface_bitset, klass->interface_id);
classes_unlock ();
}
}
/**
* mono_get_unique_iid:
* \param klass interface
*
* Assign a unique integer ID to the interface represented by \p klass.
* The ID will positive and as small as possible.
* LOCKING: Acquires the classes lock.
* \returns The new ID.
*/
static guint32
mono_get_unique_iid (MonoClass *klass)
{
int iid;
g_assert (MONO_CLASS_IS_INTERFACE_INTERNAL (klass));
classes_lock ();
if (!global_interface_bitset) {
global_interface_bitset = mono_bitset_new (128, 0);
mono_bitset_set (global_interface_bitset, 0); //don't let 0 be a valid iid
}
iid = mono_bitset_find_first_unset (global_interface_bitset, -1);
if (iid < 0) {
int old_size = mono_bitset_size (global_interface_bitset);
MonoBitSet *new_set = mono_bitset_clone (global_interface_bitset, old_size * 2);
mono_bitset_free (global_interface_bitset);
global_interface_bitset = new_set;
iid = old_size;
}
mono_bitset_set (global_interface_bitset, iid);
/* set the bit also in the per-image set */
if (!mono_class_is_ginst (klass)) {
if (klass->image->interface_bitset) {
if (iid >= mono_bitset_size (klass->image->interface_bitset)) {
MonoBitSet *new_set = mono_bitset_clone (klass->image->interface_bitset, iid + 1);
mono_bitset_free (klass->image->interface_bitset);
klass->image->interface_bitset = new_set;
}
} else {
klass->image->interface_bitset = mono_bitset_new (iid + 1, 0);
}
mono_bitset_set (klass->image->interface_bitset, iid);
}
classes_unlock ();
#ifndef MONO_SMALL_CONFIG
if (mono_print_vtable) {
int generic_id;
char *type_name = mono_type_full_name (m_class_get_byval_arg (klass));
MonoGenericClass *gklass = mono_class_try_get_generic_class (klass);
if (gklass && !gklass->context.class_inst->is_open) {
generic_id = gklass->context.class_inst->id;
g_assert (generic_id != 0);
} else {
generic_id = 0;
}
printf ("Interface: assigned id %d to %s|%s|%d\n", iid, klass->image->assembly_name, type_name, generic_id);
g_free (type_name);
}
#endif
/* I've confirmed iids safe past 16 bits, however bitset code uses a signed int while testing.
* Once this changes, it should be safe for us to allow 2^32-1 interfaces, until then 2^31-2 is the max. */
g_assert (iid < INT_MAX);
return iid;
}
/**
* mono_class_init_internal:
* \param klass the class to initialize
*
* Compute the \c instance_size, \c class_size and other infos that cannot be
* computed at \c mono_class_get time. Also compute vtable_size if possible.
* Initializes the following fields in \p klass:
* - all the fields initialized by \c mono_class_init_sizes
* - has_cctor
* - ghcimpl
* - inited
*
* LOCKING: Acquires the loader lock.
*
* \returns TRUE on success or FALSE if there was a problem in loading
* the type (incorrect assemblies, missing assemblies, methods, etc).
*/
gboolean
mono_class_init_internal (MonoClass *klass)
{
int i, vtable_size = 0, array_method_count = 0;
MonoCachedClassInfo cached_info;
gboolean has_cached_info;
gboolean locked = FALSE;
gboolean ghcimpl = FALSE;
gboolean has_cctor = FALSE;
int first_iface_slot = 0;
g_assert (klass);
/* Double-checking locking pattern */
if (klass->inited || mono_class_has_failure (klass))
return !mono_class_has_failure (klass);
/*g_print ("Init class %s\n", mono_type_get_full_name (klass));*/
/*
* This function can recursively call itself.
*/
GSList *init_list = (GSList *)mono_native_tls_get_value (init_pending_tls_id);
if (g_slist_find (init_list, klass)) {
mono_class_set_type_load_failure (klass, "Recursive type definition detected %s.%s", klass->name_space, klass->name);
goto leave_no_init_pending;
}
init_list = g_slist_prepend (init_list, klass);
mono_native_tls_set_value (init_pending_tls_id, init_list);
/*
* We want to avoid doing complicated work inside locks, so we compute all the required
* information and write it to @klass inside a lock.
*/
MonoType *klass_byval_arg;
klass_byval_arg = m_class_get_byval_arg (klass);
if (klass_byval_arg->type == MONO_TYPE_ARRAY || klass_byval_arg->type == MONO_TYPE_SZARRAY) {
MonoClass *element_class = klass->element_class;
MonoClass *cast_class = klass->cast_class;
if (!element_class->inited)
mono_class_init_internal (element_class);
if (mono_class_set_type_load_failure_causedby_class (klass, element_class, "Could not load array element class"))
goto leave;
if (!cast_class->inited)
mono_class_init_internal (cast_class);
if (mono_class_set_type_load_failure_causedby_class (klass, cast_class, "Could not load array cast class"))
goto leave;
}
UnlockedIncrement (&mono_stats.initialized_class_count);
if (mono_class_is_ginst (klass) && !mono_class_get_generic_class (klass)->is_dynamic) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic Type Definition failed to init"))
goto leave;
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass))
mono_class_setup_interface_id (klass);
}
if (klass->parent && !klass->parent->inited)
mono_class_init_internal (klass->parent);
has_cached_info = mono_class_get_cached_class_info (klass, &cached_info);
/* Compute instance size etc. */
init_sizes_with_info (klass, has_cached_info ? &cached_info : NULL);
if (mono_class_has_failure (klass))
goto leave;
mono_class_setup_supertypes (klass);
initialize_object_slots (klass);
/*
* Initialize the rest of the data without creating a generic vtable if possible.
* If possible, also compute vtable_size, so mono_class_create_runtime_vtable () can
* also avoid computing a generic vtable.
*/
if (has_cached_info) {
/* AOT case */
vtable_size = cached_info.vtable_size;
ghcimpl = cached_info.ghcimpl;
has_cctor = cached_info.has_cctor;
} else if (klass->rank == 1 && klass_byval_arg->type == MONO_TYPE_SZARRAY) {
/* SZARRAY can have 3 vtable layouts, with and without the stelemref method and enum element type
* The first slot if for array with.
*/
static int szarray_vtable_size[3] = { 0 };
int slot;
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (klass))))
slot = 0;
else if (klass->element_class->enumtype)
slot = 1;
else
slot = 2;
/* SZARRAY case */
if (!szarray_vtable_size [slot]) {
mono_class_setup_vtable (klass);
szarray_vtable_size [slot] = klass->vtable_size;
vtable_size = klass->vtable_size;
} else {
vtable_size = szarray_vtable_size[slot];
}
} else if (mono_class_is_ginst (klass) && !MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
/* Generic instance case */
ghcimpl = gklass->ghcimpl;
has_cctor = gklass->has_cctor;
mono_class_setup_vtable (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to init"))
goto leave;
vtable_size = gklass->vtable_size;
} else {
/* General case */
/* C# doesn't allow interfaces to have cctors */
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || klass->image != mono_defaults.corlib) {
MonoMethod *cmethod = NULL;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
/* Generic instance case */
ghcimpl = gklass->ghcimpl;
has_cctor = gklass->has_cctor;
} else if (klass->type_token && !image_is_dynamic(klass->image)) {
cmethod = mono_find_method_in_metadata (klass, ".cctor", 0, METHOD_ATTRIBUTE_SPECIAL_NAME);
/* The find_method function ignores the 'flags' argument */
if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_SPECIAL_NAME))
has_cctor = 1;
} else {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
goto leave;
int mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
MonoMethod *method = klass->methods [i];
if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
(strcmp (".cctor", method->name) == 0)) {
has_cctor = 1;
break;
}
}
}
}
}
if (klass->rank) {
array_method_count = array_get_method_count (klass);
if (klass->interface_count) {
int count_generic = generic_array_methods (klass);
array_method_count += klass->interface_count * count_generic;
}
}
if (klass->parent) {
if (!klass->parent->vtable_size)
mono_class_setup_vtable (klass->parent);
if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class vtable failed to initialize"))
goto leave;
g_assert (klass->parent->vtable_size);
first_iface_slot = klass->parent->vtable_size;
if (mono_class_setup_need_stelemref_method (klass))
++first_iface_slot;
}
/*
* Do the actual changes to @klass inside the loader lock
*/
mono_loader_lock ();
locked = TRUE;
if (klass->inited || mono_class_has_failure (klass)) {
/* Somebody might have gotten in before us */
goto leave;
}
UnlockedIncrement (&mono_stats.initialized_class_count);
if (mono_class_is_ginst (klass) && !mono_class_get_generic_class (klass)->is_dynamic)
UnlockedIncrement (&mono_stats.generic_class_count);
if (mono_class_is_ginst (klass) || image_is_dynamic (klass->image) || !klass->type_token || (has_cached_info && !cached_info.has_nested_classes))
klass->nested_classes_inited = TRUE;
klass->ghcimpl = ghcimpl;
klass->has_cctor = has_cctor;
if (vtable_size)
klass->vtable_size = vtable_size;
if (has_cached_info) {
klass->has_finalize = cached_info.has_finalize;
klass->has_finalize_inited = TRUE;
}
if (klass->rank)
mono_class_set_method_count (klass, array_method_count);
mono_loader_unlock ();
locked = FALSE;
mono_class_setup_interface_offsets_internal (klass, first_iface_slot, TRUE);
if (mono_class_is_ginst (klass) && !mono_verifier_class_is_valid_generic_instantiation (klass))
mono_class_set_type_load_failure (klass, "Invalid generic instantiation");
goto leave;
leave:
init_list = (GSList*)mono_native_tls_get_value (init_pending_tls_id);
init_list = g_slist_remove (init_list, klass);
mono_native_tls_set_value (init_pending_tls_id, init_list);
leave_no_init_pending:
if (locked)
mono_loader_unlock ();
/* Leave this for last */
mono_loader_lock ();
klass->inited = 1;
mono_loader_unlock ();
return !mono_class_has_failure (klass);
}
gboolean
mono_class_init_checked (MonoClass *klass, MonoError *error)
{
error_init (error);
gboolean const success = mono_class_init_internal (klass);
if (!success)
mono_error_set_for_class_failure (error, klass);
return success;
}
#ifndef DISABLE_COM
/*
* COM initialization is delayed until needed.
* However when a [ComImport] attribute is present on a type it will trigger
* the initialization. This is not a problem unless the BCL being executed
* lacks the types that COM depends on (e.g. Variant on Silverlight).
*/
static void
init_com_from_comimport (MonoClass *klass)
{
/* FIXME : we should add an extra checks to ensure COM can be initialized properly before continuing */
}
#endif /*DISABLE_COM*/
/*
* LOCKING: this assumes the loader lock is held
*/
void
mono_class_setup_parent (MonoClass *klass, MonoClass *parent)
{
gboolean system_namespace;
gboolean is_corlib = mono_is_corlib_image (klass->image);
system_namespace = !strcmp (klass->name_space, "System") && is_corlib;
/* if root of the hierarchy */
if (system_namespace && !strcmp (klass->name, "Object")) {
klass->parent = NULL;
klass->instance_size = MONO_ABI_SIZEOF (MonoObject);
return;
}
if (!strcmp (klass->name, "<Module>")) {
klass->parent = NULL;
klass->instance_size = 0;
return;
}
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
/* Imported COM Objects always derive from __ComObject. */
#ifndef DISABLE_COM
if (MONO_CLASS_IS_IMPORT (klass)) {
init_com_from_comimport (klass);
if (parent == mono_defaults.object_class)
parent = mono_class_get_com_object_class ();
}
#endif
if (!parent) {
/* set the parent to something useful and safe, but mark the type as broken */
parent = mono_defaults.object_class;
mono_class_set_type_load_failure (klass, "");
g_assert (parent);
}
klass->parent = parent;
if (mono_class_is_ginst (parent) && !parent->name) {
/*
* If the parent is a generic instance, we may get
* called before it is fully initialized, especially
* before it has its name.
*/
return;
}
klass->delegate = parent->delegate;
if (MONO_CLASS_IS_IMPORT (klass) || mono_class_is_com_object (parent))
mono_class_set_is_com_object (klass);
if (system_namespace) {
if (klass->name [0] == 'D' && !strcmp (klass->name, "Delegate"))
klass->delegate = 1;
}
if (klass->parent->enumtype || (mono_is_corlib_image (klass->parent->image) && (strcmp (klass->parent->name, "ValueType") == 0) &&
(strcmp (klass->parent->name_space, "System") == 0)))
klass->valuetype = 1;
if (mono_is_corlib_image (klass->parent->image) && ((strcmp (klass->parent->name, "Enum") == 0) && (strcmp (klass->parent->name_space, "System") == 0))) {
klass->valuetype = klass->enumtype = 1;
}
/*klass->enumtype = klass->parent->enumtype; */
} else {
/* initialize com types if COM interfaces are present */
#ifndef DISABLE_COM
if (MONO_CLASS_IS_IMPORT (klass))
init_com_from_comimport (klass);
#endif
klass->parent = NULL;
}
}
/* Locking: must be called with the loader lock held. */
void
mono_class_setup_interface_id_nolock (MonoClass *klass)
{
if (!MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || klass->interface_id)
return;
klass->interface_id = mono_get_unique_iid (klass);
if (mono_is_corlib_image (klass->image) && !strcmp (m_class_get_name_space (klass), "System.Collections.Generic")) {
//FIXME IEnumerator needs to be special because GetEnumerator uses magic under the hood
/* FIXME: System.Array/InternalEnumerator don't need all this interface fabrication machinery.
* MS returns diferrent types based on which instance is called. For example:
* object obj = new byte[10][];
* Type a = ((IEnumerable<byte[]>)obj).GetEnumerator ().GetType ();
* Type b = ((IEnumerable<IList<byte>>)obj).GetEnumerator ().GetType ();
* a != b ==> true
*/
const char *name = m_class_get_name (klass);
if (!strcmp (name, "IList`1") || !strcmp (name, "ICollection`1") || !strcmp (name, "IEnumerable`1") || !strcmp (name, "IEnumerator`1"))
klass->is_array_special_interface = 1;
}
}
/*
* LOCKING: this assumes the loader lock is held
*/
void
mono_class_setup_mono_type (MonoClass *klass)
{
const char *name = klass->name;
const char *nspace = klass->name_space;
gboolean is_corlib = mono_is_corlib_image (klass->image);
klass->this_arg.byref__ = 1;
klass->this_arg.data.klass = klass;
klass->this_arg.type = MONO_TYPE_CLASS;
klass->_byval_arg.data.klass = klass;
klass->_byval_arg.type = MONO_TYPE_CLASS;
if (is_corlib && !strcmp (nspace, "System")) {
if (!strcmp (name, "ValueType")) {
/*
* do not set the valuetype bit for System.ValueType.
* klass->valuetype = 1;
*/
klass->blittable = TRUE;
} else if (!strcmp (name, "Enum")) {
/*
* do not set the valuetype bit for System.Enum.
* klass->valuetype = 1;
*/
klass->valuetype = 0;
klass->enumtype = 0;
} else if (!strcmp (name, "Object")) {
klass->_byval_arg.type = MONO_TYPE_OBJECT;
klass->this_arg.type = MONO_TYPE_OBJECT;
} else if (!strcmp (name, "String")) {
klass->_byval_arg.type = MONO_TYPE_STRING;
klass->this_arg.type = MONO_TYPE_STRING;
} else if (!strcmp (name, "TypedReference")) {
klass->_byval_arg.type = MONO_TYPE_TYPEDBYREF;
klass->this_arg.type = MONO_TYPE_TYPEDBYREF;
}
}
if (klass->valuetype) {
int t = MONO_TYPE_VALUETYPE;
if (is_corlib && !strcmp (nspace, "System")) {
switch (*name) {
case 'B':
if (!strcmp (name, "Boolean")) {
t = MONO_TYPE_BOOLEAN;
} else if (!strcmp(name, "Byte")) {
t = MONO_TYPE_U1;
klass->blittable = TRUE;
}
break;
case 'C':
if (!strcmp (name, "Char")) {
t = MONO_TYPE_CHAR;
}
break;
case 'D':
if (!strcmp (name, "Double")) {
t = MONO_TYPE_R8;
klass->blittable = TRUE;
}
break;
case 'I':
if (!strcmp (name, "Int32")) {
t = MONO_TYPE_I4;
klass->blittable = TRUE;
} else if (!strcmp(name, "Int16")) {
t = MONO_TYPE_I2;
klass->blittable = TRUE;
} else if (!strcmp(name, "Int64")) {
t = MONO_TYPE_I8;
klass->blittable = TRUE;
} else if (!strcmp(name, "IntPtr")) {
t = MONO_TYPE_I;
klass->blittable = TRUE;
}
break;
case 'S':
if (!strcmp (name, "Single")) {
t = MONO_TYPE_R4;
klass->blittable = TRUE;
} else if (!strcmp(name, "SByte")) {
t = MONO_TYPE_I1;
klass->blittable = TRUE;
}
break;
case 'U':
if (!strcmp (name, "UInt32")) {
t = MONO_TYPE_U4;
klass->blittable = TRUE;
} else if (!strcmp(name, "UInt16")) {
t = MONO_TYPE_U2;
klass->blittable = TRUE;
} else if (!strcmp(name, "UInt64")) {
t = MONO_TYPE_U8;
klass->blittable = TRUE;
} else if (!strcmp(name, "UIntPtr")) {
t = MONO_TYPE_U;
klass->blittable = TRUE;
}
break;
case 'T':
if (!strcmp (name, "TypedReference")) {
t = MONO_TYPE_TYPEDBYREF;
klass->blittable = TRUE;
}
break;
case 'V':
if (!strcmp (name, "Void")) {
t = MONO_TYPE_VOID;
}
break;
default:
break;
}
}
klass->_byval_arg.type = (MonoTypeEnum)t;
klass->this_arg.type = (MonoTypeEnum)t;
}
mono_class_setup_interface_id_nolock (klass);
}
static MonoMethod*
create_array_method (MonoClass *klass, const char *name, MonoMethodSignature *sig)
{
MonoMethod *method;
method = (MonoMethod *) mono_image_alloc0 (klass->image, sizeof (MonoMethodPInvoke));
method->klass = klass;
method->flags = METHOD_ATTRIBUTE_PUBLIC;
method->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
method->signature = sig;
method->name = name;
method->slot = -1;
/* .ctor */
if (name [0] == '.') {
method->flags |= METHOD_ATTRIBUTE_RT_SPECIAL_NAME | METHOD_ATTRIBUTE_SPECIAL_NAME;
} else {
method->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
}
return method;
}
/*
* mono_class_setup_methods:
* @class: a class
*
* Initializes the 'methods' array in CLASS.
* Calling this method should be avoided if possible since it allocates a lot
* of long-living MonoMethod structures.
* Methods belonging to an interface are assigned a sequential slot starting
* from 0.
*
* On failure this function sets klass->has_failure and stores a MonoErrorBoxed with details
*/
void
mono_class_setup_methods (MonoClass *klass)
{
int i, count;
MonoMethod **methods;
if (klass->methods)
return;
if (mono_class_is_ginst (klass)) {
ERROR_DECL (error);
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
if (!mono_class_has_failure (gklass))
mono_class_setup_methods (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
/* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
count = mono_class_get_method_count (gklass);
methods = (MonoMethod **)mono_class_alloc0 (klass, sizeof (MonoMethod*) * (count + 1));
for (i = 0; i < count; i++) {
methods [i] = mono_class_inflate_generic_method_full_checked (
gklass->methods [i], klass, mono_class_get_context (klass), error);
if (!is_ok (error)) {
char *method = mono_method_full_name (gklass->methods [i], TRUE);
mono_class_set_type_load_failure (klass, "Could not inflate method %s due to %s", method, mono_error_get_message (error));
g_free (method);
mono_error_cleanup (error);
return;
}
}
} else if (klass->rank) {
ERROR_DECL (error);
MonoMethod *amethod;
MonoMethodSignature *sig;
int count_generic = 0, first_generic = 0;
int method_num = 0;
count = array_get_method_count (klass);
mono_class_setup_interfaces (klass, error);
g_assert (is_ok (error)); /*FIXME can this fail for array types?*/
if (klass->interface_count) {
count_generic = generic_array_methods (klass);
first_generic = count;
count += klass->interface_count * count_generic;
}
methods = (MonoMethod **)mono_class_alloc0 (klass, sizeof (MonoMethod*) * count);
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, ".ctor", sig);
methods [method_num++] = amethod;
if (array_supports_additional_ctor_method (klass)) {
sig = mono_metadata_signature_alloc (klass->image, klass->rank * 2);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank * 2; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, ".ctor", sig);
methods [method_num++] = amethod;
}
/* element Get (idx11, [idx2, ...]) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = m_class_get_byval_arg (m_class_get_element_class (klass));
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, "Get", sig);
methods [method_num++] = amethod;
/* element& Address (idx11, [idx2, ...]) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank);
sig->ret = &klass->element_class->this_arg;
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
amethod = create_array_method (klass, "Address", sig);
methods [method_num++] = amethod;
/* void Set (idx11, [idx2, ...], element) */
sig = mono_metadata_signature_alloc (klass->image, klass->rank + 1);
sig->ret = mono_get_void_type ();
sig->pinvoke = TRUE;
sig->hasthis = TRUE;
for (i = 0; i < klass->rank; ++i)
sig->params [i] = mono_get_int32_type ();
sig->params [i] = m_class_get_byval_arg (m_class_get_element_class (klass));
amethod = create_array_method (klass, "Set", sig);
methods [method_num++] = amethod;
GHashTable *cache = g_hash_table_new (NULL, NULL);
for (i = 0; i < klass->interface_count; i++)
setup_generic_array_ifaces (klass, klass->interfaces [i], methods, first_generic + i * count_generic, cache);
g_hash_table_destroy (cache);
} else if (mono_class_has_static_metadata (klass)) {
ERROR_DECL (error);
int first_idx = mono_class_get_first_method_idx (klass);
count = mono_class_get_method_count (klass);
methods = (MonoMethod **)mono_class_alloc (klass, sizeof (MonoMethod*) * count);
for (i = 0; i < count; ++i) {
int idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, first_idx + i + 1);
methods [i] = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, error);
if (!methods [i]) {
mono_class_set_type_load_failure (klass, "Could not load method %d due to %s", i, mono_error_get_message (error));
mono_error_cleanup (error);
}
}
} else {
methods = (MonoMethod **)mono_class_alloc (klass, sizeof (MonoMethod*) * 1);
count = 0;
}
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass)) {
int slot = 0;
/*Only assign slots to virtual methods as interfaces are allowed to have static methods.*/
for (i = 0; i < count; ++i) {
if (methods [i]->flags & METHOD_ATTRIBUTE_VIRTUAL)
{
if (method_is_reabstracted (methods[i]->flags)) {
if (!methods [i]->is_inflated)
mono_method_set_is_reabstracted (methods [i]);
continue;
}
methods [i]->slot = slot++;
}
}
}
mono_image_lock (klass->image);
if (!klass->methods) {
mono_class_set_method_count (klass, count);
/* Needed because of the double-checking locking pattern */
mono_memory_barrier ();
klass->methods = methods;
}
mono_image_unlock (klass->image);
}
/*
* mono_class_setup_properties:
*
* Initialize klass->ext.property and klass->ext.properties.
*
* This method can fail the class.
*/
void
mono_class_setup_properties (MonoClass *klass)
{
guint startm, endm, i, j;
guint32 cols [MONO_PROPERTY_SIZE];
MonoTableInfo *msemt = &klass->image->tables [MONO_TABLE_METHODSEMANTICS];
MonoProperty *properties;
guint32 last;
int first, count;
MonoClassPropertyInfo *info;
info = mono_class_get_property_info (klass);
if (info)
return;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_init_internal (gklass);
mono_class_setup_properties (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
MonoClassPropertyInfo *ginfo = mono_class_get_property_info (gklass);
properties = mono_class_new0 (klass, MonoProperty, ginfo->count + 1);
for (i = 0; i < ginfo->count; i++) {
ERROR_DECL (error);
MonoProperty *prop = &properties [i];
*prop = ginfo->properties [i];
if (prop->get)
prop->get = mono_class_inflate_generic_method_full_checked (
prop->get, klass, mono_class_get_context (klass), error);
if (prop->set)
prop->set = mono_class_inflate_generic_method_full_checked (
prop->set, klass, mono_class_get_context (klass), error);
g_assert (is_ok (error)); /*FIXME proper error handling*/
prop->parent = klass;
}
first = ginfo->first;
count = ginfo->count;
} else {
first = mono_metadata_properties_from_typedef (klass->image, mono_metadata_token_index (klass->type_token) - 1, &last);
count = last - first;
if (count) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return;
}
properties = (MonoProperty *)mono_class_alloc0 (klass, sizeof (MonoProperty) * count);
for (i = first; i < last; ++i) {
mono_metadata_decode_table_row (klass->image, MONO_TABLE_PROPERTY, i, cols, MONO_PROPERTY_SIZE);
properties [i - first].parent = klass;
properties [i - first].attrs = cols [MONO_PROPERTY_FLAGS];
properties [i - first].name = mono_metadata_string_heap (klass->image, cols [MONO_PROPERTY_NAME]);
startm = mono_metadata_methods_from_property (klass->image, i, &endm);
int first_idx = mono_class_get_first_method_idx (klass);
for (j = startm; j < endm; ++j) {
MonoMethod *method;
mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
if (klass->image->uncompressed_metadata) {
ERROR_DECL (error);
/* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], klass, NULL, error);
mono_error_cleanup (error); /* FIXME don't swallow this error */
} else {
method = klass->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - first_idx];
}
switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
case METHOD_SEMANTIC_SETTER:
properties [i - first].set = method;
break;
case METHOD_SEMANTIC_GETTER:
properties [i - first].get = method;
break;
default:
break;
}
}
}
}
info = (MonoClassPropertyInfo*)mono_class_alloc0 (klass, sizeof (MonoClassPropertyInfo));
info->first = first;
info->count = count;
info->properties = properties;
mono_memory_barrier ();
/* This might leak 'info' which was allocated from the image mempool */
mono_class_set_property_info (klass, info);
}
static MonoMethod**
inflate_method_listz (MonoMethod **methods, MonoClass *klass, MonoGenericContext *context)
{
MonoMethod **om, **retval;
int count;
for (om = methods, count = 0; *om; ++om, ++count)
;
retval = g_new0 (MonoMethod*, count + 1);
count = 0;
for (om = methods, count = 0; *om; ++om, ++count) {
ERROR_DECL (error);
retval [count] = mono_class_inflate_generic_method_full_checked (*om, klass, context, error);
g_assert (is_ok (error)); /*FIXME proper error handling*/
}
return retval;
}
/*This method can fail the class.*/
void
mono_class_setup_events (MonoClass *klass)
{
int first, count;
guint startm, endm, i, j;
guint32 cols [MONO_EVENT_SIZE];
MonoTableInfo *msemt = &klass->image->tables [MONO_TABLE_METHODSEMANTICS];
guint32 last;
MonoEvent *events;
MonoClassEventInfo *info = mono_class_get_event_info (klass);
if (info)
return;
if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
MonoGenericContext *context = NULL;
mono_class_setup_events (gklass);
if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
MonoClassEventInfo *ginfo = mono_class_get_event_info (gklass);
first = ginfo->first;
count = ginfo->count;
events = mono_class_new0 (klass, MonoEvent, count);
if (count)
context = mono_class_get_context (klass);
for (i = 0; i < count; i++) {
ERROR_DECL (error);
MonoEvent *event = &events [i];
MonoEvent *gevent = &ginfo->events [i];
event->parent = klass;
event->name = gevent->name;
event->add = gevent->add ? mono_class_inflate_generic_method_full_checked (gevent->add, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
event->remove = gevent->remove ? mono_class_inflate_generic_method_full_checked (gevent->remove, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
event->raise = gevent->raise ? mono_class_inflate_generic_method_full_checked (gevent->raise, klass, context, error) : NULL;
g_assert (is_ok (error)); /*FIXME proper error handling*/
#ifndef MONO_SMALL_CONFIG
event->other = gevent->other ? inflate_method_listz (gevent->other, klass, context) : NULL;
#endif
event->attrs = gevent->attrs;
}
} else {
first = mono_metadata_events_from_typedef (klass->image, mono_metadata_token_index (klass->type_token) - 1, &last);
count = last - first;
if (count) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass)) {
return;
}
}
events = (MonoEvent *)mono_class_alloc0 (klass, sizeof (MonoEvent) * count);
for (i = first; i < last; ++i) {
MonoEvent *event = &events [i - first];
mono_metadata_decode_table_row (klass->image, MONO_TABLE_EVENT, i, cols, MONO_EVENT_SIZE);
event->parent = klass;
event->attrs = cols [MONO_EVENT_FLAGS];
event->name = mono_metadata_string_heap (klass->image, cols [MONO_EVENT_NAME]);
startm = mono_metadata_methods_from_event (klass->image, i, &endm);
int first_idx = mono_class_get_first_method_idx (klass);
for (j = startm; j < endm; ++j) {
MonoMethod *method;
mono_metadata_decode_row (msemt, j, cols, MONO_METHOD_SEMA_SIZE);
if (klass->image->uncompressed_metadata) {
ERROR_DECL (error);
/* It seems like the MONO_METHOD_SEMA_METHOD column needs no remapping */
method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | cols [MONO_METHOD_SEMA_METHOD], klass, NULL, error);
mono_error_cleanup (error); /* FIXME don't swallow this error */
} else {
method = klass->methods [cols [MONO_METHOD_SEMA_METHOD] - 1 - first_idx];
}
switch (cols [MONO_METHOD_SEMA_SEMANTICS]) {
case METHOD_SEMANTIC_ADD_ON:
event->add = method;
break;
case METHOD_SEMANTIC_REMOVE_ON:
event->remove = method;
break;
case METHOD_SEMANTIC_FIRE:
event->raise = method;
break;
case METHOD_SEMANTIC_OTHER: {
#ifndef MONO_SMALL_CONFIG
int n = 0;
if (event->other == NULL) {
event->other = g_new0 (MonoMethod*, 2);
} else {
while (event->other [n])
n++;
event->other = (MonoMethod **)g_realloc (event->other, (n + 2) * sizeof (MonoMethod*));
}
event->other [n] = method;
/* NULL terminated */
event->other [n + 1] = NULL;
#endif
break;
}
default:
break;
}
}
}
}
info = (MonoClassEventInfo*)mono_class_alloc0 (klass, sizeof (MonoClassEventInfo));
info->events = events;
info->first = first;
info->count = count;
mono_memory_barrier ();
mono_class_set_event_info (klass, info);
}
/*
* mono_class_setup_interface_id:
*
* Initializes MonoClass::interface_id if required.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_interface_id (MonoClass *klass)
{
g_assert (MONO_CLASS_IS_INTERFACE_INTERNAL (klass));
mono_loader_lock ();
mono_class_setup_interface_id_nolock (klass);
mono_loader_unlock ();
}
/*
* mono_class_setup_interfaces:
*
* Initialize klass->interfaces/interfaces_count.
* LOCKING: Acquires the loader lock.
* This function can fail the type.
*/
void
mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
{
int i, interface_count;
MonoClass *iface, **interfaces;
error_init (error);
if (klass->interfaces_inited)
return;
if (klass->rank == 1 && m_class_get_byval_arg (klass)->type != MONO_TYPE_ARRAY) {
MonoType *args [1];
MonoClass *array_ifaces [16];
/*
* Arrays implement IList and IReadOnlyList or their base interfaces if they are not linked out.
* For arrays of enums, they implement the interfaces for the base type as well.
*/
interface_count = 0;
if (mono_defaults.generic_ilist_class) {
array_ifaces [interface_count ++] = mono_defaults.generic_ilist_class;
} else {
iface = mono_class_try_get_icollection_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
if (mono_defaults.generic_ireadonlylist_class) {
array_ifaces [interface_count ++] = mono_defaults.generic_ireadonlylist_class;
} else {
iface = mono_class_try_get_ireadonlycollection_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
if (!mono_defaults.generic_ilist_class && !mono_defaults.generic_ireadonlylist_class) {
iface = mono_class_try_get_ienumerable_class ();
if (iface)
array_ifaces [interface_count ++] = iface;
}
int mult = klass->element_class->enumtype ? 2 : 1;
interfaces = (MonoClass **)mono_image_alloc0 (klass->image, sizeof (MonoClass*) * interface_count * mult);
int itf_idx = 0;
args [0] = m_class_get_byval_arg (m_class_get_element_class (klass));
for (int i = 0; i < interface_count; ++i)
interfaces [itf_idx++] = mono_class_bind_generic_parameters (array_ifaces [i], 1, args, FALSE);
if (klass->element_class->enumtype) {
args [0] = mono_class_enum_basetype_internal (klass->element_class);
for (int i = 0; i < interface_count; ++i)
interfaces [itf_idx++] = mono_class_bind_generic_parameters (array_ifaces [i], 1, args, FALSE);
}
interface_count *= mult;
g_assert (itf_idx == interface_count);
} else if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
mono_class_setup_interfaces (gklass, error);
if (!is_ok (error)) {
mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
interface_count = gklass->interface_count;
interfaces = mono_class_new0 (klass, MonoClass *, interface_count);
for (i = 0; i < interface_count; i++) {
interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
if (!is_ok (error)) {
mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
}
} else {
interface_count = 0;
interfaces = NULL;
}
mono_loader_lock ();
if (!klass->interfaces_inited) {
klass->interface_count = interface_count;
klass->interfaces = interfaces;
mono_memory_barrier ();
klass->interfaces_inited = TRUE;
}
mono_loader_unlock ();
}
/*
* mono_class_setup_has_finalizer:
*
* Initialize klass->has_finalizer if it isn't already initialized.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_has_finalizer (MonoClass *klass)
{
gboolean has_finalize = FALSE;
if (m_class_is_has_finalize_inited (klass))
return;
/* Interfaces and valuetypes are not supposed to have finalizers */
if (!(MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || m_class_is_valuetype (klass))) {
MonoMethod *cmethod = NULL;
if (m_class_get_rank (klass) == 1 && m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY) {
} else if (mono_class_is_ginst (klass)) {
MonoClass *gklass = mono_class_get_generic_class (klass)->container_class;
has_finalize = mono_class_has_finalizer (gklass);
} else if (m_class_get_parent (klass) && m_class_has_finalize (m_class_get_parent (klass))) {
has_finalize = TRUE;
} else {
if (m_class_get_parent (klass)) {
/*
* Can't search in metadata for a method named Finalize, because that
* ignores overrides.
*/
mono_class_setup_vtable (klass);
if (mono_class_has_failure (klass))
cmethod = NULL;
else
cmethod = m_class_get_vtable (klass) [mono_class_get_object_finalize_slot ()];
}
if (cmethod) {
g_assert (m_class_get_vtable_size (klass) > mono_class_get_object_finalize_slot ());
if (m_class_get_parent (klass)) {
if (cmethod->is_inflated)
cmethod = ((MonoMethodInflated*)cmethod)->declaring;
if (cmethod != mono_class_get_default_finalize_method ())
has_finalize = TRUE;
}
}
}
}
mono_loader_lock ();
if (!m_class_is_has_finalize_inited (klass)) {
klass->has_finalize = has_finalize ? 1 : 0;
mono_memory_barrier ();
klass->has_finalize_inited = TRUE;
}
mono_loader_unlock ();
}
/*
* mono_class_setup_supertypes:
* @class: a class
*
* Build the data structure needed to make fast type checks work.
* This currently sets two fields in @class:
* - idepth: distance between @class and System.Object in the type
* hierarchy + 1
* - supertypes: array of classes: each element has a class in the hierarchy
* starting from @class up to System.Object
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_supertypes (MonoClass *klass)
{
int ms, idepth;
MonoClass **supertypes;
mono_atomic_load_acquire (supertypes, MonoClass **, &klass->supertypes);
if (supertypes)
return;
if (klass->parent && !klass->parent->supertypes)
mono_class_setup_supertypes (klass->parent);
if (klass->parent)
idepth = klass->parent->idepth + 1;
else
idepth = 1;
ms = MAX (MONO_DEFAULT_SUPERTABLE_SIZE, idepth);
supertypes = (MonoClass **)mono_class_alloc0 (klass, sizeof (MonoClass *) * ms);
if (klass->parent) {
CHECKED_METADATA_WRITE_PTR ( supertypes [idepth - 1] , klass );
int supertype_idx;
for (supertype_idx = 0; supertype_idx < klass->parent->idepth; supertype_idx++)
CHECKED_METADATA_WRITE_PTR ( supertypes [supertype_idx] , klass->parent->supertypes [supertype_idx] );
} else {
CHECKED_METADATA_WRITE_PTR ( supertypes [0] , klass );
}
mono_memory_barrier ();
mono_loader_lock ();
klass->idepth = idepth;
/* Needed so idepth is visible before supertypes is set */
mono_memory_barrier ();
klass->supertypes = supertypes;
mono_loader_unlock ();
}
/* mono_class_setup_nested_types:
*
* Initialize the nested_classes property for the given MonoClass if it hasn't already been initialized.
*
* LOCKING: Acquires the loader lock.
*/
void
mono_class_setup_nested_types (MonoClass *klass)
{
ERROR_DECL (error);
GList *classes, *nested_classes, *l;
int i;
if (klass->nested_classes_inited)
return;
if (!klass->type_token) {
mono_loader_lock ();
klass->nested_classes_inited = TRUE;
mono_loader_unlock ();
return;
}
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, 1);
classes = NULL;
while (i) {
MonoClass* nclass;
guint32 cols [MONO_NESTED_CLASS_SIZE];
mono_metadata_decode_row (&klass->image->tables [MONO_TABLE_NESTEDCLASS], i - 1, cols, MONO_NESTED_CLASS_SIZE);
nclass = mono_class_create_from_typedef (klass->image, MONO_TOKEN_TYPE_DEF | cols [MONO_NESTED_CLASS_NESTED], error);
if (!is_ok (error)) {
/*FIXME don't swallow the error message*/
mono_error_cleanup (error);
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
continue;
}
classes = g_list_prepend (classes, nclass);
i = mono_metadata_nesting_typedef (klass->image, klass->type_token, i + 1);
}
nested_classes = NULL;
for (l = classes; l; l = l->next)
nested_classes = mono_g_list_prepend_image (klass->image, nested_classes, l->data);
g_list_free (classes);
mono_loader_lock ();
if (!klass->nested_classes_inited) {
mono_class_set_nested_classes_property (klass, nested_classes);
mono_memory_barrier ();
klass->nested_classes_inited = TRUE;
}
mono_loader_unlock ();
}
/**
* mono_class_create_array_fill_type:
*
* Returns a \c MonoClass that is used by SGen to fill out nursery fragments before a collection.
*/
MonoClass *
mono_class_create_array_fill_type (void)
{
static MonoClassArray aklass;
aklass.klass.class_kind = MONO_CLASS_GC_FILLER;
aklass.klass.element_class = mono_defaults.int64_class;
aklass.klass.rank = 1;
aklass.klass.instance_size = MONO_SIZEOF_MONO_ARRAY;
aklass.klass.sizes.element_size = 8;
aklass.klass.size_inited = 1;
aklass.klass.name = "array_filler_type";
return &aklass.klass;
}
void
mono_class_set_runtime_vtable (MonoClass *klass, MonoVTable *vtable)
{
klass->runtime_vtable = vtable;
}
/**
* mono_classes_init:
*
* Initialize the resources used by this module.
* Known racy counters: `class_gparam_count`, `classes_size` and `mono_inflated_methods_size`
*/
MONO_NO_SANITIZE_THREAD
void
mono_classes_init (void)
{
mono_os_mutex_init (&classes_mutex);
mono_native_tls_alloc (&setup_fields_tls_id, NULL);
mono_native_tls_alloc (&init_pending_tls_id, NULL);
mono_counters_register ("MonoClassDef count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_def_count);
mono_counters_register ("MonoClassGtd count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_gtd_count);
mono_counters_register ("MonoClassGenericInst count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ginst_count);
mono_counters_register ("MonoClassGenericParam count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_gparam_count);
mono_counters_register ("MonoClassArray count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_array_count);
mono_counters_register ("MonoClassPointer count",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_pointer_count);
mono_counters_register ("Inflated methods size",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &mono_inflated_methods_size);
mono_counters_register ("Inflated classes size",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_classes_size);
mono_counters_register ("MonoClass size",
MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size);
}
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/custom-attrs.c | /**
* \file
* Custom attributes.
*
* Author:
* Paolo Molaro ([email protected])
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2011 Rodrigo Kumpera
* Copyright 2016 Microsoft
*
* 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/class-init.h"
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internals.h"
#include "mono/metadata/mono-endian.h"
#include "mono/metadata/object-internals.h"
#include "mono/metadata/custom-attrs-internals.h"
#include "mono/metadata/sre-internals.h"
#include "mono/metadata/reflection-internals.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/icall-decl.h"
#include "mono/metadata/metadata-update.h"
#include "mono/utils/checked-build.h"
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
#define CATTR_TYPE_SYSTEM_TYPE 0x50
#define CATTR_BOXED_VALUETYPE_PREFIX 0x51
#define CATTR_TYPE_FIELD 0x53
#define CATTR_TYPE_PROPERTY 0x54
static gboolean type_is_reference (MonoType *type);
static GENERATE_GET_CLASS_WITH_CACHE (custom_attribute_typed_argument, "System.Reflection", "CustomAttributeTypedArgument");
static GENERATE_GET_CLASS_WITH_CACHE (custom_attribute_named_argument, "System.Reflection", "CustomAttributeNamedArgument");
static GENERATE_TRY_GET_CLASS_WITH_CACHE (customattribute_data, "System.Reflection", "RuntimeCustomAttributeData");
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders_handle (MonoImage *alloc_img, MonoImage *image, MonoArrayHandle cattrs);
static gboolean
bcheck_blob (const char *ptr, int bump, const char *endp, MonoError *error);
static gboolean
decode_blob_value_checked (const char *ptr, const char *endp, guint32 *size_out, const char **retp, MonoError *error);
static guint32
custom_attrs_idx_from_class (MonoClass *klass);
static guint32
custom_attrs_idx_from_method (MonoMethod *method);
static void
metadata_foreach_custom_attr_from_index (MonoImage *image, guint32 idx, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data);
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoCustomAttrInfo* res;
res = (MonoCustomAttrInfo *)mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
res = (MonoCustomAttrInfo *)g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
res->cached = 0;
return res;
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttrHandle cattr, MonoReflectionMethodHandle ctor_handle, MonoMethod **ctor_method)
// ctor_handle is local to this function, allocated by its caller for efficiency.
{
MONO_REQ_GC_UNSAFE_MODE;
MONO_HANDLE_GET (ctor_handle, cattr, ctor);
*ctor_method = MONO_HANDLE_GETVAL (ctor_handle, method);
/* FIXME: Need to do more checks */
if (*ctor_method) {
MonoClass *klass = (*ctor_method)->klass;
if (m_class_get_image (klass) != image) {
const int visibility = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_VISIBILITY_MASK);
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
}
return TRUE;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
if (G_UNLIKELY (m_field_is_from_update (field)))
return mono_metadata_update_get_field_idx (field);
int fcount = mono_class_get_field_count (klass);
MonoClassField *klass_fields = m_class_get_fields (klass);
int index = field - klass_fields;
if (index > fcount)
return 0;
g_assert (field == &klass_fields [index]);
return mono_class_get_first_field_idx (klass) + 1 + index;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property)
{
int i;
MonoClassPropertyInfo *info = mono_class_get_property_info (klass);
for (i = 0; i < info->count; ++i) {
if (property == &info->properties [i])
return info->first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event)
{
int i;
MonoClassEventInfo *info = mono_class_get_event_info (klass);
for (i = 0; i < info->count; ++i) {
if (event == &info->events [i])
return info->first + 1 + i;
}
return 0;
}
/*
* Load the type with name @n on behalf of image @image. On failure sets @error and returns NULL.
* The @is_enum flag only affects the error message that's displayed on failure.
*/
static MonoType*
cattr_type_from_name (char *n, MonoImage *image, gboolean is_enum, MonoError *error)
{
ERROR_DECL (inner_error);
MonoAssemblyLoadContext *alc = mono_alc_get_ambient ();
MonoType *t = mono_reflection_type_from_name_checked (n, alc, image, inner_error);
if (!t) {
mono_error_set_type_load_name (error, g_strdup(n), NULL,
"Could not load %s %s while decoding custom attribute: %s",
is_enum ? "enum type": "type",
n,
mono_error_get_message (inner_error));
mono_error_cleanup (inner_error);
return NULL;
}
return t;
}
static MonoClass*
load_cattr_enum_type (MonoImage *image, const char *p, const char *boundp, const char **end, MonoError *error)
{
char *n;
MonoType *t;
guint32 slen;
error_init (error);
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (boundp && slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = cattr_type_from_name (n, image, TRUE, error);
g_free (n);
return_val_if_nok (error, NULL);
p += slen;
*end = p;
return mono_class_from_mono_type_internal (t);
}
static MonoType*
load_cattr_type (MonoImage *image, MonoType *t, gboolean header, const char *p, const char *boundp, const char **end, MonoError *error, guint32 *slen)
{
MonoType *res;
char *n;
if (header) {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MONO_DISABLE_WARNING(4310) // cast truncates constant value
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
MONO_RESTORE_WARNING
}
if (!decode_blob_value_checked (p, boundp, slen, &p, error))
return NULL;
if (*slen > 0 && !bcheck_blob (p, *slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, *slen + 1);
n [*slen] = 0;
res = cattr_type_from_name (n, image, FALSE, error);
g_free (n);
return_val_if_nok (error, NULL);
*end = p + *slen;
return res;
}
/*
* If OUT_OBJ is non-NULL, created objects are stored into it and NULL is returned.
* If OUT_OBJ is NULL, assert if objects were to be created.
*/
static void*
load_cattr_value (MonoImage *image, MonoType *t, MonoObject **out_obj, const char *p, const char *boundp, const char **end, MonoError *error)
{
int type = t->type;
guint32 slen;
MonoClass *tklass = t->data.klass;
if (out_obj)
*out_obj = NULL;
g_assert (boundp);
error_init (error);
if (type == MONO_TYPE_GENERICINST) {
MonoGenericClass * mgc = t->data.generic_class;
MonoClass * cc = mgc->container_class;
if (m_class_is_enumtype (cc)) {
tklass = m_class_get_element_class (cc);
t = m_class_get_byval_arg (tklass);
type = t->type;
} else {
g_error ("Unhandled type of generic instance in load_cattr_value: %s", m_class_get_name (cc));
}
}
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = (MonoBoolean *)g_malloc (sizeof (MonoBoolean));
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = (guint16 *)g_malloc (sizeof (guint16));
if (!bcheck_blob (p, 1, boundp, error))
return NULL;
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = (guint32 *)g_malloc (sizeof (guint32));
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = (guint64 *)g_malloc (sizeof (guint64));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = (double *)g_malloc (sizeof (double));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (m_class_is_enumtype (t->data.klass)) {
type = mono_class_enum_basetype_internal (t->data.klass)->type;
goto handle_enum;
} else {
MonoClass *k = t->data.klass;
if (mono_is_corlib_image (m_class_get_image (k)) && strcmp (m_class_get_name_space (k), "System") == 0 && strcmp (m_class_get_name (k), "DateTime") == 0){
guint64 *val = (guint64 *)g_malloc (sizeof (guint64));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
*val = read64 (p);
*end = p + 8;
return val;
}
}
g_error ("generic valutype %s not handled in custom attr value decoding", m_class_get_name (t->data.klass));
break;
case MONO_TYPE_STRING: {
const char *start = p;
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MONO_DISABLE_WARNING (4310) // cast truncates constant value
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
MONO_RESTORE_WARNING
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
*end = p + slen;
if (!out_obj)
return (void*)start;
// https://bugzilla.xamarin.com/show_bug.cgi?id=60848
// Custom attribute strings are encoded as wtf-8 instead of utf-8.
// If we decode using utf-8 like the spec says, we will silently fail
// to decode some attributes in assemblies that Windows .NET Framework
// and CoreCLR both manage to decode.
// See https://simonsapin.github.io/wtf-8/ for a description of wtf-8.
// Always use string.Empty for empty strings
if (slen == 0)
*out_obj = (MonoObject*)mono_string_empty_internal (mono_domain_get ());
else
*out_obj = (MonoObject*)mono_string_new_wtf8_len_checked (p, slen, error);
return NULL;
}
case MONO_TYPE_CLASS: {
MonoType *type = load_cattr_type (image, t, TRUE, p, boundp, end, error, &slen);
if (out_obj) {
if (!type)
return NULL;
*out_obj = (MonoObject*)mono_type_get_object_checked (type, error);
return NULL;
} else {
return type;
}
}
case MONO_TYPE_OBJECT: {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == CATTR_TYPE_SYSTEM_TYPE) {
MonoType *type = load_cattr_type (image, t, FALSE, p, boundp, end, error, &slen);
if (out_obj) {
if (!type)
return NULL;
*out_obj = (MonoObject*)mono_type_get_object_checked (type, error);
return NULL;
} else {
return type;
}
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
int etype = *p;
p ++;
type = MONO_TYPE_SZARRAY;
if (etype == CATTR_TYPE_SYSTEM_TYPE) {
tklass = mono_defaults.systemtype_class;
} else if (etype == MONO_TYPE_ENUM) {
tklass = load_cattr_enum_type (image, p, boundp, &p, error);
if (!is_ok (error))
return NULL;
} else {
if (etype == CATTR_BOXED_VALUETYPE_PREFIX)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
simple_type.type = (MonoTypeEnum)etype;
tklass = mono_class_from_mono_type_internal (&simple_type);
}
goto handle_enum;
} else if (subt == MONO_TYPE_ENUM) {
char *n;
MonoType *t;
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = cattr_type_from_name (n, image, FALSE, error);
g_free (n);
return_val_if_nok (error, NULL);
p += slen;
subc = mono_class_from_mono_type_internal (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = (MonoTypeEnum)subt;
subc = mono_class_from_mono_type_internal (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, m_class_get_byval_arg (subc), NULL, p, boundp, end, error);
if (is_ok (error)) {
obj = mono_object_new_checked (subc, error);
g_assert (!m_class_has_references (subc));
if (is_ok (error))
mono_gc_memmove_atomic (mono_object_get_data (obj), val, mono_class_value_size (subc, NULL));
g_assert (out_obj);
*out_obj = obj;
}
g_free (val);
return NULL;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new_checked (tklass, alen, error);
return_val_if_nok (error, NULL);
basetype = m_class_get_byval_arg (tklass)->type;
if (basetype == MONO_TYPE_VALUETYPE && m_class_is_enumtype (tklass))
basetype = mono_class_enum_basetype_internal (tklass)->type;
if (basetype == MONO_TYPE_GENERICINST) {
MonoGenericClass * mgc = m_class_get_byval_arg (tklass)->data.generic_class;
MonoClass * cc = mgc->container_class;
if (m_class_is_enumtype (cc)) {
basetype = m_class_get_byval_arg (m_class_get_element_class (cc))->type;
} else {
g_error ("Unhandled type of generic instance in load_cattr_value: %s[]", m_class_get_name (cc));
}
}
switch (basetype) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MonoBoolean val = *p++;
mono_array_set_internal (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 1, boundp, error))
return NULL;
guint16 val = read16 (p);
mono_array_set_internal (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
guint32 val = read32 (p);
mono_array_set_internal (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
double val;
readr8 (p, &val);
mono_array_set_internal (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
guint64 val = read64 (p);
mono_array_set_internal (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY: {
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_NEW (MonoArray, arr);
for (i = 0; i < alen; i++) {
MonoObject *item = NULL;
load_cattr_value (image, m_class_get_byval_arg (tklass), &item, p, boundp, &p, error);
if (!is_ok (error))
return NULL;
mono_array_setref_internal (arr, i, item);
}
HANDLE_FUNCTION_RETURN ();
break;
}
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end = p;
g_assert (out_obj);
*out_obj = (MonoObject*)arr;
return NULL;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
load_cattr_value_boxed (MonoDomain *domain, MonoImage *image, MonoType *t, const char* p, const char *boundp, const char** end, MonoError *error)
{
error_init (error);
gboolean is_ref = type_is_reference (t);
if (is_ref) {
MonoObject *obj = NULL;
gpointer val = load_cattr_value (image, t, &obj, p, boundp, end, error);
if (!is_ok (error))
return NULL;
g_assert (!val);
return obj;
} else {
void *val = load_cattr_value (image, t, NULL, p, boundp, end, error);
if (!is_ok (error))
return NULL;
MonoObject *boxed = mono_value_box_checked (mono_class_from_mono_type_internal (t), val, error);
g_free (val);
return boxed;
}
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val, MonoError *error)
{
MonoObject *retval;
void *params [2], *unboxed;
error_init (error);
HANDLE_FUNCTION_ENTER ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (mono_class_get_custom_attribute_typed_argument_class (), ".ctor", 2, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
params [0] = mono_type_get_object_checked (t, error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN ((MonoObject*)params [0]);
params [1] = val;
retval = mono_object_new_checked (mono_class_get_custom_attribute_typed_argument_class (), error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN (retval);
unboxed = mono_object_unbox_internal (retval);
mono_runtime_invoke_checked (ctor, unboxed, params, error);
return_val_if_nok (error, NULL);
HANDLE_FUNCTION_RETURN ();
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg, MonoError *error)
{
MonoObject *retval;
void *unboxed, *params [2];
error_init (error);
HANDLE_FUNCTION_ENTER ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (mono_class_get_custom_attribute_named_argument_class (), ".ctor", 2, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new_checked (mono_class_get_custom_attribute_named_argument_class (), error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN (retval);
unboxed = mono_object_unbox_internal (retval);
mono_runtime_invoke_checked (ctor, unboxed, params, error);
return_val_if_nok (error, NULL);
HANDLE_FUNCTION_RETURN ();
return retval;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders_handle (MonoImage *alloc_img, MonoImage *image, MonoArrayHandle cattrs)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!MONO_HANDLE_BOOL (cattrs))
return NULL;
HANDLE_FUNCTION_ENTER ();
/* FIXME: check in assembly the Run flag is set */
MonoReflectionCustomAttrHandle cattr = MONO_HANDLE_NEW (MonoReflectionCustomAttr, NULL);
MonoArrayHandle cattr_data = MONO_HANDLE_NEW (MonoArray, NULL);
MonoReflectionMethodHandle ctor_handle = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
int const count = mono_array_handle_length (cattrs);
MonoMethod *ctor_method = NULL;
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
int count_visible = 0;
for (int i = 0; i < count; ++i) {
MONO_HANDLE_ARRAY_GETREF (cattr, cattrs, i);
count_visible += custom_attr_visible (image, cattr, ctor_handle, &ctor_method);
}
MonoCustomAttrInfo *ainfo;
ainfo = (MonoCustomAttrInfo *)mono_image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count_visible);
ainfo->image = image;
ainfo->num_attrs = count_visible;
ainfo->cached = alloc_img != NULL;
int index = 0;
for (int i = 0; i < count; ++i) {
MONO_HANDLE_ARRAY_GETREF (cattr, cattrs, i);
if (!custom_attr_visible (image, cattr, ctor_handle, &ctor_method))
continue;
if (image_is_dynamic (image))
mono_reflection_resolution_scope_from_image ((MonoDynamicImage *)image->assembly->image, m_class_get_image (ctor_method->klass));
MONO_HANDLE_GET (cattr_data, cattr, data);
unsigned char *saved = (unsigned char *)mono_image_alloc (image, mono_array_handle_length (cattr_data));
MonoGCHandle gchandle = NULL;
memcpy (saved, MONO_ARRAY_HANDLE_PIN (cattr_data, char, 0, &gchandle), mono_array_handle_length (cattr_data));
mono_gchandle_free_internal (gchandle);
ainfo->attrs [index].ctor = ctor_method;
g_assert (ctor_method);
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_handle_length (cattr_data);
index ++;
}
g_assert (index == count_visible);
HANDLE_FUNCTION_RETURN_VAL (ainfo);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray* cattrs)
{
HANDLE_FUNCTION_ENTER ();
MonoCustomAttrInfo* const result = mono_custom_attrs_from_builders_handle (alloc_img, image, MONO_HANDLE_NEW (MonoArray, cattrs));
HANDLE_FUNCTION_RETURN_VAL (result);
}
static void
set_custom_attr_fmt_error (MonoError *error)
{
error_init (error);
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
}
/**
* bcheck_blob:
* \param ptr a pointer into a blob
* \param bump how far we plan on reading past \p ptr.
* \param endp upper bound for \p ptr - one past the last valid value for \p ptr.
* \param error set on error
*
* Check that ptr+bump is below endp. Returns TRUE on success, or FALSE on
* failure and sets \p error.
*/
static gboolean
bcheck_blob (const char *ptr, int bump, const char *endp, MonoError *error)
{
error_init (error);
if (ADDP_IS_GREATER_OR_OVF (ptr, bump, endp - 1)) {
set_custom_attr_fmt_error (error);
return FALSE;
} else
return TRUE;
}
/**
* decode_blob_size_checked:
* \param ptr a pointer into a blob
* \param endp upper bound for \p ptr - one pas the last valid value for \p ptr
* \param size_out on success set to the decoded size
* \param retp on success set to the next byte after the encoded size
* \param error set on error
*
* Decode an encoded size value which takes 1, 2, or 4 bytes and set \p
* size_out to the decoded size and \p retp to the next byte after the encoded
* size. Returns TRUE on success, or FALASE on failure and sets \p error.
*/
static gboolean
decode_blob_size_checked (const char *ptr, const char *endp, guint32 *size_out, const char **retp, MonoError *error)
{
error_init (error);
if (endp && !bcheck_blob (ptr, 0, endp, error))
goto leave;
if ((*ptr & 0x80) != 0) {
if ((*ptr & 0x40) == 0 && !bcheck_blob (ptr, 1, endp, error))
goto leave;
else if (!bcheck_blob (ptr, 3, endp, error))
goto leave;
}
*size_out = mono_metadata_decode_blob_size (ptr, retp);
leave:
return is_ok (error);
}
/**
* decode_blob_value_checked:
* \param ptr a pointer into a blob
* \param endp upper bound for \p ptr - one pas the last valid value for \p ptr
* \param value_out on success set to the decoded value
* \param retp on success set to the next byte after the encoded size
* \param error set on error
*
* Decode an encoded uint32 value which takes 1, 2, or 4 bytes and set \p
* value_out to the decoded value and \p retp to the next byte after the
* encoded value. Returns TRUE on success, or FALASE on failure and sets \p
* error.
*/
static gboolean
decode_blob_value_checked (const char *ptr, const char *endp, guint32 *value_out, const char **retp, MonoError *error)
{
/* This similar to decode_blob_size_checked, above but delegates to
* mono_metadata_decode_value which is semantically different. */
error_init (error);
if (!bcheck_blob (ptr, 0, endp, error))
goto leave;
if ((*ptr & 0x80) != 0) {
if ((*ptr & 0x40) == 0 && !bcheck_blob (ptr, 1, endp, error))
goto leave;
else if (!bcheck_blob (ptr, 3, endp, error))
goto leave;
}
*value_out = mono_metadata_decode_value (ptr, retp);
leave:
return is_ok (error);
}
static MonoObjectHandle
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
const char *p = (const char*)data;
const char *data_end = (const char*)data + len;
const char *named;
guint32 i, j, num_named;
MonoObjectHandle attr = NULL_HANDLE;
void *params_buf [32];
void **params = NULL;
MonoMethodSignature *sig;
MonoClassField *field = NULL;
char *name = NULL;
void *pparams [1] = { NULL };
MonoType *prop_type = NULL;
void *val = NULL; // FIXMEcoop is this a raw pointer or a value?
error_init (error);
mono_class_init_internal (method->klass);
if (len == 0) {
attr = mono_object_new_handle (method->klass, error);
goto_if_nok (error, fail);
mono_runtime_invoke_handle_void (method, attr, NULL, error);
goto_if_nok (error, fail);
goto exit;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
goto fail;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature_internal (method);
if (sig->param_count < 32) {
params = params_buf;
memset (params, 0, sizeof (void*) * sig->param_count);
} else {
/* Allocate using GC so it gets GC tracking */
params = (void **)mono_gc_alloc_fixed (sig->param_count * sizeof (void*), MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_REFLECTION, NULL, "Reflection Custom Attribute Parameters");
}
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature_internal (method)->param_count; ++i) {
MonoObject *param_obj;
params [i] = load_cattr_value (image, mono_method_signature_internal (method)->params [i], ¶m_obj, p, data_end, &p, error);
if (param_obj)
params [i] = param_obj;
goto_if_nok (error, fail);
}
named = p;
attr = mono_object_new_handle (method->klass, error);
goto_if_nok (error, fail);
(void)mono_runtime_try_invoke_handle (method, attr, params, error);
goto_if_nok (error, fail);
if (named + 1 < data_end) {
num_named = read16 (named);
named += 2;
} else {
/* CoreCLR allows p == data + len */
if (named == data_end)
num_named = 0;
else {
set_custom_attr_fmt_error (error);
goto fail;
}
}
for (j = 0; j < num_named; j++) {
guint32 name_len;
char named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
goto fail;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
goto fail;
if (type_len > 0 && !bcheck_blob (named, type_len - 1, data_end, error))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
if (!decode_blob_size_checked (named, data_end, &name_len, &named, error))
goto fail;
if (name_len > 0 && !bcheck_blob (named, name_len - 1, data_end, error))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* how this fail is a blackbox */
field = mono_class_get_field_from_name_full (mono_handle_class (attr), name, NULL);
if (!field) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find a field with name %s", name);
goto fail;
}
MonoObject *param_obj;
val = load_cattr_value (image, field->type, ¶m_obj, named, data_end, &named, error);
if (param_obj)
val = param_obj;
goto_if_nok (error, fail);
mono_field_set_value_internal (MONO_HANDLE_RAW (attr), field, val); // FIXMEcoop
} else if (named_type == CATTR_TYPE_PROPERTY) {
MonoProperty *prop;
prop = mono_class_get_property_from_name_internal (mono_handle_class (attr), name);
if (!prop) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find a property with name %s", name);
goto fail;
}
if (!prop->set) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find the setter for %s", name);
goto fail;
}
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
MonoObject *param_obj;
pparams [0] = load_cattr_value (image, prop_type, ¶m_obj, named, data_end, &named, error);
if (param_obj)
pparams [0] = param_obj;
goto_if_nok (error, fail);
mono_property_set_value_handle (prop, attr, pparams, error);
goto_if_nok (error, fail);
}
g_free (name);
name = NULL;
}
goto exit;
fail:
g_free (name);
name = NULL;
attr = mono_new_null ();
exit:
if (field && !type_is_reference (field->type))
g_free (val);
if (prop_type && !type_is_reference (prop_type))
g_free (pparams [0]);
if (params) {
free_param_data (method->signature, params);
if (params != params_buf)
mono_gc_free_fixed (params);
}
HANDLE_FUNCTION_RETURN_REF (MonoObject, attr);
}
static void
create_custom_attr_into_array (MonoImage *image, MonoMethod *method, const guchar *data,
guint32 len, MonoArrayHandle array, int index, MonoError *error)
{
// This function serves to avoid creating handles in a loop.
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle attr = create_custom_attr (image, method, data, len, error);
MONO_HANDLE_ARRAY_SETREF (array, index, attr);
HANDLE_FUNCTION_RETURN ();
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArrayHandleOut typed_args_h, MonoArrayHandleOut named_args_h, CattrNamedArg **named_arg_info, MonoError *error)
{
MonoArray *typed_args, *named_args;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *data_end = p + len;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
MONO_HANDLE_ASSIGN_RAW (typed_args_h, NULL);
MONO_HANDLE_ASSIGN_RAW (named_args_h, NULL);
*named_arg_info = NULL;
typed_args = NULL;
named_args = NULL;
error_init (error);
mono_class_init_internal (method->klass);
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
/* skip prolog */
p += 2;
/* Parse each argument corresponding to the signature's parameters from
* the blob and store in typed_args.
*/
typed_args = mono_array_new_checked (mono_get_object_class (), mono_method_signature_internal (method)->param_count, error);
return_if_nok (error);
MONO_HANDLE_ASSIGN_RAW (typed_args_h, typed_args);
for (i = 0; i < mono_method_signature_internal (method)->param_count; ++i) {
MonoObject *obj;
obj = load_cattr_value_boxed (domain, image, mono_method_signature_internal (method)->params [i], p, data_end, &p, error);
return_if_nok (error);
mono_array_setref_internal (typed_args, i, obj);
}
named = p;
/* Parse mandatory count of named arguments (could be zero) */
if (!bcheck_blob (named, 1, data_end, error))
return;
num_named = read16 (named);
named_args = mono_array_new_checked (mono_get_object_class (), num_named, error);
return_if_nok (error);
MONO_HANDLE_ASSIGN_RAW (named_args_h, named_args);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
/* Parse each named arg, and add to arginfo. Each named argument could
* be a field name or a property name followed by a value. */
for (j = 0; j < num_named; j++) {
guint32 name_len;
char *name, named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
return;
named_type = *named++; /* field or property? */
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
return;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
return;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, type_len, data + len))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
/* named argument name: length, then name */
if (!decode_blob_size_checked(named, data_end, &name_len, &named, error))
return;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, name_len, data + len))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* Named arg is a field. */
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name_full (attrklass, name, NULL);
if (!field) {
g_free (name);
goto fail;
}
arginfo [j].type = field->type;
arginfo [j].field = field;
obj = load_cattr_value_boxed (domain, image, field->type, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
return;
}
mono_array_setref_internal (named_args, j, obj);
} else if (named_type == CATTR_TYPE_PROPERTY) {
/* Named arg is a property */
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name_internal (attrklass, name);
if (!prop || !prop->set) {
g_free (name);
goto fail;
}
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
obj = load_cattr_value_boxed (domain, image, prop_type, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
return;
}
mono_array_setref_internal (named_args, j, obj);
}
g_free (name);
}
return;
fail:
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
g_free (arginfo);
*named_arg_info = NULL;
}
/*
* mono_reflection_create_custom_attr_data_args_noalloc:
*
* Same as mono_reflection_create_custom_attr_data_args but allocate no managed objects, return values
* using C arrays. Only usable for cattrs with primitive/type/string arguments.
* For types, a MonoType* is returned.
* For strings, the address in the metadata blob is returned.
* TYPED_ARGS, NAMED_ARGS, and NAMED_ARG_INFO should be freed using g_free ().
*/
void
mono_reflection_create_custom_attr_data_args_noalloc (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len,
gpointer **typed_args_out, gpointer **named_args_out, int *num_named_args,
CattrNamedArg **named_arg_info, MonoError *error)
{
gpointer *typed_args, *named_args;
MonoClass *attrklass;
const char *p = (const char*)data;
const char *data_end = p + len;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
MonoMethodSignature *sig = mono_method_signature_internal (method);
*typed_args_out = NULL;
*named_args_out = NULL;
*named_arg_info = NULL;
typed_args = NULL;
named_args = NULL;
error_init (error);
mono_class_init_internal (method->klass);
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
goto fail;
/* skip prolog */
p += 2;
typed_args = g_new0 (gpointer, sig->param_count);
for (i = 0; i < sig->param_count; ++i) {
typed_args [i] = load_cattr_value (image, sig->params [i], NULL, p, data_end, &p, error);
return_if_nok (error);
}
named = p;
/* Parse mandatory count of named arguments (could be zero) */
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
num_named = read16 (named);
named_args = g_new0 (gpointer, num_named);
return_if_nok (error);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
*num_named_args = num_named;
/* Parse each named arg, and add to arginfo. Each named argument could
* be a field name or a property name followed by a value. */
for (j = 0; j < num_named; j++) {
guint32 name_len;
char *name, named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
named_type = *named++; /* field or property? */
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
goto fail;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
goto fail;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, type_len, data + len))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
/* named argument name: length, then name */
if (!decode_blob_size_checked(named, data_end, &name_len, &named, error))
goto fail;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, name_len, data + len))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* Named arg is a field. */
MonoClassField *field = mono_class_get_field_from_name_full (attrklass, name, NULL);
if (!field) {
g_free (name);
goto fail;
}
arginfo [j].type = field->type;
arginfo [j].field = field;
named_args [j] = load_cattr_value (image, field->type, NULL, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
goto fail;
}
} else if (named_type == CATTR_TYPE_PROPERTY) {
/* Named arg is a property */
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name_internal (attrklass, name);
if (!prop || !prop->set) {
g_free (name);
goto fail;
}
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
named_args [j] = load_cattr_value (image, prop_type, NULL, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
goto fail;
}
}
g_free (name);
}
*typed_args_out = typed_args;
*named_args_out = named_args;
return;
fail:
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
g_free (typed_args);
g_free (named_args);
g_free (arginfo);
*named_arg_info = NULL;
}
void
ves_icall_System_Reflection_RuntimeCustomAttributeData_ResolveArgumentsInternal (MonoReflectionMethodHandle ref_method_h, MonoReflectionAssemblyHandle assembly_h,
gpointer data, guint32 len,
MonoArrayHandleOut ctor_args_h, MonoArrayHandleOut named_args_h,
MonoError *error)
{
MonoArray *typed_args, *named_args;
MonoImage *image;
MonoMethod *method;
CattrNamedArg *arginfo = NULL;
MonoReflectionMethod *ref_method = MONO_HANDLE_RAW (ref_method_h);
MonoReflectionAssembly *assembly = MONO_HANDLE_RAW (assembly_h);
MonoMethodSignature *sig;
MonoObjectHandle obj_h, namedarg_h, minfo_h;
int i;
if (len == 0)
return;
obj_h = MONO_HANDLE_NEW (MonoObject, NULL);
namedarg_h = MONO_HANDLE_NEW (MonoObject, NULL);
minfo_h = MONO_HANDLE_NEW (MonoObject, NULL);
image = assembly->assembly->image;
method = ref_method->method;
if (!mono_class_init_internal (method->klass)) {
mono_error_set_for_class_failure (error, method->klass);
goto leave;
}
// FIXME: Handles
mono_reflection_create_custom_attr_data_args (image, method, (const guchar *)data, len, ctor_args_h, named_args_h, &arginfo, error);
goto_if_nok (error, leave);
typed_args = MONO_HANDLE_RAW (ctor_args_h);
named_args = MONO_HANDLE_RAW (named_args_h);
if (!typed_args || !named_args)
goto leave;
sig = mono_method_signature_internal (method);
for (i = 0; i < sig->param_count; ++i) {
MonoObject *obj;
MonoObject *typedarg;
MonoType *t;
obj = mono_array_get_internal (typed_args, MonoObject*, i);
MONO_HANDLE_ASSIGN_RAW (obj_h, obj);
t = sig->params [i];
if (t->type == MONO_TYPE_OBJECT && obj)
t = m_class_get_byval_arg (obj->vtable->klass);
typedarg = create_cattr_typed_arg (t, obj, error);
goto_if_nok (error, leave);
mono_array_setref_internal (typed_args, i, typedarg);
}
for (i = 0; i < mono_array_length_internal (named_args); ++i) {
MonoObject *obj;
MonoObject *namedarg, *minfo;
obj = mono_array_get_internal (named_args, MonoObject*, i);
MONO_HANDLE_ASSIGN_RAW (obj_h, obj);
if (arginfo [i].prop) {
minfo = (MonoObject*)mono_property_get_object_checked (arginfo [i].prop->parent, arginfo [i].prop, error);
if (!minfo)
goto leave;
} else {
minfo = (MonoObject*)mono_field_get_object_checked (NULL, arginfo [i].field, error);
goto_if_nok (error, leave);
}
MONO_HANDLE_ASSIGN_RAW (minfo_h, minfo);
namedarg = create_cattr_named_arg (minfo, obj, error);
MONO_HANDLE_ASSIGN_RAW (namedarg_h, namedarg);
goto_if_nok (error, leave);
mono_array_setref_internal (named_args, i, namedarg);
}
leave:
g_free (arginfo);
}
static MonoClass*
try_get_cattr_data_class (MonoError* error)
{
error_init (error);
MonoClass *res = mono_class_try_get_customattribute_data_class ();
if (!res)
mono_error_set_execution_engine (error, "Class System.Reflection.RuntimeCustomAttributeData not found, probably removed by the linker");
return res;
}
static MonoObjectHandle
create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
static MonoMethod *ctor;
void *params [4];
error_init (error);
g_assert (image->assembly);
MonoObjectHandle attr;
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, result_null);
if (!ctor) {
MonoMethod *tmp = mono_class_get_method_from_name_checked (cattr_data, ".ctor", 4, 0, error);
mono_error_assert_ok (error);
g_assert (tmp);
mono_memory_barrier (); //safe publish!
ctor = tmp;
}
attr = mono_object_new_handle (cattr_data, error);
goto_if_nok (error, fail);
MonoReflectionMethodHandle ctor_obj;
ctor_obj = mono_method_get_object_handle (cattr->ctor, NULL, error);
goto_if_nok (error, fail);
MonoReflectionAssemblyHandle assm;
assm = mono_assembly_get_object_handle (image->assembly, error);
goto_if_nok (error, fail);
params [0] = MONO_HANDLE_RAW (ctor_obj);
params [1] = MONO_HANDLE_RAW (assm);
params [2] = &cattr->data;
params [3] = &cattr->data_size;
mono_runtime_invoke_handle_void (ctor, attr, params, error);
goto fail;
result_null:
attr = MONO_HANDLE_CAST (MonoObject, mono_new_null ());
fail:
HANDLE_FUNCTION_RETURN_REF (MonoObject, attr);
}
static void
create_custom_attr_data_into_array (MonoImage *image, MonoCustomAttrEntry *cattr, MonoArrayHandle result, int index, MonoError *error)
{
// This function serves to avoid creating handles in a loop.
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle attr = create_custom_attr_data (image, cattr, error);
goto_if_nok (error, exit);
MONO_HANDLE_ARRAY_SETREF (result, index, attr);
exit:
HANDLE_FUNCTION_RETURN ();
}
static MonoArrayHandle
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle result;
int i, n;
error_init (error);
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &cinfo->attrs[i];
if (!centry->ctor) {
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_error_set_type_load_name (error, NULL, NULL, "Custom attribute constructor is null because the custom attribute type is not finished yet.");
goto return_null;
}
}
n = 0;
if (attr_klass) {
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoMethod *ctor = cinfo->attrs[i].ctor;
g_assert (ctor);
if (mono_class_is_assignable_from_internal (attr_klass, ctor->klass))
n++;
}
} else {
n = cinfo->num_attrs;
}
result = mono_array_new_cached_handle (mono_defaults.attribute_class, n, error);
goto_if_nok (error, return_null);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &cinfo->attrs [i];
if (!attr_klass || mono_class_is_assignable_from_internal (attr_klass, centry->ctor->klass)) {
create_custom_attr_into_array (cinfo->image, centry->ctor, centry->data,
centry->data_size, result, n, error);
goto_if_nok (error, exit);
n ++;
}
}
goto exit;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
exit:
HANDLE_FUNCTION_RETURN_REF (MonoArray, result);
}
/**
* mono_custom_attrs_construct:
*/
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoArrayHandle result = mono_custom_attrs_construct_by_type (cinfo, NULL, error);
mono_error_assert_ok (error); /*FIXME proper error handling*/
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static MonoArrayHandle
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle result;
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, return_null);
result = mono_array_new_handle (cattr_data, cinfo->num_attrs, error);
goto_if_nok (error, return_null);
for (int i = 0; i < cinfo->num_attrs; ++i) {
create_custom_attr_data_into_array (cinfo->image, &cinfo->attrs [i], result, i, error);
goto_if_nok (error, return_null);
}
goto exit;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
exit:
HANDLE_FUNCTION_RETURN_REF (MonoArray, result);
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_custom_attrs_from_index_checked:
* \returns NULL if no attributes are found. On error returns NULL and sets \p error.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index_checked (MonoImage *image, guint32 idx, gboolean ignore_missing, MonoError *error)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GArray *attr_array;
const char *data;
MonoCustomAttrEntry* attr;
error_init (error);
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
// initial size chosen arbitrarily, but default is 16 which is rather small
attr_array = g_array_sized_new (TRUE, TRUE, sizeof (guint32), 128);
while (!mono_metadata_table_bounds_check (image, MONO_TABLE_CUSTOMATTRIBUTE, i + 1)) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx) {
if (G_LIKELY (!image->has_updates)) {
break;
} else {
// if there are updates, the new custom attributes are not sorted,
// so we have to go until the end.
++i;
continue;
}
}
attr_array = g_array_append_val (attr_array, i);
++i;
}
len = attr_array->len;
if (!len) {
g_array_free (attr_array, TRUE);
return NULL;
}
ainfo = (MonoCustomAttrInfo *)g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0; i < len; ++i) {
mono_metadata_decode_row (ca, g_array_index (attr_array, guint32, i), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
attr = &ainfo->attrs [i];
attr->ctor = mono_get_method_checked (image, mtoken, NULL, NULL, error);
if (!attr->ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x due to: %s", image->name, mtoken, mono_error_get_message (error));
if (ignore_missing) {
mono_error_cleanup (error);
error_init (error);
} else {
g_array_free (attr_array, TRUE);
g_free (ainfo);
return NULL;
}
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
attr->data_size = mono_metadata_decode_value (data, &data);
attr->data = (guchar*)data;
}
g_array_free (attr_array, TRUE);
return ainfo;
}
/**
* mono_custom_attrs_from_method:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
ERROR_DECL (error);
MonoCustomAttrInfo* result = mono_custom_attrs_from_method_checked (method, error);
mono_error_cleanup (error); /* FIXME want a better API that doesn't swallow the error */
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method_checked (MonoMethod *method, MonoError *error)
{
guint32 idx;
error_init (error);
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method_is_dynamic (method) || image_is_dynamic (m_class_get_image (method->klass)))
return lookup_custom_attr (m_class_get_image (method->klass), method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = custom_attrs_idx_from_method (method);
return mono_custom_attrs_from_index_checked (m_class_get_image (method->klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_class:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_class_checked (klass, error);
mono_error_cleanup (error);
return result;
}
guint32
custom_attrs_idx_from_class (MonoClass *klass)
{
guint32 idx;
g_assert (!image_is_dynamic (m_class_get_image (klass)));
if (m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR || m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (m_class_get_sizes (klass).generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (m_class_get_type_token (klass));
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return idx;
}
guint32
custom_attrs_idx_from_method (MonoMethod *method)
{
guint32 idx;
g_assert (!image_is_dynamic (m_class_get_image (method->klass)));
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return idx;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class_checked (MonoClass *klass, MonoError *error)
{
guint32 idx;
error_init (error);
if (mono_class_is_ginst (klass))
klass = mono_class_get_generic_class (klass)->container_class;
if (image_is_dynamic (m_class_get_image (klass)))
return lookup_custom_attr (m_class_get_image (klass), klass);
idx = custom_attrs_idx_from_class (klass);
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_assembly:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_assembly_checked (assembly, FALSE, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly_checked (MonoAssembly *assembly, gboolean ignore_missing, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (assembly->image))
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index_checked (assembly->image, idx, ignore_missing, error);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (image))
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
}
/**
* mono_custom_attrs_from_property:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_property_checked (klass, property, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property_checked (MonoClass *klass, MonoProperty *property, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (m_class_get_image (klass), property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_event:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_event_checked (klass, event, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event_checked (MonoClass *klass, MonoEvent *event, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (m_class_get_image (klass), event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_field:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_field_checked (klass, field, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field_checked (MonoClass *klass, MonoClassField *field, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (m_class_get_image (klass), field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_param:
* \param method handle to the method that we want to retrieve custom parameter information from
* \param param parameter number, where zero represent the return value, and one is the first parameter in the method
*
* The result must be released with mono_custom_attrs_free().
*
* \returns the custom attribute object for the specified parameter, or NULL if there are none.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_param_checked (method, param, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_custom_attrs_from_param_checked:
* \param method handle to the method that we want to retrieve custom parameter information from
* \param param parameter number, where zero represent the return value, and one is the first parameter in the method
* \param error set on error
*
* The result must be released with mono_custom_attrs_free().
*
* \returns the custom attribute object for the specified parameter, or NULL if there are none. On failure returns NULL and sets \p error.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_param_checked (MonoMethod *method, guint32 param, MonoError *error)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
error_init (error);
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (image_is_dynamic (m_class_get_image (method->klass))) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)m_class_get_image (method->klass))->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = (MonoCustomAttrInfo *)g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = m_class_get_image (method->klass);
method_index = mono_method_get_index (method);
if (!method_index)
return NULL;
ca = &image->tables [MONO_TABLE_METHOD];
/* FIXME: metadata-update */
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == table_info_get_rows (ca)) {
param_last = table_info_get_rows (&image->tables [MONO_TABLE_PARAM]) + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
}
ca = &image->tables [MONO_TABLE_PARAM];
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
}
/**
* mono_custom_attrs_has_attr:
*/
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
for (i = 0; i < ainfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &ainfo->attrs[i];
if (centry->ctor == NULL)
continue;
MonoClass *klass = centry->ctor->klass;
if (klass == attr_klass || mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE_INTERNAL (attr_klass) && mono_class_is_assignable_from_internal (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
/**
* mono_custom_attrs_get_attr:
*/
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
ERROR_DECL (error);
MonoObject *res = mono_custom_attrs_get_attr_checked (ainfo, attr_klass, error);
mono_error_assert_ok (error); /*FIXME proper error handling*/
return res;
}
MonoObject*
mono_custom_attrs_get_attr_checked (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass, MonoError *error)
{
int i;
MonoCustomAttrEntry *centry = NULL;
g_assert (attr_klass != NULL);
error_init (error);
for (i = 0; i < ainfo->num_attrs; ++i) {
centry = &ainfo->attrs[i];
if (centry->ctor == NULL)
continue;
MonoClass *klass = centry->ctor->klass;
if (attr_klass == klass || mono_class_is_assignable_from_internal (attr_klass, klass)) {
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle result = create_custom_attr (ainfo->image, centry->ctor, centry->data, centry->data_size, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
}
return NULL;
}
/**
* mono_reflection_get_custom_attrs_info:
* \param obj a reflection object handle
*
* \returns the custom attribute info for attributes defined for the
* reflection handle \p obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoCustomAttrInfo * const result = mono_reflection_get_custom_attrs_info_checked (obj, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/**
* mono_reflection_get_custom_attrs_info_checked:
* \param obj a reflection object handle
* \param error set on error
*
* \returns the custom attribute info for attributes defined for the
* reflection handle \p obj. The objects. On failure returns NULL and sets \p error.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info_checked (MonoObjectHandle obj, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
error_init (error);
klass = mono_handle_class (obj);
const char *klass_name = m_class_get_name (klass);
if (klass == mono_defaults.runtimetype_class) {
MonoType *type = mono_reflection_type_handle_mono_type (MONO_HANDLE_CAST(MonoReflectionType, obj), error);
goto_if_nok (error, leave);
klass = mono_class_from_mono_type_internal (type);
/*We cannot mono_class_init_internal the class from which we'll load the custom attributes since this must work with broken types.*/
cinfo = mono_custom_attrs_from_class_checked (klass, error);
goto_if_nok (error, leave);
} else if (strcmp ("Assembly", klass_name) == 0 || strcmp ("RuntimeAssembly", klass_name) == 0) {
MonoReflectionAssemblyHandle rassembly = MONO_HANDLE_CAST (MonoReflectionAssembly, obj);
cinfo = mono_custom_attrs_from_assembly_checked (MONO_HANDLE_GETVAL (rassembly, assembly), FALSE, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeModule", klass_name) == 0) {
MonoReflectionModuleHandle module = MONO_HANDLE_CAST (MonoReflectionModule, obj);
cinfo = mono_custom_attrs_from_module (MONO_HANDLE_GETVAL (module, image), error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimePropertyInfo", klass_name) == 0) {
MonoReflectionPropertyHandle rprop = MONO_HANDLE_CAST (MonoReflectionProperty, obj);
MonoProperty *property = MONO_HANDLE_GETVAL (rprop, property);
cinfo = mono_custom_attrs_from_property_checked (property->parent, property, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeEventInfo", klass_name) == 0) {
MonoReflectionMonoEventHandle revent = MONO_HANDLE_CAST (MonoReflectionMonoEvent, obj);
MonoEvent *event = MONO_HANDLE_GETVAL (revent, event);
cinfo = mono_custom_attrs_from_event_checked (event->parent, event, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeFieldInfo", klass_name) == 0) {
MonoReflectionFieldHandle rfield = MONO_HANDLE_CAST (MonoReflectionField, obj);
MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
cinfo = mono_custom_attrs_from_field_checked (m_field_get_parent (field), field, error);
goto_if_nok (error, leave);
} else if ((strcmp ("RuntimeMethodInfo", klass_name) == 0) || (strcmp ("RuntimeConstructorInfo", klass_name) == 0)) {
MonoReflectionMethodHandle rmethod = MONO_HANDLE_CAST (MonoReflectionMethod, obj);
cinfo = mono_custom_attrs_from_method_checked (MONO_HANDLE_GETVAL (rmethod, method), error);
goto_if_nok (error, leave);
} else if (strcmp ("ParameterInfo", klass_name) == 0 || strcmp ("RuntimeParameterInfo", klass_name) == 0) {
MonoReflectionParameterHandle param = MONO_HANDLE_CAST (MonoReflectionParameter, obj);
MonoObjectHandle member_impl = MONO_HANDLE_NEW (MonoObject, NULL);
int position;
mono_reflection_get_param_info_member_and_pos (param, member_impl, &position);
MonoClass *member_class = mono_handle_class (member_impl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethodHandle rmethod = MONO_HANDLE_CAST (MonoReflectionMethod, member_impl);
cinfo = mono_custom_attrs_from_param_checked (MONO_HANDLE_GETVAL (rmethod, method), position + 1, error);
goto_if_nok (error, leave);
} else if (mono_is_sr_mono_property (member_class)) {
MonoReflectionPropertyHandle prop = MONO_HANDLE_CAST (MonoReflectionProperty, member_impl);
MonoProperty *property = MONO_HANDLE_GETVAL (prop, property);
MonoMethod *method;
if (!(method = property->get))
method = property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param_checked (method, position + 1, error);
goto_if_nok (error, leave);
}
#ifndef DISABLE_REFLECTION_EMIT
else if (mono_is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
// FIXME: Is this still needed ?
g_assert_not_reached ();
} else if (mono_is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
// FIXME: Is this still needed ?
g_assert_not_reached ();
}
#endif
else {
char *type_name = mono_type_get_full_name (member_class);
mono_error_set_not_supported (error,
"Custom attributes on a ParamInfo with member %s are not supported",
type_name);
g_free (type_name);
goto leave;
}
} else if (strcmp ("AssemblyBuilder", klass_name) == 0) {
MonoReflectionAssemblyBuilderHandle assemblyb = MONO_HANDLE_CAST (MonoReflectionAssemblyBuilder, obj);
MonoReflectionAssemblyHandle assembly = MONO_HANDLE_CAST (MonoReflectionAssembly, assemblyb);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, assemblyb, cattrs);
MonoImage * image = MONO_HANDLE_GETVAL (assembly, assembly)->image;
g_assert (image);
cinfo = mono_custom_attrs_from_builders_handle (NULL, image, cattrs);
} else if (strcmp ("TypeBuilder", klass_name) == 0) {
MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, obj);
MonoReflectionModuleBuilderHandle module = MONO_HANDLE_NEW_GET (MonoReflectionModuleBuilder, tb, module);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (module, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, tb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("ModuleBuilder", klass_name) == 0) {
MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionModuleBuilder, obj);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, mb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("ConstructorBuilder", klass_name) == 0) {
mono_error_set_not_supported (error, "");
goto leave;
} else if (strcmp ("MethodBuilder", klass_name) == 0) {
MonoReflectionMethodBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionMethodBuilder, obj);
MonoMethod *mhandle = MONO_HANDLE_GETVAL (mb, mhandle);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, mb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, m_class_get_image (mhandle->klass), cattrs);
} else if (strcmp ("FieldBuilder", klass_name) == 0) {
MonoReflectionFieldBuilderHandle fb = MONO_HANDLE_CAST (MonoReflectionFieldBuilder, obj);
MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, MONO_HANDLE_NEW_GET (MonoReflectionType, fb, typeb));
MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW_GET (MonoReflectionModuleBuilder, tb, module);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, fb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("MonoGenericClass", klass_name) == 0) {
MonoReflectionGenericClassHandle gclass = MONO_HANDLE_CAST (MonoReflectionGenericClass, obj);
MonoReflectionTypeHandle generic_type = MONO_HANDLE_NEW_GET (MonoReflectionType, gclass, generic_type);
cinfo = mono_reflection_get_custom_attrs_info_checked (MONO_HANDLE_CAST (MonoObject, generic_type), error);
goto_if_nok (error, leave);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", m_class_get_name (klass));
}
leave:
HANDLE_FUNCTION_RETURN_VAL (cinfo);
}
/**
* mono_reflection_get_custom_attrs_by_type:
* \param obj a reflection object handle
* \returns an array with all the custom attributes defined of the
* reflection handle \p obj. If \p attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj_raw, MonoClass *attr_klass, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_by_type_handle (obj, attr_klass, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
MonoArrayHandle
mono_reflection_get_custom_attrs_by_type_handle (MonoObjectHandle obj, MonoClass *attr_klass, MonoError *error)
{
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
MonoCustomAttrInfo *cinfo;
error_init (error);
cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
goto_if_nok (error, leave);
if (cinfo) {
MONO_HANDLE_ASSIGN (result, mono_custom_attrs_construct_by_type (cinfo, attr_klass, error));
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
MONO_HANDLE_ASSIGN (result, mono_array_new_handle (mono_defaults.attribute_class, 0, error));
}
leave:
return result;
}
/**
* mono_reflection_get_custom_attrs:
* \param obj a reflection object handle
* \return an array with all the custom attributes defined of the
* reflection handle \p obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_by_type_handle (obj, NULL, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_reflection_get_custom_attrs_data:
* \param obj a reflection obj handle
* \returns an array of \c System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_data_checked (obj, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/*
* mono_reflection_get_custom_attrs_data_checked:
* @obj: a reflection obj handle
* @error: set on error
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArrayHandle
mono_reflection_get_custom_attrs_data_checked (MonoObjectHandle obj, MonoError *error)
{
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
goto_if_nok (error, leave);
if (cinfo) {
MONO_HANDLE_ASSIGN (result, mono_custom_attrs_data_construct (cinfo, error));
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
goto_if_nok (error, leave);
} else {
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, return_null);
MONO_HANDLE_ASSIGN (result, mono_array_new_handle (cattr_data, 0, error));
}
goto leave;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
leave:
return result;
}
static gboolean
custom_attr_class_name_from_methoddef (MonoImage *image, guint32 method_token, const gchar **nspace, const gchar **class_name)
{
/* mono_get_method_from_token () */
g_assert (mono_metadata_token_table (method_token) == MONO_TABLE_METHOD);
guint32 type_token = mono_metadata_typedef_from_method (image, method_token);
if (!type_token) {
/* Bad method token (could not find corresponding typedef) */
return FALSE;
}
type_token |= MONO_TOKEN_TYPE_DEF;
{
/* mono_class_create_from_typedef () */
MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
guint32 cols [MONO_TYPEDEF_SIZE];
guint tidx = mono_metadata_token_index (type_token);
if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || mono_metadata_table_bounds_check (image, MONO_TABLE_TYPEDEF, tidx)) {
/* "Invalid typedef token %x", type_token */
return FALSE;
}
mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
if (class_name)
*class_name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
if (nspace)
*nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
return TRUE;
}
}
/**
* custom_attr_class_name_from_method_token:
* @image: The MonoImage
* @method_token: a token for a custom attr constructor in @image
* @assembly_token: out argument set to the assembly ref token of the custom attr
* @nspace: out argument set to namespace (a string in the string heap of @image) of the custom attr
* @class_name: out argument set to the class name of the custom attr.
*
* Given an @image and a @method_token (which is assumed to be a
* constructor), fills in the out arguments with the assembly ref (if
* a methodref) and the namespace and class name of the custom
* attribute.
*
* Returns: TRUE on success, FALSE otherwise.
*
* LOCKING: does not take locks
*/
static gboolean
custom_attr_class_name_from_method_token (MonoImage *image, guint32 method_token, guint32 *assembly_token, const gchar **nspace, const gchar **class_name)
{
/* This only works with method tokens constructed from a
* custom attr token, which can only be methoddef or
* memberref */
g_assert (mono_metadata_token_table (method_token) == MONO_TABLE_METHOD
|| mono_metadata_token_table (method_token) == MONO_TABLE_MEMBERREF);
if (mono_metadata_token_table (method_token) == MONO_TABLE_MEMBERREF) {
/* method_from_memberref () */
guint32 cols[6];
guint32 nindex, class_index;
int idx = mono_metadata_token_index (method_token);
mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
if (class_index == MONO_MEMBERREF_PARENT_TYPEREF) {
guint32 type_token = MONO_TOKEN_TYPE_REF | nindex;
/* mono_class_from_typeref_checked () */
{
guint32 cols [MONO_TYPEREF_SIZE];
MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
if (class_name)
*class_name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
if (nspace)
*nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
if (assembly_token)
*assembly_token = cols [MONO_TYPEREF_SCOPE];
return TRUE;
}
} else if (class_index == MONO_MEMBERREF_PARENT_METHODDEF) {
guint32 methoddef_token = MONO_TOKEN_METHOD_DEF | nindex;
if (assembly_token)
*assembly_token = 0;
return custom_attr_class_name_from_methoddef (image, methoddef_token, nspace, class_name);
} else {
/* Attributes can't be generic, so it won't be
* a typespec, and they're always
* constructors, so it won't be a moduleref */
g_assert_not_reached ();
}
} else {
/* must be MONO_TABLE_METHOD */
if (assembly_token)
*assembly_token = 0;
return custom_attr_class_name_from_methoddef (image, method_token, nspace, class_name);
}
}
/**
* mono_assembly_metadata_foreach_custom_attr:
* \param assembly the assembly to iterate over
* \param func the function to call for each custom attribute
* \param user_data passed to \p func
* Calls \p func for each custom attribute type on the given assembly until \p func returns TRUE.
* Everything is done using low-level metadata APIs, so it is safe to use during assembly loading.
*/
void
mono_assembly_metadata_foreach_custom_attr (MonoAssembly *assembly, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
MonoImage *image;
guint32 idx;
/*
* This might be called during assembly loading, so do everything using the low-level
* metadata APIs.
*/
image = assembly->image;
/* Dynamic images would need to go through the AssemblyBuilder's
* CustomAttributeBuilder array. Going through the tables below
* definitely won't work. */
g_assert (!image_is_dynamic (image));
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
/**
* iterate over the custom attributes that belong to the given index and call func, passing the
* assembly ref (if any) and the namespace and name of the custom attribute.
*
* Everything is done using low-level metadata APIs, so it is safe to use
* during assembly loading and class initialization.
*/
void
metadata_foreach_custom_attr_from_index (MonoImage *image, guint32 idx, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
guint32 mtoken, i;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
/* Inlined from mono_custom_attrs_from_index_checked () */
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return;
i --;
gboolean stop_iterating = FALSE;
int rows = table_info_get_rows (ca);
while (!stop_iterating && i < rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
mono_metadata_decode_row (ca, i, cols, MONO_CUSTOM_ATTR_SIZE);
i ++;
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_warning ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
continue;
}
const char *nspace = NULL;
const char *name = NULL;
guint32 assembly_token = 0;
if (!custom_attr_class_name_from_method_token (image, mtoken, &assembly_token, &nspace, &name))
continue;
stop_iterating = func (image, assembly_token, nspace, name, mtoken, user_data);
}
}
/**
* mono_class_metadata_foreach_custom_attr:
* \param klass - the class to iterate over
* \param func the funciton to call for each custom attribute
* \param user_data passed to \p func
*
* Calls \p func for each custom attribute type on the given class until \p func returns TRUE.
*
* Everything is done using low-level metadata APIs, so it is fafe to use
* during assembly loading and class initialization.
*
* The MonoClass \p klass should have the following fields initialized:
*
* \c MonoClass:kind, \c MonoClass:image, \c MonoClassGenericInst:generic_class,
* \c MonoClass:type_token, \c MonoClass:sizes.generic_param_token, MonoClass:byval_arg
*/
void
mono_class_metadata_foreach_custom_attr (MonoClass *klass, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
MonoImage *image = m_class_get_image (klass);
/* dynamic images don't store custom attributes in tables */
g_assert (!image_is_dynamic (image));
if (mono_class_is_ginst (klass))
klass = mono_class_get_generic_class (klass)->container_class;
guint32 idx = custom_attrs_idx_from_class (klass);
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
/**
* mono_method_metadata_foreach_custom_attr:
* \param method - the method to iterate over
* \param func the funciton to call for each custom attribute
* \param user_data passed to \p func
*
* Calls \p func for each custom attribute type on the given class until \p func returns TRUE.
*
* Everything is done using low-level metadata APIs, so it is fafe to use
* during assembly loading and class initialization.
*
*/
void
mono_method_metadata_foreach_custom_attr (MonoMethod *method, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
MonoImage *image = m_class_get_image (method->klass);
g_assert (!image_is_dynamic (image));
if (!method->token)
return;
guint32 idx = custom_attrs_idx_from_method (method);
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
static void
init_weak_fields_inner (MonoImage *image, GHashTable *indexes)
{
MonoTableInfo *tdef;
ERROR_DECL (error);
MonoClass *klass = NULL;
guint32 memberref_index = -1;
int first_method_idx = -1;
int method_count = -1;
if (image == mono_get_corlib ()) {
/* Typedef */
klass = mono_class_from_name_checked (image, "System", "WeakAttribute", error);
if (!is_ok (error)) {
mono_error_cleanup (error);
return;
}
if (!klass)
return;
first_method_idx = mono_class_get_first_method_idx (klass);
method_count = mono_class_get_method_count (klass);
tdef = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
guint32 parent, field_idx, col, mtoken, idx;
int rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
parent = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_PARENT);
if ((parent & MONO_CUSTOM_ATTR_MASK) != MONO_CUSTOM_ATTR_FIELDDEF)
continue;
col = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_TYPE);
mtoken = col >> MONO_CUSTOM_ATTR_TYPE_BITS;
/* 1 based index */
idx = mtoken - 1;
if ((col & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
field_idx = parent >> MONO_CUSTOM_ATTR_BITS;
if (idx >= first_method_idx && idx < first_method_idx + method_count)
g_hash_table_insert (indexes, GUINT_TO_POINTER (field_idx), GUINT_TO_POINTER (1));
}
}
} else {
/* FIXME: metadata-update */
/* Memberref pointing to a typeref */
tdef = &image->tables [MONO_TABLE_MEMBERREF];
/* Check whenever the assembly references the WeakAttribute type */
gboolean found = FALSE;
tdef = &image->tables [MONO_TABLE_TYPEREF];
int rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
guint32 string_offset = mono_metadata_decode_row_col (tdef, i, MONO_TYPEREF_NAME);
const char *name = mono_metadata_string_heap (image, string_offset);
if (!strcmp (name, "WeakAttribute")) {
found = TRUE;
break;
}
}
if (!found)
return;
/* Find the memberref pointing to a typeref */
tdef = &image->tables [MONO_TABLE_MEMBERREF];
rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
guint32 cols [MONO_MEMBERREF_SIZE];
const char *sig;
mono_metadata_decode_row (tdef, i, cols, MONO_MEMBERREF_SIZE);
sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
mono_metadata_decode_blob_size (sig, &sig);
guint32 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
guint32 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
if (!strcmp (fname, ".ctor") && class_index == MONO_MEMBERREF_PARENT_TYPEREF) {
MonoTableInfo *typeref_table = &image->tables [MONO_TABLE_TYPEREF];
guint32 cols [MONO_TYPEREF_SIZE];
mono_metadata_decode_row (typeref_table, nindex - 1, cols, MONO_TYPEREF_SIZE);
const char *name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
const char *nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
if (!strcmp (nspace, "System") && !strcmp (name, "WeakAttribute")) {
MonoClass *klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
return;
}
g_assert (!strcmp (m_class_get_name (klass), "WeakAttribute"));
/* Allow a testing dll as well since some profiles don't have WeakAttribute */
if (klass && (m_class_get_image (klass) == mono_get_corlib () || strstr (m_class_get_image (klass)->name, "Mono.Runtime.Testing"))) {
/* Sanity check that it only has 1 ctor */
gpointer iter = NULL;
int count = 0;
MonoMethod *method;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, ".ctor"))
count ++;
}
count ++;
memberref_index = i;
break;
}
}
}
}
if (memberref_index == -1)
return;
tdef = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
guint32 parent, field_idx, col, mtoken, idx;
rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
parent = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_PARENT);
if ((parent & MONO_CUSTOM_ATTR_MASK) != MONO_CUSTOM_ATTR_FIELDDEF)
continue;
col = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_TYPE);
mtoken = col >> MONO_CUSTOM_ATTR_TYPE_BITS;
/* 1 based index */
idx = mtoken - 1;
field_idx = parent >> MONO_CUSTOM_ATTR_BITS;
if ((col & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_MEMBERREF) {
if (idx == memberref_index)
g_hash_table_insert (indexes, GUINT_TO_POINTER (field_idx), GUINT_TO_POINTER (1));
}
}
}
}
/*
* mono_assembly_init_weak_fields:
*
* Initialize the image->weak_field_indexes hash.
*/
void
mono_assembly_init_weak_fields (MonoImage *image)
{
if (image->weak_fields_inited)
return;
GHashTable *indexes = NULL;
if (mono_get_runtime_callbacks ()->get_weak_field_indexes)
indexes = mono_get_runtime_callbacks ()->get_weak_field_indexes (image);
if (!indexes) {
indexes = g_hash_table_new (NULL, NULL);
/*
* To avoid lookups for every field, we scan the customattr table for entries whose
* parent is a field and whose type is WeakAttribute.
*/
init_weak_fields_inner (image, indexes);
}
mono_image_lock (image);
if (!image->weak_fields_inited) {
image->weak_field_indexes = indexes;
mono_memory_barrier ();
image->weak_fields_inited = TRUE;
} else {
g_hash_table_destroy (indexes);
}
mono_image_unlock (image);
}
/*
* mono_assembly_is_weak_field:
*
* Return whenever the FIELD table entry with the 1-based index FIELD_IDX has
* a [Weak] attribute.
*/
gboolean
mono_assembly_is_weak_field (MonoImage *image, guint32 field_idx)
{
if (image->dynamic)
return FALSE;
mono_assembly_init_weak_fields (image);
/* The hash is not mutated, no need to lock */
return g_hash_table_lookup (image->weak_field_indexes, GINT_TO_POINTER (field_idx)) != NULL;
}
| /**
* \file
* Custom attributes.
*
* Author:
* Paolo Molaro ([email protected])
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2011 Rodrigo Kumpera
* Copyright 2016 Microsoft
*
* 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/class-init.h"
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internals.h"
#include "mono/metadata/mono-endian.h"
#include "mono/metadata/object-internals.h"
#include "mono/metadata/custom-attrs-internals.h"
#include "mono/metadata/sre-internals.h"
#include "mono/metadata/reflection-internals.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/icall-decl.h"
#include "mono/metadata/metadata-update.h"
#include "mono/utils/checked-build.h"
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
#define CATTR_TYPE_SYSTEM_TYPE 0x50
#define CATTR_BOXED_VALUETYPE_PREFIX 0x51
#define CATTR_TYPE_FIELD 0x53
#define CATTR_TYPE_PROPERTY 0x54
static gboolean type_is_reference (MonoType *type);
static GENERATE_GET_CLASS_WITH_CACHE (custom_attribute_typed_argument, "System.Reflection", "CustomAttributeTypedArgument");
static GENERATE_GET_CLASS_WITH_CACHE (custom_attribute_named_argument, "System.Reflection", "CustomAttributeNamedArgument");
static GENERATE_TRY_GET_CLASS_WITH_CACHE (customattribute_data, "System.Reflection", "RuntimeCustomAttributeData");
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders_handle (MonoImage *alloc_img, MonoImage *image, MonoArrayHandle cattrs);
static gboolean
bcheck_blob (const char *ptr, int bump, const char *endp, MonoError *error);
static gboolean
decode_blob_value_checked (const char *ptr, const char *endp, guint32 *size_out, const char **retp, MonoError *error);
static guint32
custom_attrs_idx_from_class (MonoClass *klass);
static guint32
custom_attrs_idx_from_method (MonoMethod *method);
static void
metadata_foreach_custom_attr_from_index (MonoImage *image, guint32 idx, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data);
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoCustomAttrInfo* res;
res = (MonoCustomAttrInfo *)mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
res = (MonoCustomAttrInfo *)g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
res->cached = 0;
return res;
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttrHandle cattr, MonoReflectionMethodHandle ctor_handle, MonoMethod **ctor_method)
// ctor_handle is local to this function, allocated by its caller for efficiency.
{
MONO_REQ_GC_UNSAFE_MODE;
MONO_HANDLE_GET (ctor_handle, cattr, ctor);
*ctor_method = MONO_HANDLE_GETVAL (ctor_handle, method);
/* FIXME: Need to do more checks */
if (*ctor_method) {
MonoClass *klass = (*ctor_method)->klass;
if (m_class_get_image (klass) != image) {
const int visibility = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_VISIBILITY_MASK);
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
}
return TRUE;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
if (G_UNLIKELY (m_field_is_from_update (field)))
return mono_metadata_update_get_field_idx (field);
int fcount = mono_class_get_field_count (klass);
MonoClassField *klass_fields = m_class_get_fields (klass);
int index = field - klass_fields;
if (index > fcount)
return 0;
g_assert (field == &klass_fields [index]);
return mono_class_get_first_field_idx (klass) + 1 + index;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property)
{
int i;
MonoClassPropertyInfo *info = mono_class_get_property_info (klass);
for (i = 0; i < info->count; ++i) {
if (property == &info->properties [i])
return info->first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event)
{
int i;
MonoClassEventInfo *info = mono_class_get_event_info (klass);
for (i = 0; i < info->count; ++i) {
if (event == &info->events [i])
return info->first + 1 + i;
}
return 0;
}
/*
* Load the type with name @n on behalf of image @image. On failure sets @error and returns NULL.
* The @is_enum flag only affects the error message that's displayed on failure.
*/
static MonoType*
cattr_type_from_name (char *n, MonoImage *image, gboolean is_enum, MonoError *error)
{
ERROR_DECL (inner_error);
MonoAssemblyLoadContext *alc = mono_alc_get_ambient ();
MonoType *t = mono_reflection_type_from_name_checked (n, alc, image, inner_error);
if (!t) {
mono_error_set_type_load_name (error, g_strdup(n), NULL,
"Could not load %s %s while decoding custom attribute: %s",
is_enum ? "enum type": "type",
n,
mono_error_get_message (inner_error));
mono_error_cleanup (inner_error);
return NULL;
}
return t;
}
static MonoClass*
load_cattr_enum_type (MonoImage *image, const char *p, const char *boundp, const char **end, MonoError *error)
{
char *n;
MonoType *t;
guint32 slen;
error_init (error);
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (boundp && slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = cattr_type_from_name (n, image, TRUE, error);
g_free (n);
return_val_if_nok (error, NULL);
p += slen;
*end = p;
return mono_class_from_mono_type_internal (t);
}
static MonoType*
load_cattr_type (MonoImage *image, MonoType *t, gboolean header, const char *p, const char *boundp, const char **end, MonoError *error, guint32 *slen)
{
MonoType *res;
char *n;
if (header) {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MONO_DISABLE_WARNING(4310) // cast truncates constant value
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
MONO_RESTORE_WARNING
}
if (!decode_blob_value_checked (p, boundp, slen, &p, error))
return NULL;
if (*slen > 0 && !bcheck_blob (p, *slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, *slen + 1);
n [*slen] = 0;
res = cattr_type_from_name (n, image, FALSE, error);
g_free (n);
return_val_if_nok (error, NULL);
*end = p + *slen;
return res;
}
/*
* If OUT_OBJ is non-NULL, created objects are stored into it and NULL is returned.
* If OUT_OBJ is NULL, assert if objects were to be created.
*/
static void*
load_cattr_value (MonoImage *image, MonoType *t, MonoObject **out_obj, const char *p, const char *boundp, const char **end, MonoError *error)
{
int type = t->type;
guint32 slen;
MonoClass *tklass = t->data.klass;
if (out_obj)
*out_obj = NULL;
g_assert (boundp);
error_init (error);
if (type == MONO_TYPE_GENERICINST) {
MonoGenericClass * mgc = t->data.generic_class;
MonoClass * cc = mgc->container_class;
if (m_class_is_enumtype (cc)) {
tklass = m_class_get_element_class (cc);
t = m_class_get_byval_arg (tklass);
type = t->type;
} else {
g_error ("Unhandled type of generic instance in load_cattr_value: %s", m_class_get_name (cc));
}
}
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = (MonoBoolean *)g_malloc (sizeof (MonoBoolean));
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = (guint16 *)g_malloc (sizeof (guint16));
if (!bcheck_blob (p, 1, boundp, error))
return NULL;
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = (guint32 *)g_malloc (sizeof (guint32));
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = (guint64 *)g_malloc (sizeof (guint64));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = (double *)g_malloc (sizeof (double));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (m_class_is_enumtype (t->data.klass)) {
type = mono_class_enum_basetype_internal (t->data.klass)->type;
goto handle_enum;
} else {
MonoClass *k = t->data.klass;
if (mono_is_corlib_image (m_class_get_image (k)) && strcmp (m_class_get_name_space (k), "System") == 0 && strcmp (m_class_get_name (k), "DateTime") == 0){
guint64 *val = (guint64 *)g_malloc (sizeof (guint64));
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
*val = read64 (p);
*end = p + 8;
return val;
}
}
g_error ("generic valutype %s not handled in custom attr value decoding", m_class_get_name (t->data.klass));
break;
case MONO_TYPE_STRING: {
const char *start = p;
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MONO_DISABLE_WARNING (4310) // cast truncates constant value
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
MONO_RESTORE_WARNING
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
*end = p + slen;
if (!out_obj)
return (void*)start;
// https://bugzilla.xamarin.com/show_bug.cgi?id=60848
// Custom attribute strings are encoded as wtf-8 instead of utf-8.
// If we decode using utf-8 like the spec says, we will silently fail
// to decode some attributes in assemblies that Windows .NET Framework
// and CoreCLR both manage to decode.
// See https://simonsapin.github.io/wtf-8/ for a description of wtf-8.
// Always use string.Empty for empty strings
if (slen == 0)
*out_obj = (MonoObject*)mono_string_empty_internal (mono_domain_get ());
else
*out_obj = (MonoObject*)mono_string_new_wtf8_len_checked (p, slen, error);
return NULL;
}
case MONO_TYPE_CLASS: {
MonoType *type = load_cattr_type (image, t, TRUE, p, boundp, end, error, &slen);
if (out_obj) {
if (!type)
return NULL;
*out_obj = (MonoObject*)mono_type_get_object_checked (type, error);
return NULL;
} else {
return type;
}
}
case MONO_TYPE_OBJECT: {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == CATTR_TYPE_SYSTEM_TYPE) {
MonoType *type = load_cattr_type (image, t, FALSE, p, boundp, end, error, &slen);
if (out_obj) {
if (!type)
return NULL;
*out_obj = (MonoObject*)mono_type_get_object_checked (type, error);
return NULL;
} else {
return type;
}
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
int etype = *p;
p ++;
type = MONO_TYPE_SZARRAY;
if (etype == CATTR_TYPE_SYSTEM_TYPE) {
tklass = mono_defaults.systemtype_class;
} else if (etype == MONO_TYPE_ENUM) {
tklass = load_cattr_enum_type (image, p, boundp, &p, error);
if (!is_ok (error))
return NULL;
} else {
if (etype == CATTR_BOXED_VALUETYPE_PREFIX)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
simple_type.type = (MonoTypeEnum)etype;
tklass = mono_class_from_mono_type_internal (&simple_type);
}
goto handle_enum;
} else if (subt == MONO_TYPE_ENUM) {
char *n;
MonoType *t;
if (!decode_blob_value_checked (p, boundp, &slen, &p, error))
return NULL;
if (slen > 0 && !bcheck_blob (p, slen - 1, boundp, error))
return NULL;
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = cattr_type_from_name (n, image, FALSE, error);
g_free (n);
return_val_if_nok (error, NULL);
p += slen;
subc = mono_class_from_mono_type_internal (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = (MonoTypeEnum)subt;
subc = mono_class_from_mono_type_internal (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, m_class_get_byval_arg (subc), NULL, p, boundp, end, error);
if (is_ok (error)) {
obj = mono_object_new_checked (subc, error);
g_assert (!m_class_has_references (subc));
if (is_ok (error))
mono_gc_memmove_atomic (mono_object_get_data (obj), val, mono_class_value_size (subc, NULL));
g_assert (out_obj);
*out_obj = obj;
}
g_free (val);
return NULL;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new_checked (tklass, alen, error);
return_val_if_nok (error, NULL);
basetype = m_class_get_byval_arg (tklass)->type;
if (basetype == MONO_TYPE_VALUETYPE && m_class_is_enumtype (tklass))
basetype = mono_class_enum_basetype_internal (tklass)->type;
if (basetype == MONO_TYPE_GENERICINST) {
MonoGenericClass * mgc = m_class_get_byval_arg (tklass)->data.generic_class;
MonoClass * cc = mgc->container_class;
if (m_class_is_enumtype (cc)) {
basetype = m_class_get_byval_arg (m_class_get_element_class (cc))->type;
} else {
g_error ("Unhandled type of generic instance in load_cattr_value: %s[]", m_class_get_name (cc));
}
}
switch (basetype) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 0, boundp, error))
return NULL;
MonoBoolean val = *p++;
mono_array_set_internal (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 1, boundp, error))
return NULL;
guint16 val = read16 (p);
mono_array_set_internal (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 3, boundp, error))
return NULL;
guint32 val = read32 (p);
mono_array_set_internal (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
double val;
readr8 (p, &val);
mono_array_set_internal (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
if (!bcheck_blob (p, 7, boundp, error))
return NULL;
guint64 val = read64 (p);
mono_array_set_internal (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY: {
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_NEW (MonoArray, arr);
for (i = 0; i < alen; i++) {
MonoObject *item = NULL;
load_cattr_value (image, m_class_get_byval_arg (tklass), &item, p, boundp, &p, error);
if (!is_ok (error))
return NULL;
mono_array_setref_internal (arr, i, item);
}
HANDLE_FUNCTION_RETURN ();
break;
}
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end = p;
g_assert (out_obj);
*out_obj = (MonoObject*)arr;
return NULL;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
load_cattr_value_boxed (MonoDomain *domain, MonoImage *image, MonoType *t, const char* p, const char *boundp, const char** end, MonoError *error)
{
error_init (error);
gboolean is_ref = type_is_reference (t);
if (is_ref) {
MonoObject *obj = NULL;
gpointer val = load_cattr_value (image, t, &obj, p, boundp, end, error);
if (!is_ok (error))
return NULL;
g_assert (!val);
return obj;
} else {
void *val = load_cattr_value (image, t, NULL, p, boundp, end, error);
if (!is_ok (error))
return NULL;
MonoObject *boxed = mono_value_box_checked (mono_class_from_mono_type_internal (t), val, error);
g_free (val);
return boxed;
}
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val, MonoError *error)
{
MonoObject *retval;
void *params [2], *unboxed;
error_init (error);
HANDLE_FUNCTION_ENTER ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (mono_class_get_custom_attribute_typed_argument_class (), ".ctor", 2, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
params [0] = mono_type_get_object_checked (t, error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN ((MonoObject*)params [0]);
params [1] = val;
retval = mono_object_new_checked (mono_class_get_custom_attribute_typed_argument_class (), error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN (retval);
unboxed = mono_object_unbox_internal (retval);
mono_runtime_invoke_checked (ctor, unboxed, params, error);
return_val_if_nok (error, NULL);
HANDLE_FUNCTION_RETURN ();
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg, MonoError *error)
{
MonoObject *retval;
void *unboxed, *params [2];
error_init (error);
HANDLE_FUNCTION_ENTER ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (mono_class_get_custom_attribute_named_argument_class (), ".ctor", 2, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new_checked (mono_class_get_custom_attribute_named_argument_class (), error);
return_val_if_nok (error, NULL);
MONO_HANDLE_PIN (retval);
unboxed = mono_object_unbox_internal (retval);
mono_runtime_invoke_checked (ctor, unboxed, params, error);
return_val_if_nok (error, NULL);
HANDLE_FUNCTION_RETURN ();
return retval;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders_handle (MonoImage *alloc_img, MonoImage *image, MonoArrayHandle cattrs)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!MONO_HANDLE_BOOL (cattrs))
return NULL;
HANDLE_FUNCTION_ENTER ();
/* FIXME: check in assembly the Run flag is set */
MonoReflectionCustomAttrHandle cattr = MONO_HANDLE_NEW (MonoReflectionCustomAttr, NULL);
MonoArrayHandle cattr_data = MONO_HANDLE_NEW (MonoArray, NULL);
MonoReflectionMethodHandle ctor_handle = MONO_HANDLE_NEW (MonoReflectionMethod, NULL);
int const count = mono_array_handle_length (cattrs);
MonoMethod *ctor_method = NULL;
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
int count_visible = 0;
for (int i = 0; i < count; ++i) {
MONO_HANDLE_ARRAY_GETREF (cattr, cattrs, i);
count_visible += custom_attr_visible (image, cattr, ctor_handle, &ctor_method);
}
MonoCustomAttrInfo *ainfo;
ainfo = (MonoCustomAttrInfo *)mono_image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count_visible);
ainfo->image = image;
ainfo->num_attrs = count_visible;
ainfo->cached = alloc_img != NULL;
int index = 0;
for (int i = 0; i < count; ++i) {
MONO_HANDLE_ARRAY_GETREF (cattr, cattrs, i);
if (!custom_attr_visible (image, cattr, ctor_handle, &ctor_method))
continue;
if (image_is_dynamic (image))
mono_reflection_resolution_scope_from_image ((MonoDynamicImage *)image->assembly->image, m_class_get_image (ctor_method->klass));
MONO_HANDLE_GET (cattr_data, cattr, data);
unsigned char *saved = (unsigned char *)mono_image_alloc (image, mono_array_handle_length (cattr_data));
MonoGCHandle gchandle = NULL;
memcpy (saved, MONO_ARRAY_HANDLE_PIN (cattr_data, char, 0, &gchandle), mono_array_handle_length (cattr_data));
mono_gchandle_free_internal (gchandle);
ainfo->attrs [index].ctor = ctor_method;
g_assert (ctor_method);
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_handle_length (cattr_data);
index ++;
}
g_assert (index == count_visible);
HANDLE_FUNCTION_RETURN_VAL (ainfo);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray* cattrs)
{
HANDLE_FUNCTION_ENTER ();
MonoCustomAttrInfo* const result = mono_custom_attrs_from_builders_handle (alloc_img, image, MONO_HANDLE_NEW (MonoArray, cattrs));
HANDLE_FUNCTION_RETURN_VAL (result);
}
static void
set_custom_attr_fmt_error (MonoError *error)
{
error_init (error);
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
}
/**
* bcheck_blob:
* \param ptr a pointer into a blob
* \param bump how far we plan on reading past \p ptr.
* \param endp upper bound for \p ptr - one past the last valid value for \p ptr.
* \param error set on error
*
* Check that ptr+bump is below endp. Returns TRUE on success, or FALSE on
* failure and sets \p error.
*/
static gboolean
bcheck_blob (const char *ptr, int bump, const char *endp, MonoError *error)
{
error_init (error);
if (ADDP_IS_GREATER_OR_OVF (ptr, bump, endp - 1)) {
set_custom_attr_fmt_error (error);
return FALSE;
} else
return TRUE;
}
/**
* decode_blob_size_checked:
* \param ptr a pointer into a blob
* \param endp upper bound for \p ptr - one pas the last valid value for \p ptr
* \param size_out on success set to the decoded size
* \param retp on success set to the next byte after the encoded size
* \param error set on error
*
* Decode an encoded size value which takes 1, 2, or 4 bytes and set \p
* size_out to the decoded size and \p retp to the next byte after the encoded
* size. Returns TRUE on success, or FALASE on failure and sets \p error.
*/
static gboolean
decode_blob_size_checked (const char *ptr, const char *endp, guint32 *size_out, const char **retp, MonoError *error)
{
error_init (error);
if (endp && !bcheck_blob (ptr, 0, endp, error))
goto leave;
if ((*ptr & 0x80) != 0) {
if ((*ptr & 0x40) == 0 && !bcheck_blob (ptr, 1, endp, error))
goto leave;
else if (!bcheck_blob (ptr, 3, endp, error))
goto leave;
}
*size_out = mono_metadata_decode_blob_size (ptr, retp);
leave:
return is_ok (error);
}
/**
* decode_blob_value_checked:
* \param ptr a pointer into a blob
* \param endp upper bound for \p ptr - one pas the last valid value for \p ptr
* \param value_out on success set to the decoded value
* \param retp on success set to the next byte after the encoded size
* \param error set on error
*
* Decode an encoded uint32 value which takes 1, 2, or 4 bytes and set \p
* value_out to the decoded value and \p retp to the next byte after the
* encoded value. Returns TRUE on success, or FALASE on failure and sets \p
* error.
*/
static gboolean
decode_blob_value_checked (const char *ptr, const char *endp, guint32 *value_out, const char **retp, MonoError *error)
{
/* This similar to decode_blob_size_checked, above but delegates to
* mono_metadata_decode_value which is semantically different. */
error_init (error);
if (!bcheck_blob (ptr, 0, endp, error))
goto leave;
if ((*ptr & 0x80) != 0) {
if ((*ptr & 0x40) == 0 && !bcheck_blob (ptr, 1, endp, error))
goto leave;
else if (!bcheck_blob (ptr, 3, endp, error))
goto leave;
}
*value_out = mono_metadata_decode_value (ptr, retp);
leave:
return is_ok (error);
}
static MonoObjectHandle
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
const char *p = (const char*)data;
const char *data_end = (const char*)data + len;
const char *named;
guint32 i, j, num_named;
MonoObjectHandle attr = NULL_HANDLE;
void *params_buf [32];
void **params = NULL;
MonoMethodSignature *sig;
MonoClassField *field = NULL;
char *name = NULL;
void *pparams [1] = { NULL };
MonoType *prop_type = NULL;
void *val = NULL; // FIXMEcoop is this a raw pointer or a value?
error_init (error);
mono_class_init_internal (method->klass);
if (len == 0) {
attr = mono_object_new_handle (method->klass, error);
goto_if_nok (error, fail);
mono_runtime_invoke_handle_void (method, attr, NULL, error);
goto_if_nok (error, fail);
goto exit;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
goto fail;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature_internal (method);
if (sig->param_count < 32) {
params = params_buf;
memset (params, 0, sizeof (void*) * sig->param_count);
} else {
/* Allocate using GC so it gets GC tracking */
params = (void **)mono_gc_alloc_fixed (sig->param_count * sizeof (void*), MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_REFLECTION, NULL, "Reflection Custom Attribute Parameters");
}
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature_internal (method)->param_count; ++i) {
MonoObject *param_obj;
params [i] = load_cattr_value (image, mono_method_signature_internal (method)->params [i], ¶m_obj, p, data_end, &p, error);
if (param_obj)
params [i] = param_obj;
goto_if_nok (error, fail);
}
named = p;
attr = mono_object_new_handle (method->klass, error);
goto_if_nok (error, fail);
(void)mono_runtime_try_invoke_handle (method, attr, params, error);
goto_if_nok (error, fail);
if (named + 1 < data_end) {
num_named = read16 (named);
named += 2;
} else {
/* CoreCLR allows p == data + len */
if (named == data_end)
num_named = 0;
else {
set_custom_attr_fmt_error (error);
goto fail;
}
}
for (j = 0; j < num_named; j++) {
guint32 name_len;
char named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
goto fail;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
goto fail;
if (type_len > 0 && !bcheck_blob (named, type_len - 1, data_end, error))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
if (!decode_blob_size_checked (named, data_end, &name_len, &named, error))
goto fail;
if (name_len > 0 && !bcheck_blob (named, name_len - 1, data_end, error))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* how this fail is a blackbox */
field = mono_class_get_field_from_name_full (mono_handle_class (attr), name, NULL);
if (!field) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find a field with name %s", name);
goto fail;
}
MonoObject *param_obj;
val = load_cattr_value (image, field->type, ¶m_obj, named, data_end, &named, error);
if (param_obj)
val = param_obj;
goto_if_nok (error, fail);
mono_field_set_value_internal (MONO_HANDLE_RAW (attr), field, val); // FIXMEcoop
} else if (named_type == CATTR_TYPE_PROPERTY) {
MonoProperty *prop;
prop = mono_class_get_property_from_name_internal (mono_handle_class (attr), name);
if (!prop) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find a property with name %s", name);
goto fail;
}
if (!prop->set) {
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Could not find the setter for %s", name);
goto fail;
}
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
MonoObject *param_obj;
pparams [0] = load_cattr_value (image, prop_type, ¶m_obj, named, data_end, &named, error);
if (param_obj)
pparams [0] = param_obj;
goto_if_nok (error, fail);
mono_property_set_value_handle (prop, attr, pparams, error);
goto_if_nok (error, fail);
}
g_free (name);
name = NULL;
}
goto exit;
fail:
g_free (name);
name = NULL;
attr = mono_new_null ();
exit:
if (field && !type_is_reference (field->type))
g_free (val);
if (prop_type && !type_is_reference (prop_type))
g_free (pparams [0]);
if (params) {
free_param_data (method->signature, params);
if (params != params_buf)
mono_gc_free_fixed (params);
}
HANDLE_FUNCTION_RETURN_REF (MonoObject, attr);
}
static void
create_custom_attr_into_array (MonoImage *image, MonoMethod *method, const guchar *data,
guint32 len, MonoArrayHandle array, int index, MonoError *error)
{
// This function serves to avoid creating handles in a loop.
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle attr = create_custom_attr (image, method, data, len, error);
MONO_HANDLE_ARRAY_SETREF (array, index, attr);
HANDLE_FUNCTION_RETURN ();
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArrayHandleOut typed_args_h, MonoArrayHandleOut named_args_h, CattrNamedArg **named_arg_info, MonoError *error)
{
MonoArray *typed_args, *named_args;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *data_end = p + len;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
MONO_HANDLE_ASSIGN_RAW (typed_args_h, NULL);
MONO_HANDLE_ASSIGN_RAW (named_args_h, NULL);
*named_arg_info = NULL;
typed_args = NULL;
named_args = NULL;
error_init (error);
mono_class_init_internal (method->klass);
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
/* skip prolog */
p += 2;
/* Parse each argument corresponding to the signature's parameters from
* the blob and store in typed_args.
*/
typed_args = mono_array_new_checked (mono_get_object_class (), mono_method_signature_internal (method)->param_count, error);
return_if_nok (error);
MONO_HANDLE_ASSIGN_RAW (typed_args_h, typed_args);
for (i = 0; i < mono_method_signature_internal (method)->param_count; ++i) {
MonoObject *obj;
obj = load_cattr_value_boxed (domain, image, mono_method_signature_internal (method)->params [i], p, data_end, &p, error);
return_if_nok (error);
mono_array_setref_internal (typed_args, i, obj);
}
named = p;
/* Parse mandatory count of named arguments (could be zero) */
if (!bcheck_blob (named, 1, data_end, error))
return;
num_named = read16 (named);
named_args = mono_array_new_checked (mono_get_object_class (), num_named, error);
return_if_nok (error);
MONO_HANDLE_ASSIGN_RAW (named_args_h, named_args);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
/* Parse each named arg, and add to arginfo. Each named argument could
* be a field name or a property name followed by a value. */
for (j = 0; j < num_named; j++) {
guint32 name_len;
char *name, named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
return;
named_type = *named++; /* field or property? */
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
return;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
return;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, type_len, data + len))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
/* named argument name: length, then name */
if (!decode_blob_size_checked(named, data_end, &name_len, &named, error))
return;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, name_len, data + len))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* Named arg is a field. */
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name_full (attrklass, name, NULL);
if (!field) {
g_free (name);
goto fail;
}
arginfo [j].type = field->type;
arginfo [j].field = field;
obj = load_cattr_value_boxed (domain, image, field->type, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
return;
}
mono_array_setref_internal (named_args, j, obj);
} else if (named_type == CATTR_TYPE_PROPERTY) {
/* Named arg is a property */
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name_internal (attrklass, name);
if (!prop || !prop->set) {
g_free (name);
goto fail;
}
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
obj = load_cattr_value_boxed (domain, image, prop_type, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
return;
}
mono_array_setref_internal (named_args, j, obj);
}
g_free (name);
}
return;
fail:
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
g_free (arginfo);
*named_arg_info = NULL;
}
/*
* mono_reflection_create_custom_attr_data_args_noalloc:
*
* Same as mono_reflection_create_custom_attr_data_args but allocate no managed objects, return values
* using C arrays. Only usable for cattrs with primitive/type/string arguments.
* For types, a MonoType* is returned.
* For strings, the address in the metadata blob is returned.
* TYPED_ARGS, NAMED_ARGS, and NAMED_ARG_INFO should be freed using g_free ().
*/
void
mono_reflection_create_custom_attr_data_args_noalloc (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len,
gpointer **typed_args_out, gpointer **named_args_out, int *num_named_args,
CattrNamedArg **named_arg_info, MonoError *error)
{
gpointer *typed_args, *named_args;
MonoClass *attrklass;
const char *p = (const char*)data;
const char *data_end = p + len;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
MonoMethodSignature *sig = mono_method_signature_internal (method);
*typed_args_out = NULL;
*named_args_out = NULL;
*named_arg_info = NULL;
typed_args = NULL;
named_args = NULL;
error_init (error);
mono_class_init_internal (method->klass);
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
goto fail;
/* skip prolog */
p += 2;
typed_args = g_new0 (gpointer, sig->param_count);
for (i = 0; i < sig->param_count; ++i) {
typed_args [i] = load_cattr_value (image, sig->params [i], NULL, p, data_end, &p, error);
return_if_nok (error);
}
named = p;
/* Parse mandatory count of named arguments (could be zero) */
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
num_named = read16 (named);
named_args = g_new0 (gpointer, num_named);
return_if_nok (error);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
*num_named_args = num_named;
/* Parse each named arg, and add to arginfo. Each named argument could
* be a field name or a property name followed by a value. */
for (j = 0; j < num_named; j++) {
guint32 name_len;
char *name, named_type, data_type;
if (!bcheck_blob (named, 1, data_end, error))
goto fail;
named_type = *named++; /* field or property? */
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY) {
if (!bcheck_blob (named, 0, data_end, error))
goto fail;
data_type = *named++;
}
if (data_type == MONO_TYPE_ENUM) {
guint32 type_len;
char *type_name;
if (!decode_blob_size_checked (named, data_end, &type_len, &named, error))
goto fail;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, type_len, data + len))
goto fail;
type_name = (char *)g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
/* named argument name: length, then name */
if (!decode_blob_size_checked(named, data_end, &name_len, &named, error))
goto fail;
if (ADDP_IS_GREATER_OR_OVF ((const guchar*)named, name_len, data + len))
goto fail;
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == CATTR_TYPE_FIELD) {
/* Named arg is a field. */
MonoClassField *field = mono_class_get_field_from_name_full (attrklass, name, NULL);
if (!field) {
g_free (name);
goto fail;
}
arginfo [j].type = field->type;
arginfo [j].field = field;
named_args [j] = load_cattr_value (image, field->type, NULL, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
goto fail;
}
} else if (named_type == CATTR_TYPE_PROPERTY) {
/* Named arg is a property */
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name_internal (attrklass, name);
if (!prop || !prop->set) {
g_free (name);
goto fail;
}
prop_type = prop->get? mono_method_signature_internal (prop->get)->ret :
mono_method_signature_internal (prop->set)->params [mono_method_signature_internal (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
named_args [j] = load_cattr_value (image, prop_type, NULL, named, data_end, &named, error);
if (!is_ok (error)) {
g_free (name);
goto fail;
}
}
g_free (name);
}
*typed_args_out = typed_args;
*named_args_out = named_args;
return;
fail:
mono_error_set_generic_error (error, "System.Reflection", "CustomAttributeFormatException", "Binary format of the specified custom attribute was invalid.");
g_free (typed_args);
g_free (named_args);
g_free (arginfo);
*named_arg_info = NULL;
}
void
ves_icall_System_Reflection_RuntimeCustomAttributeData_ResolveArgumentsInternal (MonoReflectionMethodHandle ref_method_h, MonoReflectionAssemblyHandle assembly_h,
gpointer data, guint32 len,
MonoArrayHandleOut ctor_args_h, MonoArrayHandleOut named_args_h,
MonoError *error)
{
MonoArray *typed_args, *named_args;
MonoImage *image;
MonoMethod *method;
CattrNamedArg *arginfo = NULL;
MonoReflectionMethod *ref_method = MONO_HANDLE_RAW (ref_method_h);
MonoReflectionAssembly *assembly = MONO_HANDLE_RAW (assembly_h);
MonoMethodSignature *sig;
MonoObjectHandle obj_h, namedarg_h, minfo_h;
int i;
if (len == 0)
return;
obj_h = MONO_HANDLE_NEW (MonoObject, NULL);
namedarg_h = MONO_HANDLE_NEW (MonoObject, NULL);
minfo_h = MONO_HANDLE_NEW (MonoObject, NULL);
image = assembly->assembly->image;
method = ref_method->method;
if (!mono_class_init_internal (method->klass)) {
mono_error_set_for_class_failure (error, method->klass);
goto leave;
}
// FIXME: Handles
mono_reflection_create_custom_attr_data_args (image, method, (const guchar *)data, len, ctor_args_h, named_args_h, &arginfo, error);
goto_if_nok (error, leave);
typed_args = MONO_HANDLE_RAW (ctor_args_h);
named_args = MONO_HANDLE_RAW (named_args_h);
if (!typed_args || !named_args)
goto leave;
sig = mono_method_signature_internal (method);
for (i = 0; i < sig->param_count; ++i) {
MonoObject *obj;
MonoObject *typedarg;
MonoType *t;
obj = mono_array_get_internal (typed_args, MonoObject*, i);
MONO_HANDLE_ASSIGN_RAW (obj_h, obj);
t = sig->params [i];
if (t->type == MONO_TYPE_OBJECT && obj)
t = m_class_get_byval_arg (obj->vtable->klass);
typedarg = create_cattr_typed_arg (t, obj, error);
goto_if_nok (error, leave);
mono_array_setref_internal (typed_args, i, typedarg);
}
for (i = 0; i < mono_array_length_internal (named_args); ++i) {
MonoObject *obj;
MonoObject *namedarg, *minfo;
obj = mono_array_get_internal (named_args, MonoObject*, i);
MONO_HANDLE_ASSIGN_RAW (obj_h, obj);
if (arginfo [i].prop) {
minfo = (MonoObject*)mono_property_get_object_checked (arginfo [i].prop->parent, arginfo [i].prop, error);
if (!minfo)
goto leave;
} else {
minfo = (MonoObject*)mono_field_get_object_checked (NULL, arginfo [i].field, error);
goto_if_nok (error, leave);
}
MONO_HANDLE_ASSIGN_RAW (minfo_h, minfo);
namedarg = create_cattr_named_arg (minfo, obj, error);
MONO_HANDLE_ASSIGN_RAW (namedarg_h, namedarg);
goto_if_nok (error, leave);
mono_array_setref_internal (named_args, i, namedarg);
}
leave:
g_free (arginfo);
}
static MonoClass*
try_get_cattr_data_class (MonoError* error)
{
error_init (error);
MonoClass *res = mono_class_try_get_customattribute_data_class ();
if (!res)
mono_error_set_execution_engine (error, "Class System.Reflection.RuntimeCustomAttributeData not found, probably removed by the linker");
return res;
}
static MonoObjectHandle
create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
static MonoMethod *ctor;
void *params [4];
error_init (error);
g_assert (image->assembly);
MonoObjectHandle attr;
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, result_null);
if (!ctor) {
MonoMethod *tmp = mono_class_get_method_from_name_checked (cattr_data, ".ctor", 4, 0, error);
mono_error_assert_ok (error);
g_assert (tmp);
mono_memory_barrier (); //safe publish!
ctor = tmp;
}
attr = mono_object_new_handle (cattr_data, error);
goto_if_nok (error, fail);
MonoReflectionMethodHandle ctor_obj;
ctor_obj = mono_method_get_object_handle (cattr->ctor, NULL, error);
goto_if_nok (error, fail);
MonoReflectionAssemblyHandle assm;
assm = mono_assembly_get_object_handle (image->assembly, error);
goto_if_nok (error, fail);
params [0] = MONO_HANDLE_RAW (ctor_obj);
params [1] = MONO_HANDLE_RAW (assm);
params [2] = &cattr->data;
params [3] = &cattr->data_size;
mono_runtime_invoke_handle_void (ctor, attr, params, error);
goto fail;
result_null:
attr = MONO_HANDLE_CAST (MonoObject, mono_new_null ());
fail:
HANDLE_FUNCTION_RETURN_REF (MonoObject, attr);
}
static void
create_custom_attr_data_into_array (MonoImage *image, MonoCustomAttrEntry *cattr, MonoArrayHandle result, int index, MonoError *error)
{
// This function serves to avoid creating handles in a loop.
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle attr = create_custom_attr_data (image, cattr, error);
goto_if_nok (error, exit);
MONO_HANDLE_ARRAY_SETREF (result, index, attr);
exit:
HANDLE_FUNCTION_RETURN ();
}
static MonoArrayHandle
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle result;
int i, n;
error_init (error);
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &cinfo->attrs[i];
if (!centry->ctor) {
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_error_set_type_load_name (error, NULL, NULL, "Custom attribute constructor is null because the custom attribute type is not finished yet.");
goto return_null;
}
}
n = 0;
if (attr_klass) {
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoMethod *ctor = cinfo->attrs[i].ctor;
g_assert (ctor);
if (mono_class_is_assignable_from_internal (attr_klass, ctor->klass))
n++;
}
} else {
n = cinfo->num_attrs;
}
result = mono_array_new_cached_handle (mono_defaults.attribute_class, n, error);
goto_if_nok (error, return_null);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &cinfo->attrs [i];
if (!attr_klass || mono_class_is_assignable_from_internal (attr_klass, centry->ctor->klass)) {
create_custom_attr_into_array (cinfo->image, centry->ctor, centry->data,
centry->data_size, result, n, error);
goto_if_nok (error, exit);
n ++;
}
}
goto exit;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
exit:
HANDLE_FUNCTION_RETURN_REF (MonoArray, result);
}
/**
* mono_custom_attrs_construct:
*/
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoArrayHandle result = mono_custom_attrs_construct_by_type (cinfo, NULL, error);
mono_error_assert_ok (error); /*FIXME proper error handling*/
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static MonoArrayHandle
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle result;
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, return_null);
result = mono_array_new_handle (cattr_data, cinfo->num_attrs, error);
goto_if_nok (error, return_null);
for (int i = 0; i < cinfo->num_attrs; ++i) {
create_custom_attr_data_into_array (cinfo->image, &cinfo->attrs [i], result, i, error);
goto_if_nok (error, return_null);
}
goto exit;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
exit:
HANDLE_FUNCTION_RETURN_REF (MonoArray, result);
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_custom_attrs_from_index_checked:
* \returns NULL if no attributes are found. On error returns NULL and sets \p error.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index_checked (MonoImage *image, guint32 idx, gboolean ignore_missing, MonoError *error)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GArray *attr_array;
const char *data;
MonoCustomAttrEntry* attr;
error_init (error);
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
// initial size chosen arbitrarily, but default is 16 which is rather small
attr_array = g_array_sized_new (TRUE, TRUE, sizeof (guint32), 128);
while (!mono_metadata_table_bounds_check (image, MONO_TABLE_CUSTOMATTRIBUTE, i + 1)) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx) {
if (G_LIKELY (!image->has_updates)) {
break;
} else {
// if there are updates, the new custom attributes are not sorted,
// so we have to go until the end.
++i;
continue;
}
}
attr_array = g_array_append_val (attr_array, i);
++i;
}
len = attr_array->len;
if (!len) {
g_array_free (attr_array, TRUE);
return NULL;
}
ainfo = (MonoCustomAttrInfo *)g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0; i < len; ++i) {
mono_metadata_decode_row (ca, g_array_index (attr_array, guint32, i), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
attr = &ainfo->attrs [i];
attr->ctor = mono_get_method_checked (image, mtoken, NULL, NULL, error);
if (!attr->ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x due to: %s", image->name, mtoken, mono_error_get_message (error));
if (ignore_missing) {
mono_error_cleanup (error);
error_init (error);
} else {
g_array_free (attr_array, TRUE);
g_free (ainfo);
return NULL;
}
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
attr->data_size = mono_metadata_decode_value (data, &data);
attr->data = (guchar*)data;
}
g_array_free (attr_array, TRUE);
return ainfo;
}
/**
* mono_custom_attrs_from_method:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
ERROR_DECL (error);
MonoCustomAttrInfo* result = mono_custom_attrs_from_method_checked (method, error);
mono_error_cleanup (error); /* FIXME want a better API that doesn't swallow the error */
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method_checked (MonoMethod *method, MonoError *error)
{
guint32 idx;
error_init (error);
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method_is_dynamic (method) || image_is_dynamic (m_class_get_image (method->klass)))
return lookup_custom_attr (m_class_get_image (method->klass), method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = custom_attrs_idx_from_method (method);
return mono_custom_attrs_from_index_checked (m_class_get_image (method->klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_class:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_class_checked (klass, error);
mono_error_cleanup (error);
return result;
}
guint32
custom_attrs_idx_from_class (MonoClass *klass)
{
guint32 idx;
g_assert (!image_is_dynamic (m_class_get_image (klass)));
if (m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR || m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (m_class_get_sizes (klass).generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (m_class_get_type_token (klass));
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return idx;
}
guint32
custom_attrs_idx_from_method (MonoMethod *method)
{
guint32 idx;
g_assert (!image_is_dynamic (m_class_get_image (method->klass)));
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return idx;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class_checked (MonoClass *klass, MonoError *error)
{
guint32 idx;
error_init (error);
if (mono_class_is_ginst (klass))
klass = mono_class_get_generic_class (klass)->container_class;
if (image_is_dynamic (m_class_get_image (klass)))
return lookup_custom_attr (m_class_get_image (klass), klass);
idx = custom_attrs_idx_from_class (klass);
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_assembly:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_assembly_checked (assembly, FALSE, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly_checked (MonoAssembly *assembly, gboolean ignore_missing, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (assembly->image))
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index_checked (assembly->image, idx, ignore_missing, error);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (image))
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
}
/**
* mono_custom_attrs_from_property:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_property_checked (klass, property, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property_checked (MonoClass *klass, MonoProperty *property, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (m_class_get_image (klass), property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_event:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_event_checked (klass, event, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event_checked (MonoClass *klass, MonoEvent *event, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (m_class_get_image (klass), event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_field:
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
ERROR_DECL (error);
MonoCustomAttrInfo * result = mono_custom_attrs_from_field_checked (klass, field, error);
mono_error_cleanup (error);
return result;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field_checked (MonoClass *klass, MonoClassField *field, MonoError *error)
{
guint32 idx;
error_init (error);
if (image_is_dynamic (m_class_get_image (klass))) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (m_class_get_image (klass), field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index_checked (m_class_get_image (klass), idx, FALSE, error);
}
/**
* mono_custom_attrs_from_param:
* \param method handle to the method that we want to retrieve custom parameter information from
* \param param parameter number, where zero represent the return value, and one is the first parameter in the method
*
* The result must be released with mono_custom_attrs_free().
*
* \returns the custom attribute object for the specified parameter, or NULL if there are none.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
ERROR_DECL (error);
MonoCustomAttrInfo *result = mono_custom_attrs_from_param_checked (method, param, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_custom_attrs_from_param_checked:
* \param method handle to the method that we want to retrieve custom parameter information from
* \param param parameter number, where zero represent the return value, and one is the first parameter in the method
* \param error set on error
*
* The result must be released with mono_custom_attrs_free().
*
* \returns the custom attribute object for the specified parameter, or NULL if there are none. On failure returns NULL and sets \p error.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_param_checked (MonoMethod *method, guint32 param, MonoError *error)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
error_init (error);
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (image_is_dynamic (m_class_get_image (method->klass))) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)m_class_get_image (method->klass))->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = (MonoCustomAttrInfo *)g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = m_class_get_image (method->klass);
method_index = mono_method_get_index (method);
if (!method_index)
return NULL;
ca = &image->tables [MONO_TABLE_METHOD];
/* FIXME: metadata-update */
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == table_info_get_rows (ca)) {
param_last = table_info_get_rows (&image->tables [MONO_TABLE_PARAM]) + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
}
ca = &image->tables [MONO_TABLE_PARAM];
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index_checked (image, idx, FALSE, error);
}
/**
* mono_custom_attrs_has_attr:
*/
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
for (i = 0; i < ainfo->num_attrs; ++i) {
MonoCustomAttrEntry *centry = &ainfo->attrs[i];
if (centry->ctor == NULL)
continue;
MonoClass *klass = centry->ctor->klass;
if (klass == attr_klass || mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE_INTERNAL (attr_klass) && mono_class_is_assignable_from_internal (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
/**
* mono_custom_attrs_get_attr:
*/
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
ERROR_DECL (error);
MonoObject *res = mono_custom_attrs_get_attr_checked (ainfo, attr_klass, error);
mono_error_assert_ok (error); /*FIXME proper error handling*/
return res;
}
MonoObject*
mono_custom_attrs_get_attr_checked (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass, MonoError *error)
{
int i;
MonoCustomAttrEntry *centry = NULL;
g_assert (attr_klass != NULL);
error_init (error);
for (i = 0; i < ainfo->num_attrs; ++i) {
centry = &ainfo->attrs[i];
if (centry->ctor == NULL)
continue;
MonoClass *klass = centry->ctor->klass;
if (attr_klass == klass || mono_class_is_assignable_from_internal (attr_klass, klass)) {
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle result = create_custom_attr (ainfo->image, centry->ctor, centry->data, centry->data_size, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
}
return NULL;
}
/**
* mono_reflection_get_custom_attrs_info:
* \param obj a reflection object handle
*
* \returns the custom attribute info for attributes defined for the
* reflection handle \p obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoCustomAttrInfo * const result = mono_reflection_get_custom_attrs_info_checked (obj, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/**
* mono_reflection_get_custom_attrs_info_checked:
* \param obj a reflection object handle
* \param error set on error
*
* \returns the custom attribute info for attributes defined for the
* reflection handle \p obj. The objects. On failure returns NULL and sets \p error.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info_checked (MonoObjectHandle obj, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
error_init (error);
klass = mono_handle_class (obj);
const char *klass_name = m_class_get_name (klass);
if (klass == mono_defaults.runtimetype_class) {
MonoType *type = mono_reflection_type_handle_mono_type (MONO_HANDLE_CAST(MonoReflectionType, obj), error);
goto_if_nok (error, leave);
klass = mono_class_from_mono_type_internal (type);
/*We cannot mono_class_init_internal the class from which we'll load the custom attributes since this must work with broken types.*/
cinfo = mono_custom_attrs_from_class_checked (klass, error);
goto_if_nok (error, leave);
} else if (strcmp ("Assembly", klass_name) == 0 || strcmp ("RuntimeAssembly", klass_name) == 0) {
MonoReflectionAssemblyHandle rassembly = MONO_HANDLE_CAST (MonoReflectionAssembly, obj);
cinfo = mono_custom_attrs_from_assembly_checked (MONO_HANDLE_GETVAL (rassembly, assembly), FALSE, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeModule", klass_name) == 0) {
MonoReflectionModuleHandle module = MONO_HANDLE_CAST (MonoReflectionModule, obj);
cinfo = mono_custom_attrs_from_module (MONO_HANDLE_GETVAL (module, image), error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimePropertyInfo", klass_name) == 0) {
MonoReflectionPropertyHandle rprop = MONO_HANDLE_CAST (MonoReflectionProperty, obj);
MonoProperty *property = MONO_HANDLE_GETVAL (rprop, property);
cinfo = mono_custom_attrs_from_property_checked (property->parent, property, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeEventInfo", klass_name) == 0) {
MonoReflectionMonoEventHandle revent = MONO_HANDLE_CAST (MonoReflectionMonoEvent, obj);
MonoEvent *event = MONO_HANDLE_GETVAL (revent, event);
cinfo = mono_custom_attrs_from_event_checked (event->parent, event, error);
goto_if_nok (error, leave);
} else if (strcmp ("RuntimeFieldInfo", klass_name) == 0) {
MonoReflectionFieldHandle rfield = MONO_HANDLE_CAST (MonoReflectionField, obj);
MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field);
cinfo = mono_custom_attrs_from_field_checked (m_field_get_parent (field), field, error);
goto_if_nok (error, leave);
} else if ((strcmp ("RuntimeMethodInfo", klass_name) == 0) || (strcmp ("RuntimeConstructorInfo", klass_name) == 0)) {
MonoReflectionMethodHandle rmethod = MONO_HANDLE_CAST (MonoReflectionMethod, obj);
cinfo = mono_custom_attrs_from_method_checked (MONO_HANDLE_GETVAL (rmethod, method), error);
goto_if_nok (error, leave);
} else if (strcmp ("ParameterInfo", klass_name) == 0 || strcmp ("RuntimeParameterInfo", klass_name) == 0) {
MonoReflectionParameterHandle param = MONO_HANDLE_CAST (MonoReflectionParameter, obj);
MonoObjectHandle member_impl = MONO_HANDLE_NEW (MonoObject, NULL);
int position;
mono_reflection_get_param_info_member_and_pos (param, member_impl, &position);
MonoClass *member_class = mono_handle_class (member_impl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethodHandle rmethod = MONO_HANDLE_CAST (MonoReflectionMethod, member_impl);
cinfo = mono_custom_attrs_from_param_checked (MONO_HANDLE_GETVAL (rmethod, method), position + 1, error);
goto_if_nok (error, leave);
} else if (mono_is_sr_mono_property (member_class)) {
MonoReflectionPropertyHandle prop = MONO_HANDLE_CAST (MonoReflectionProperty, member_impl);
MonoProperty *property = MONO_HANDLE_GETVAL (prop, property);
MonoMethod *method;
if (!(method = property->get))
method = property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param_checked (method, position + 1, error);
goto_if_nok (error, leave);
}
#ifndef DISABLE_REFLECTION_EMIT
else if (mono_is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
// FIXME: Is this still needed ?
g_assert_not_reached ();
} else if (mono_is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
// FIXME: Is this still needed ?
g_assert_not_reached ();
}
#endif
else {
char *type_name = mono_type_get_full_name (member_class);
mono_error_set_not_supported (error,
"Custom attributes on a ParamInfo with member %s are not supported",
type_name);
g_free (type_name);
goto leave;
}
} else if (strcmp ("AssemblyBuilder", klass_name) == 0) {
MonoReflectionAssemblyBuilderHandle assemblyb = MONO_HANDLE_CAST (MonoReflectionAssemblyBuilder, obj);
MonoReflectionAssemblyHandle assembly = MONO_HANDLE_CAST (MonoReflectionAssembly, assemblyb);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, assemblyb, cattrs);
MonoImage * image = MONO_HANDLE_GETVAL (assembly, assembly)->image;
g_assert (image);
cinfo = mono_custom_attrs_from_builders_handle (NULL, image, cattrs);
} else if (strcmp ("TypeBuilder", klass_name) == 0) {
MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, obj);
MonoReflectionModuleBuilderHandle module = MONO_HANDLE_NEW_GET (MonoReflectionModuleBuilder, tb, module);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (module, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, tb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("ModuleBuilder", klass_name) == 0) {
MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionModuleBuilder, obj);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, mb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("ConstructorBuilder", klass_name) == 0) {
mono_error_set_not_supported (error, "");
goto leave;
} else if (strcmp ("MethodBuilder", klass_name) == 0) {
MonoReflectionMethodBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionMethodBuilder, obj);
MonoMethod *mhandle = MONO_HANDLE_GETVAL (mb, mhandle);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, mb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, m_class_get_image (mhandle->klass), cattrs);
} else if (strcmp ("FieldBuilder", klass_name) == 0) {
MonoReflectionFieldBuilderHandle fb = MONO_HANDLE_CAST (MonoReflectionFieldBuilder, obj);
MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, MONO_HANDLE_NEW_GET (MonoReflectionType, fb, typeb));
MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW_GET (MonoReflectionModuleBuilder, tb, module);
MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image);
MonoArrayHandle cattrs = MONO_HANDLE_NEW_GET (MonoArray, fb, cattrs);
cinfo = mono_custom_attrs_from_builders_handle (NULL, &dynamic_image->image, cattrs);
} else if (strcmp ("MonoGenericClass", klass_name) == 0) {
MonoReflectionGenericClassHandle gclass = MONO_HANDLE_CAST (MonoReflectionGenericClass, obj);
MonoReflectionTypeHandle generic_type = MONO_HANDLE_NEW_GET (MonoReflectionType, gclass, generic_type);
cinfo = mono_reflection_get_custom_attrs_info_checked (MONO_HANDLE_CAST (MonoObject, generic_type), error);
goto_if_nok (error, leave);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", m_class_get_name (klass));
}
leave:
HANDLE_FUNCTION_RETURN_VAL (cinfo);
}
/**
* mono_reflection_get_custom_attrs_by_type:
* \param obj a reflection object handle
* \returns an array with all the custom attributes defined of the
* reflection handle \p obj. If \p attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj_raw, MonoClass *attr_klass, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_by_type_handle (obj, attr_klass, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
MonoArrayHandle
mono_reflection_get_custom_attrs_by_type_handle (MonoObjectHandle obj, MonoClass *attr_klass, MonoError *error)
{
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
MonoCustomAttrInfo *cinfo;
error_init (error);
cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
goto_if_nok (error, leave);
if (cinfo) {
MONO_HANDLE_ASSIGN (result, mono_custom_attrs_construct_by_type (cinfo, attr_klass, error));
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
MONO_HANDLE_ASSIGN (result, mono_array_new_handle (mono_defaults.attribute_class, 0, error));
}
leave:
return result;
}
/**
* mono_reflection_get_custom_attrs:
* \param obj a reflection object handle
* \return an array with all the custom attributes defined of the
* reflection handle \p obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_by_type_handle (obj, NULL, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_reflection_get_custom_attrs_data:
* \param obj a reflection obj handle
* \returns an array of \c System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj_raw)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoArrayHandle result = mono_reflection_get_custom_attrs_data_checked (obj, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/*
* mono_reflection_get_custom_attrs_data_checked:
* @obj: a reflection obj handle
* @error: set on error
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArrayHandle
mono_reflection_get_custom_attrs_data_checked (MonoObjectHandle obj, MonoError *error)
{
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info_checked (obj, error);
goto_if_nok (error, leave);
if (cinfo) {
MONO_HANDLE_ASSIGN (result, mono_custom_attrs_data_construct (cinfo, error));
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
goto_if_nok (error, leave);
} else {
MonoClass *cattr_data = try_get_cattr_data_class (error);
goto_if_nok (error, return_null);
MONO_HANDLE_ASSIGN (result, mono_array_new_handle (cattr_data, 0, error));
}
goto leave;
return_null:
result = MONO_HANDLE_CAST (MonoArray, mono_new_null ());
leave:
return result;
}
static gboolean
custom_attr_class_name_from_methoddef (MonoImage *image, guint32 method_token, const gchar **nspace, const gchar **class_name)
{
/* mono_get_method_from_token () */
g_assert (mono_metadata_token_table (method_token) == MONO_TABLE_METHOD);
guint32 type_token = mono_metadata_typedef_from_method (image, method_token);
if (!type_token) {
/* Bad method token (could not find corresponding typedef) */
return FALSE;
}
type_token |= MONO_TOKEN_TYPE_DEF;
{
/* mono_class_create_from_typedef () */
MonoTableInfo *tt = &image->tables [MONO_TABLE_TYPEDEF];
guint32 cols [MONO_TYPEDEF_SIZE];
guint tidx = mono_metadata_token_index (type_token);
if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || mono_metadata_table_bounds_check (image, MONO_TABLE_TYPEDEF, tidx)) {
/* "Invalid typedef token %x", type_token */
return FALSE;
}
mono_metadata_decode_row (tt, tidx - 1, cols, MONO_TYPEDEF_SIZE);
if (class_name)
*class_name = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
if (nspace)
*nspace = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
return TRUE;
}
}
/**
* custom_attr_class_name_from_method_token:
* @image: The MonoImage
* @method_token: a token for a custom attr constructor in @image
* @assembly_token: out argument set to the assembly ref token of the custom attr
* @nspace: out argument set to namespace (a string in the string heap of @image) of the custom attr
* @class_name: out argument set to the class name of the custom attr.
*
* Given an @image and a @method_token (which is assumed to be a
* constructor), fills in the out arguments with the assembly ref (if
* a methodref) and the namespace and class name of the custom
* attribute.
*
* Returns: TRUE on success, FALSE otherwise.
*
* LOCKING: does not take locks
*/
static gboolean
custom_attr_class_name_from_method_token (MonoImage *image, guint32 method_token, guint32 *assembly_token, const gchar **nspace, const gchar **class_name)
{
/* This only works with method tokens constructed from a
* custom attr token, which can only be methoddef or
* memberref */
g_assert (mono_metadata_token_table (method_token) == MONO_TABLE_METHOD
|| mono_metadata_token_table (method_token) == MONO_TABLE_MEMBERREF);
if (mono_metadata_token_table (method_token) == MONO_TABLE_MEMBERREF) {
/* method_from_memberref () */
guint32 cols[6];
guint32 nindex, class_index;
int idx = mono_metadata_token_index (method_token);
mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
if (class_index == MONO_MEMBERREF_PARENT_TYPEREF) {
guint32 type_token = MONO_TOKEN_TYPE_REF | nindex;
/* mono_class_from_typeref_checked () */
{
guint32 cols [MONO_TYPEREF_SIZE];
MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEREF];
mono_metadata_decode_row (t, (type_token&0xffffff)-1, cols, MONO_TYPEREF_SIZE);
if (class_name)
*class_name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
if (nspace)
*nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
if (assembly_token)
*assembly_token = cols [MONO_TYPEREF_SCOPE];
return TRUE;
}
} else if (class_index == MONO_MEMBERREF_PARENT_METHODDEF) {
guint32 methoddef_token = MONO_TOKEN_METHOD_DEF | nindex;
if (assembly_token)
*assembly_token = 0;
return custom_attr_class_name_from_methoddef (image, methoddef_token, nspace, class_name);
} else {
/* Attributes can't be generic, so it won't be
* a typespec, and they're always
* constructors, so it won't be a moduleref */
g_assert_not_reached ();
}
} else {
/* must be MONO_TABLE_METHOD */
if (assembly_token)
*assembly_token = 0;
return custom_attr_class_name_from_methoddef (image, method_token, nspace, class_name);
}
}
/**
* mono_assembly_metadata_foreach_custom_attr:
* \param assembly the assembly to iterate over
* \param func the function to call for each custom attribute
* \param user_data passed to \p func
* Calls \p func for each custom attribute type on the given assembly until \p func returns TRUE.
* Everything is done using low-level metadata APIs, so it is safe to use during assembly loading.
*/
void
mono_assembly_metadata_foreach_custom_attr (MonoAssembly *assembly, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
MonoImage *image;
guint32 idx;
/*
* This might be called during assembly loading, so do everything using the low-level
* metadata APIs.
*/
image = assembly->image;
/* Dynamic images would need to go through the AssemblyBuilder's
* CustomAttributeBuilder array. Going through the tables below
* definitely won't work. */
g_assert (!image_is_dynamic (image));
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
/**
* iterate over the custom attributes that belong to the given index and call func, passing the
* assembly ref (if any) and the namespace and name of the custom attribute.
*
* Everything is done using low-level metadata APIs, so it is safe to use
* during assembly loading and class initialization.
*/
void
metadata_foreach_custom_attr_from_index (MonoImage *image, guint32 idx, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
guint32 mtoken, i;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
/* Inlined from mono_custom_attrs_from_index_checked () */
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return;
i --;
gboolean stop_iterating = FALSE;
int rows = table_info_get_rows (ca);
while (!stop_iterating && i < rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
mono_metadata_decode_row (ca, i, cols, MONO_CUSTOM_ATTR_SIZE);
i ++;
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_warning ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
continue;
}
const char *nspace = NULL;
const char *name = NULL;
guint32 assembly_token = 0;
if (!custom_attr_class_name_from_method_token (image, mtoken, &assembly_token, &nspace, &name))
continue;
stop_iterating = func (image, assembly_token, nspace, name, mtoken, user_data);
}
}
/**
* mono_class_metadata_foreach_custom_attr:
* \param klass - the class to iterate over
* \param func the funciton to call for each custom attribute
* \param user_data passed to \p func
*
* Calls \p func for each custom attribute type on the given class until \p func returns TRUE.
*
* Everything is done using low-level metadata APIs, so it is fafe to use
* during assembly loading and class initialization.
*
* The MonoClass \p klass should have the following fields initialized:
*
* \c MonoClass:kind, \c MonoClass:image, \c MonoClassGenericInst:generic_class,
* \c MonoClass:type_token, \c MonoClass:sizes.generic_param_token, MonoClass:byval_arg
*/
void
mono_class_metadata_foreach_custom_attr (MonoClass *klass, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
MonoImage *image = m_class_get_image (klass);
/* dynamic images don't store custom attributes in tables */
g_assert (!image_is_dynamic (image));
if (mono_class_is_ginst (klass))
klass = mono_class_get_generic_class (klass)->container_class;
guint32 idx = custom_attrs_idx_from_class (klass);
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
/**
* mono_method_metadata_foreach_custom_attr:
* \param method - the method to iterate over
* \param func the funciton to call for each custom attribute
* \param user_data passed to \p func
*
* Calls \p func for each custom attribute type on the given class until \p func returns TRUE.
*
* Everything is done using low-level metadata APIs, so it is fafe to use
* during assembly loading and class initialization.
*
*/
void
mono_method_metadata_foreach_custom_attr (MonoMethod *method, MonoAssemblyMetadataCustomAttrIterFunc func, gpointer user_data)
{
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
MonoImage *image = m_class_get_image (method->klass);
g_assert (!image_is_dynamic (image));
if (!method->token)
return;
guint32 idx = custom_attrs_idx_from_method (method);
metadata_foreach_custom_attr_from_index (image, idx, func, user_data);
}
#ifdef ENABLE_WEAK_ATTR
static void
init_weak_fields_inner (MonoImage *image, GHashTable *indexes)
{
MonoTableInfo *tdef;
ERROR_DECL (error);
MonoClass *klass = NULL;
guint32 memberref_index = -1;
int first_method_idx = -1;
int method_count = -1;
if (image == mono_get_corlib ()) {
/* Typedef */
klass = mono_class_from_name_checked (image, "System", "WeakAttribute", error);
if (!is_ok (error)) {
mono_error_cleanup (error);
return;
}
if (!klass)
return;
first_method_idx = mono_class_get_first_method_idx (klass);
method_count = mono_class_get_method_count (klass);
tdef = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
guint32 parent, field_idx, col, mtoken, idx;
int rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
parent = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_PARENT);
if ((parent & MONO_CUSTOM_ATTR_MASK) != MONO_CUSTOM_ATTR_FIELDDEF)
continue;
col = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_TYPE);
mtoken = col >> MONO_CUSTOM_ATTR_TYPE_BITS;
/* 1 based index */
idx = mtoken - 1;
if ((col & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
field_idx = parent >> MONO_CUSTOM_ATTR_BITS;
if (idx >= first_method_idx && idx < first_method_idx + method_count)
g_hash_table_insert (indexes, GUINT_TO_POINTER (field_idx), GUINT_TO_POINTER (1));
}
}
} else {
/* FIXME: metadata-update */
/* Memberref pointing to a typeref */
tdef = &image->tables [MONO_TABLE_MEMBERREF];
/* Check whenever the assembly references the WeakAttribute type */
gboolean found = FALSE;
tdef = &image->tables [MONO_TABLE_TYPEREF];
int rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
guint32 string_offset = mono_metadata_decode_row_col (tdef, i, MONO_TYPEREF_NAME);
const char *name = mono_metadata_string_heap (image, string_offset);
if (!strcmp (name, "WeakAttribute")) {
found = TRUE;
break;
}
}
if (!found)
return;
/* Find the memberref pointing to a typeref */
tdef = &image->tables [MONO_TABLE_MEMBERREF];
rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
guint32 cols [MONO_MEMBERREF_SIZE];
const char *sig;
mono_metadata_decode_row (tdef, i, cols, MONO_MEMBERREF_SIZE);
sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
mono_metadata_decode_blob_size (sig, &sig);
guint32 nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
guint32 class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
if (!strcmp (fname, ".ctor") && class_index == MONO_MEMBERREF_PARENT_TYPEREF) {
MonoTableInfo *typeref_table = &image->tables [MONO_TABLE_TYPEREF];
guint32 cols [MONO_TYPEREF_SIZE];
mono_metadata_decode_row (typeref_table, nindex - 1, cols, MONO_TYPEREF_SIZE);
const char *name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
const char *nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
if (!strcmp (nspace, "System") && !strcmp (name, "WeakAttribute")) {
MonoClass *klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
return;
}
g_assert (!strcmp (m_class_get_name (klass), "WeakAttribute"));
/* Allow a testing dll as well since some profiles don't have WeakAttribute */
if (klass && (m_class_get_image (klass) == mono_get_corlib () || strstr (m_class_get_image (klass)->name, "Mono.Runtime.Testing"))) {
/* Sanity check that it only has 1 ctor */
gpointer iter = NULL;
int count = 0;
MonoMethod *method;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, ".ctor"))
count ++;
}
count ++;
memberref_index = i;
break;
}
}
}
}
if (memberref_index == -1)
return;
tdef = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
guint32 parent, field_idx, col, mtoken, idx;
rows = table_info_get_rows (tdef);
for (int i = 0; i < rows; ++i) {
parent = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_PARENT);
if ((parent & MONO_CUSTOM_ATTR_MASK) != MONO_CUSTOM_ATTR_FIELDDEF)
continue;
col = mono_metadata_decode_row_col (tdef, i, MONO_CUSTOM_ATTR_TYPE);
mtoken = col >> MONO_CUSTOM_ATTR_TYPE_BITS;
/* 1 based index */
idx = mtoken - 1;
field_idx = parent >> MONO_CUSTOM_ATTR_BITS;
if ((col & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_MEMBERREF) {
if (idx == memberref_index)
g_hash_table_insert (indexes, GUINT_TO_POINTER (field_idx), GUINT_TO_POINTER (1));
}
}
}
}
#endif
/*
* mono_assembly_init_weak_fields:
*
* Initialize the image->weak_field_indexes hash.
*/
void
mono_assembly_init_weak_fields (MonoImage *image)
{
#ifdef ENABLE_WEAK_ATTR
if (image->weak_fields_inited)
return;
GHashTable *indexes = NULL;
if (mono_get_runtime_callbacks ()->get_weak_field_indexes)
indexes = mono_get_runtime_callbacks ()->get_weak_field_indexes (image);
if (!indexes) {
indexes = g_hash_table_new (NULL, NULL);
/*
* To avoid lookups for every field, we scan the customattr table for entries whose
* parent is a field and whose type is WeakAttribute.
*/
init_weak_fields_inner (image, indexes);
}
mono_image_lock (image);
if (!image->weak_fields_inited) {
image->weak_field_indexes = indexes;
mono_memory_barrier ();
image->weak_fields_inited = TRUE;
} else {
g_hash_table_destroy (indexes);
}
mono_image_unlock (image);
#endif
}
/*
* mono_assembly_is_weak_field:
*
* Return whenever the FIELD table entry with the 1-based index FIELD_IDX has
* a [Weak] attribute.
*/
gboolean
mono_assembly_is_weak_field (MonoImage *image, guint32 field_idx)
{
#ifdef ENABLE_WEAK_ATTR
if (image->dynamic)
return FALSE;
mono_assembly_init_weak_fields (image);
/* The hash is not mutated, no need to lock */
return g_hash_table_lookup (image->weak_field_indexes, GINT_TO_POINTER (field_idx)) != NULL;
#else
g_assert_not_reached ();
#endif
}
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/image.c | /**
* \file
* Routines for manipulating an image stored in an
* extended PE/COFF file.
*
* 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 <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <mono/metadata/image.h>
#include "cil-coff.h"
#include "mono-endian.h"
#include "tabledefs.h"
#include <mono/metadata/tokentype.h>
#include "metadata-internals.h"
#include "metadata-update.h"
#include "profiler-private.h"
#include <mono/metadata/loader.h>
#include "marshal.h"
#include "coree.h"
#include <mono/metadata/exception-internals.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-errno.h>
#include <mono/utils/mono-path.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-proclib.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/image-internals.h>
#include <mono/metadata/loaded-images-internals.h>
#include <mono/metadata/metadata-update.h>
#include <mono/metadata/debug-internals.h>
#include <mono/metadata/mono-private-unstable.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <mono/metadata/w32error.h>
#define INVALID_ADDRESS 0xffffffff
// Amount initially reserved in each image's mempool.
// FIXME: This number is arbitrary, a more practical number should be found
#define INITIAL_IMAGE_SIZE 512
// Change the assembly set in `image` to the assembly set in `assemblyImage`. Halt if overwriting is attempted.
// Can be used on modules loaded through either the "file" or "module" mechanism
static gboolean
assign_assembly_parent_for_netmodule (MonoImage *image, MonoImage *assemblyImage, MonoError *error)
{
// Assembly to assign
MonoAssembly *assembly = assemblyImage->assembly;
while (1) {
// Assembly currently assigned
MonoAssembly *assemblyOld = image->assembly;
if (assemblyOld) {
if (assemblyOld == assembly)
return TRUE;
mono_error_set_bad_image (error, assemblyImage, "Attempted to load module %s which has already been loaded by assembly %s. This is not supported in Mono.", image->name, assemblyOld->image->name);
return FALSE;
}
gpointer result = mono_atomic_xchg_ptr((gpointer *)&image->assembly, assembly);
if (result == assembly)
return TRUE;
}
}
static gboolean debug_assembly_unload = FALSE;
#define mono_images_storage_lock() do { if (mutex_inited) mono_os_mutex_lock (&images_storage_mutex); } while (0)
#define mono_images_storage_unlock() do { if (mutex_inited) mono_os_mutex_unlock (&images_storage_mutex); } while (0)
static gboolean mutex_inited;
static mono_mutex_t images_mutex;
static mono_mutex_t images_storage_mutex;
void
mono_images_lock (void)
{
if (mutex_inited)
mono_os_mutex_lock (&images_mutex);
}
void
mono_images_unlock(void)
{
if (mutex_inited)
mono_os_mutex_unlock (&images_mutex);
}
static MonoImage *
mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
/* Maps string keys to MonoImageStorage values.
*
* The MonoImageStorage in the hash owns the key.
*/
static GHashTable *images_storage_hash;
static void install_pe_loader (void);
typedef struct ImageUnloadHook ImageUnloadHook;
struct ImageUnloadHook {
MonoImageUnloadFunc func;
gpointer user_data;
};
static GSList *image_unload_hooks;
void
mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
{
ImageUnloadHook *hook;
g_return_if_fail (func != NULL);
hook = g_new0 (ImageUnloadHook, 1);
hook->func = func;
hook->user_data = user_data;
image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
}
void
mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
{
GSList *l;
ImageUnloadHook *hook;
for (l = image_unload_hooks; l; l = l->next) {
hook = (ImageUnloadHook *)l->data;
if (hook->func == func && hook->user_data == user_data) {
g_free (hook);
image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
break;
}
}
}
static void
mono_image_invoke_unload_hook (MonoImage *image)
{
GSList *l;
ImageUnloadHook *hook;
for (l = image_unload_hooks; l; l = l->next) {
hook = (ImageUnloadHook *)l->data;
hook->func (image, hook->user_data);
}
}
static GSList *image_loaders;
void
mono_install_image_loader (const MonoImageLoader *loader)
{
image_loaders = g_slist_prepend (image_loaders, (MonoImageLoader*)loader);
}
/* returns offset relative to image->raw_data */
guint32
mono_cli_rva_image_map (MonoImage *image, guint32 addr)
{
MonoCLIImageInfo *iinfo = image->image_info;
const int top = iinfo->cli_section_count;
MonoSectionTable *tables = iinfo->cli_section_tables;
int i;
if (image->metadata_only)
return addr;
for (i = 0; i < top; i++){
if ((addr >= tables->st_virtual_address) &&
(addr < tables->st_virtual_address + tables->st_raw_data_size)){
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
return addr;
#endif
return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
}
tables++;
}
return INVALID_ADDRESS;
}
/**
* mono_image_rva_map:
* \param image a \c MonoImage
* \param addr relative virtual address (RVA)
*
* This is a low-level routine used by the runtime to map relative
* virtual address (RVA) into their location in memory.
*
* \returns the address in memory for the given RVA, or NULL if the
* RVA is not valid for this image.
*/
char *
mono_image_rva_map (MonoImage *image, guint32 addr)
{
MonoCLIImageInfo *iinfo = image->image_info;
const int top = iinfo->cli_section_count;
MonoSectionTable *tables = iinfo->cli_section_tables;
int i;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image)) {
if (addr && addr < image->raw_data_len)
return image->raw_data + addr;
else
return NULL;
}
#endif
for (i = 0; i < top; i++){
if ((addr >= tables->st_virtual_address) &&
(addr < tables->st_virtual_address + tables->st_raw_data_size)){
if (!iinfo->cli_sections [i]) {
if (!mono_image_ensure_section_idx (image, i))
return NULL;
}
return (char*)iinfo->cli_sections [i] +
(addr - tables->st_virtual_address);
}
tables++;
}
return NULL;
}
/**
* mono_images_init:
*
* Initialize the global variables used by this module.
*/
void
mono_images_init (void)
{
mono_os_mutex_init (&images_storage_mutex);
mono_os_mutex_init_recursive (&images_mutex);
images_storage_hash = g_hash_table_new (g_str_hash, g_str_equal);
debug_assembly_unload = g_hasenv ("MONO_DEBUG_ASSEMBLY_UNLOAD");
install_pe_loader ();
mutex_inited = TRUE;
}
/**
* mono_images_cleanup:
*
* Free all resources used by this module.
*/
void
mono_images_cleanup (void)
{
}
/**
* mono_image_ensure_section_idx:
* \param image The image we are operating on
* \param section section number that we will load/map into memory
*
* This routine makes sure that we have an in-memory copy of
* an image section (<code>.text</code>, <code>.rsrc</code>, <code>.data</code>).
*
* \returns TRUE on success
*/
int
mono_image_ensure_section_idx (MonoImage *image, int section)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoSectionTable *sect;
g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
if (iinfo->cli_sections [section] != NULL)
return TRUE;
sect = &iinfo->cli_section_tables [section];
if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
return FALSE;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
else
#endif
/* FIXME: we ignore the writable flag since we don't patch the binary */
iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
return TRUE;
}
/**
* mono_image_ensure_section:
* \param image The image we are operating on
* \param section section name that we will load/map into memory
*
* This routine makes sure that we have an in-memory copy of
* an image section (.text, .rsrc, .data).
*
* \returns TRUE on success
*/
int
mono_image_ensure_section (MonoImage *image, const char *section)
{
MonoCLIImageInfo *ii = image->image_info;
int i;
for (i = 0; i < ii->cli_section_count; i++){
if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
continue;
return mono_image_ensure_section_idx (image, i);
}
return FALSE;
}
static int
load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
{
const int top = iinfo->cli_header.coff.coff_sections;
int i;
iinfo->cli_section_count = top;
iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
iinfo->cli_sections = g_new0 (void *, top);
for (i = 0; i < top; i++){
MonoSectionTable *t = &iinfo->cli_section_tables [i];
if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
return FALSE;
memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
offset += sizeof (MonoSectionTable);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
t->st_flags = GUINT32_FROM_LE (t->st_flags);
#endif
/* consistency checks here */
}
return TRUE;
}
gboolean
mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
{
guint32 offset;
offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
if (offset == INVALID_ADDRESS)
return FALSE;
if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
return FALSE;
memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
SWAP32 (iinfo->cli_cli_header.ch_size);
SWAP32 (iinfo->cli_cli_header.ch_flags);
SWAP32 (iinfo->cli_cli_header.ch_entry_point);
SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
SWAPPDE (iinfo->cli_cli_header.ch_metadata);
SWAPPDE (iinfo->cli_cli_header.ch_resources);
SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
SWAPPDE (iinfo->cli_cli_header.ch_module_image);
SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
#undef SWAP32
#undef SWAP16
#undef SWAPPDE
#endif
/* Catch new uses of the fields that are supposed to be zero */
if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
(iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
(iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
(iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
(iinfo->cli_cli_header.ch_module_image.rva != 0) ||
(iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
(iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
(iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
(iinfo->cli_cli_header.ch_ip_map.rva != 0)){
/*
* No need to scare people who are testing this, I am just
* labelling this as a LAMESPEC
*/
/* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
}
return TRUE;
}
/**
* mono_metadata_module_mvid:
*
* Return the module mvid GUID or NULL if the image doesn't have a module table.
*/
static const guint8 *
mono_metadata_module_mvid (MonoImage *image)
{
if (!image->tables [MONO_TABLE_MODULE].base)
return NULL;
guint32 module_cols [MONO_MODULE_SIZE];
mono_metadata_decode_row (&image->tables [MONO_TABLE_MODULE], 0, module_cols, MONO_MODULE_SIZE);
return (const guint8*) mono_metadata_guid_heap (image, module_cols [MONO_MODULE_MVID]);
}
static gboolean
load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
{
guint32 offset, size;
guint16 streams;
int i;
guint32 pad;
char *ptr;
offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
if (offset == INVALID_ADDRESS)
return FALSE;
size = iinfo->cli_cli_header.ch_metadata.size;
if (offset + size > image->raw_data_len)
return FALSE;
image->raw_metadata = image->raw_data + offset;
/* 24.2.1: Metadata root starts here */
ptr = image->raw_metadata;
if (strncmp (ptr, "BSJB", 4) == 0){
guint32 version_string_len;
ptr += 4;
image->md_version_major = read16 (ptr);
ptr += 2;
image->md_version_minor = read16 (ptr);
ptr += 6;
version_string_len = read32 (ptr);
ptr += 4;
image->version = g_strndup (ptr, version_string_len);
ptr += version_string_len;
pad = ptr - image->raw_metadata;
if (pad % 4)
ptr += 4 - (pad % 4);
} else
return FALSE;
/* skip over flags */
ptr += 2;
streams = read16 (ptr);
ptr += 2;
for (i = 0; i < streams; i++){
if (strncmp (ptr + 8, "#~", 3) == 0){
image->heap_tables.data = image->raw_metadata + read32 (ptr);
image->heap_tables.size = read32 (ptr + 4);
ptr += 8 + 3;
} else if (strncmp (ptr + 8, "#Strings", 9) == 0){
image->heap_strings.data = image->raw_metadata + read32 (ptr);
image->heap_strings.size = read32 (ptr + 4);
ptr += 8 + 9;
} else if (strncmp (ptr + 8, "#US", 4) == 0){
image->heap_us.data = image->raw_metadata + read32 (ptr);
image->heap_us.size = read32 (ptr + 4);
ptr += 8 + 4;
} else if (strncmp (ptr + 8, "#Blob", 6) == 0){
image->heap_blob.data = image->raw_metadata + read32 (ptr);
image->heap_blob.size = read32 (ptr + 4);
ptr += 8 + 6;
} else if (strncmp (ptr + 8, "#GUID", 6) == 0){
image->heap_guid.data = image->raw_metadata + read32 (ptr);
image->heap_guid.size = read32 (ptr + 4);
ptr += 8 + 6;
} else if (strncmp (ptr + 8, "#-", 3) == 0) {
image->heap_tables.data = image->raw_metadata + read32 (ptr);
image->heap_tables.size = read32 (ptr + 4);
ptr += 8 + 3;
image->uncompressed_metadata = TRUE;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
} else if (strncmp (ptr + 8, "#Pdb", 5) == 0) {
image->heap_pdb.data = image->raw_metadata + read32 (ptr);
image->heap_pdb.size = read32 (ptr + 4);
ptr += 8 + 5;
} else if (strncmp (ptr + 8, "#JTD", 5) == 0) {
// See https://github.com/dotnet/runtime/blob/110282c71b3f7e1f91ea339953f4a0eba362a62c/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs#L165-L175
// skip read32(ptr) and read32(ptr + 4)
// ignore the content of this stream
image->minimal_delta = TRUE;
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Image '%s' has a minimal delta marker", image->name);
ptr += 8 + 5;
} else {
g_message ("Unknown heap type: %s\n", ptr + 8);
ptr += 8 + strlen (ptr + 8) + 1;
}
pad = ptr - image->raw_metadata;
if (pad % 4)
ptr += 4 - (pad % 4);
}
{
/* Compute the precise size of the string heap by walking back over the trailing nul padding.
*
* ENC minimal delta images require the precise size of the base image string heap to be known.
*/
const char *p;
p = image->heap_strings.data + image->heap_strings.size - 1;
pad = 0;
while (p [0] == '\0' && p [-1] == '\0') {
p--;
pad++;
}
image->heap_strings.size -= pad;
}
i = ((MonoImageLoader*)image->loader)->load_tables (image);
if (!image->metadata_only) {
g_assert (image->heap_guid.data);
g_assert (image->heap_guid.size >= 16);
image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
} else {
const guint8 *guid = mono_metadata_module_mvid (image);
if (guid)
image->guid = mono_guid_to_string (guid);
else {
/* PPDB files have no guid */
guint8 empty_guid [16];
memset (empty_guid, 0, sizeof (empty_guid));
image->guid = mono_guid_to_string (empty_guid);
}
}
return i;
}
/*
* Load representation of logical metadata tables, from the "#~" or "#-" stream
*/
static gboolean
load_tables (MonoImage *image)
{
const char *heap_tables = image->heap_tables.data;
const guint32 *rows;
guint64 valid_mask;
int valid = 0, table;
int heap_sizes;
heap_sizes = heap_tables [6];
image->idx_string_wide = ((heap_sizes & 0x01) == 1);
image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
if (G_UNLIKELY (image->minimal_delta)) {
/* sanity check */
g_assert (image->idx_string_wide);
g_assert (image->idx_guid_wide);
g_assert (image->idx_blob_wide);
}
valid_mask = read64 (heap_tables + 8);
rows = (const guint32 *) (heap_tables + 24);
for (table = 0; table < 64; table++){
if ((valid_mask & ((guint64) 1 << table)) == 0){
if (table > MONO_TABLE_LAST)
continue;
image->tables [table].rows_ = 0;
continue;
}
if (table > MONO_TABLE_LAST) {
g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)");
} else {
image->tables [table].rows_ = read32 (rows);
}
rows++;
valid++;
}
image->tables_base = (heap_tables + 24) + (4 * valid);
/* They must be the same */
g_assert ((const void *) image->tables_base == (const void *) rows);
if (image->heap_pdb.size) {
/*
* Obtain token sizes from the pdb stream.
*/
/* 24 = guid + entry point */
int pos = 24;
image->referenced_tables = read64 (image->heap_pdb.data + pos);
pos += 8;
image->referenced_table_rows = g_new0 (int, 64);
for (int i = 0; i < 64; ++i) {
if (image->referenced_tables & ((guint64)1 << i)) {
image->referenced_table_rows [i] = read32 (image->heap_pdb.data + pos);
pos += 4;
}
}
}
mono_metadata_compute_table_bases (image);
return TRUE;
}
gboolean
mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
{
if (!load_metadata_ptrs (image, iinfo))
return FALSE;
return load_tables (image);
}
void
mono_image_check_for_module_cctor (MonoImage *image)
{
MonoTableInfo *t, *mt;
t = &image->tables [MONO_TABLE_TYPEDEF];
mt = &image->tables [MONO_TABLE_METHOD];
if (image_is_dynamic (image)) {
/* FIXME: */
image->checked_module_cctor = TRUE;
return;
}
if (table_info_get_rows (t) >= 1) {
guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
const char *name = mono_metadata_string_heap (image, nameidx);
if (strcmp (name, "<Module>") == 0) {
guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
guint32 last_method;
if (table_info_get_rows (t) > 1)
last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
else
last_method = table_info_get_rows (mt);
for (; first_method < last_method; first_method++) {
nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
name = mono_metadata_string_heap (image, nameidx);
if (strcmp (name, ".cctor") == 0) {
image->has_module_cctor = TRUE;
image->checked_module_cctor = TRUE;
return;
}
}
}
}
image->has_module_cctor = FALSE;
image->checked_module_cctor = TRUE;
}
/**
* mono_image_load_module_checked:
*
* Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
* it cannot be loaded. NULL without MonoError being set will be interpreted as "not found".
*/
MonoImage*
mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error)
{
error_init (error);
if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
return NULL;
if (image->modules_loaded [idx - 1])
return image->modules [idx - 1];
/* SRE still uses image->modules, but they are not loaded from files, so the rest of this function is dead code for netcore */
g_assert_not_reached ();
}
/**
* mono_image_load_module:
*/
MonoImage*
mono_image_load_module (MonoImage *image, int idx)
{
ERROR_DECL (error);
MonoImage *result = mono_image_load_module_checked (image, idx, error);
mono_error_assert_ok (error);
return result;
}
static gpointer
class_key_extract (gpointer value)
{
MonoClass *klass = (MonoClass *)value;
return GUINT_TO_POINTER (m_class_get_type_token (klass));
}
static gpointer*
class_next_value (gpointer value)
{
MonoClassDef *klass = (MonoClassDef *)value;
return (gpointer*)m_classdef_get_next_class_cache (klass);
}
/**
* mono_image_init:
*/
void
mono_image_init (MonoImage *image)
{
mono_os_mutex_init_recursive (&image->lock);
mono_os_mutex_init_recursive (&image->szarray_cache_lock);
image->mempool = mono_mempool_new_size (INITIAL_IMAGE_SIZE);
mono_internal_hash_table_init (&image->class_cache,
g_direct_hash,
class_key_extract,
class_next_value);
image->field_cache = mono_conc_hashtable_new (NULL, NULL);
image->typespec_cache = mono_conc_hashtable_new (NULL, NULL);
image->memberref_signatures = g_hash_table_new (NULL, NULL);
image->method_signatures = g_hash_table_new (NULL, NULL);
image->property_hash = mono_property_hash_new ();
}
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
#define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
#else
#define SWAP64(x)
#define SWAP32(x)
#define SWAP16(x)
#define SWAPPDE(x)
#endif
static int
do_load_header_internal (const char *raw_data, guint32 raw_data_len, MonoDotNetHeader *header, int offset, gboolean image_is_module_handle)
{
MonoDotNetHeader64 header64;
#ifdef HOST_WIN32
if (!image_is_module_handle)
#endif
if (offset + sizeof (MonoDotNetHeader32) > raw_data_len)
return -1;
memcpy (header, raw_data + offset, sizeof (MonoDotNetHeader));
if (header->pesig [0] != 'P' || header->pesig [1] != 'E' || header->pesig [2] || header->pesig [3])
return -1;
/* endian swap the fields common between PE and PE+ */
SWAP32 (header->coff.coff_time);
SWAP32 (header->coff.coff_symptr);
SWAP32 (header->coff.coff_symcount);
SWAP16 (header->coff.coff_machine);
SWAP16 (header->coff.coff_sections);
SWAP16 (header->coff.coff_opt_header_size);
SWAP16 (header->coff.coff_attributes);
/* MonoPEHeader */
SWAP32 (header->pe.pe_code_size);
SWAP32 (header->pe.pe_uninit_data_size);
SWAP32 (header->pe.pe_rva_entry_point);
SWAP32 (header->pe.pe_rva_code_base);
SWAP32 (header->pe.pe_rva_data_base);
SWAP16 (header->pe.pe_magic);
/* now we are ready for the basic tests */
if (header->pe.pe_magic == 0x10B) {
offset += sizeof (MonoDotNetHeader);
SWAP32 (header->pe.pe_data_size);
if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
return -1;
SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
SWAP32 (header->nt.pe_stack_reserve);
SWAP32 (header->nt.pe_stack_commit);
SWAP32 (header->nt.pe_heap_reserve);
SWAP32 (header->nt.pe_heap_commit);
} else if (header->pe.pe_magic == 0x20B) {
/* PE32+ file format */
if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
return -1;
memcpy (&header64, raw_data + offset, sizeof (MonoDotNetHeader64));
offset += sizeof (MonoDotNetHeader64);
/* copy the fields already swapped. the last field, pe_data_size, is missing */
memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
/* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
* will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
*/
SWAP64 (header64.nt.pe_image_base);
header->nt.pe_image_base = header64.nt.pe_image_base;
SWAP64 (header64.nt.pe_stack_reserve);
header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
SWAP64 (header64.nt.pe_stack_commit);
header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
SWAP64 (header64.nt.pe_heap_reserve);
header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
SWAP64 (header64.nt.pe_heap_commit);
header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
header->nt.pe_section_align = header64.nt.pe_section_align;
header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
header->nt.pe_os_major = header64.nt.pe_os_major;
header->nt.pe_os_minor = header64.nt.pe_os_minor;
header->nt.pe_user_major = header64.nt.pe_user_major;
header->nt.pe_user_minor = header64.nt.pe_user_minor;
header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
header->nt.pe_image_size = header64.nt.pe_image_size;
header->nt.pe_header_size = header64.nt.pe_header_size;
header->nt.pe_checksum = header64.nt.pe_checksum;
header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
/* copy the datadir */
memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
} else {
return -1;
}
/* MonoPEHeaderNT: not used yet */
SWAP32 (header->nt.pe_section_align); /* must be 8192 */
SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
SWAP16 (header->nt.pe_os_major); /* must be 4 */
SWAP16 (header->nt.pe_os_minor); /* must be 0 */
SWAP16 (header->nt.pe_user_major);
SWAP16 (header->nt.pe_user_minor);
SWAP16 (header->nt.pe_subsys_major);
SWAP16 (header->nt.pe_subsys_minor);
SWAP32 (header->nt.pe_reserved_1);
SWAP32 (header->nt.pe_image_size);
SWAP32 (header->nt.pe_header_size);
SWAP32 (header->nt.pe_checksum);
SWAP16 (header->nt.pe_subsys_required);
SWAP16 (header->nt.pe_dll_flags);
SWAP32 (header->nt.pe_loader_flags);
SWAP32 (header->nt.pe_data_dir_count);
/* MonoDotNetHeader: mostly unused */
SWAPPDE (header->datadir.pe_export_table);
SWAPPDE (header->datadir.pe_import_table);
SWAPPDE (header->datadir.pe_resource_table);
SWAPPDE (header->datadir.pe_exception_table);
SWAPPDE (header->datadir.pe_certificate_table);
SWAPPDE (header->datadir.pe_reloc_table);
SWAPPDE (header->datadir.pe_debug);
SWAPPDE (header->datadir.pe_copyright);
SWAPPDE (header->datadir.pe_global_ptr);
SWAPPDE (header->datadir.pe_tls_table);
SWAPPDE (header->datadir.pe_load_config_table);
SWAPPDE (header->datadir.pe_bound_import);
SWAPPDE (header->datadir.pe_iat);
SWAPPDE (header->datadir.pe_delay_import_desc);
SWAPPDE (header->datadir.pe_cli_header);
SWAPPDE (header->datadir.pe_reserved);
return offset;
}
/*
* Returns < 0 to indicate an error.
*/
static int
do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
{
offset = do_load_header_internal (image->raw_data, image->raw_data_len, header, offset,
#ifdef HOST_WIN32
m_image_is_module_handle (image));
#else
FALSE);
#endif
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
image->storage->raw_data_len = header->nt.pe_image_size;
#endif
return offset;
}
mono_bool
mono_has_pdb_checksum (char *raw_data, uint32_t raw_data_len)
{
MonoDotNetHeader cli_header;
MonoMSDOSHeader msdos;
int idx;
guint8 *data;
int offset = 0;
memcpy (&msdos, raw_data + offset, sizeof (msdos));
if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) {
return FALSE;
}
msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
offset = msdos.pe_offset;
int ret = do_load_header_internal (raw_data, raw_data_len, &cli_header, offset, FALSE);
if ( ret >= 0 ) {
MonoPEDirEntry *debug_dir_entry = (MonoPEDirEntry *) &cli_header.datadir.pe_debug;
ImageDebugDirectory debug_dir;
if (!debug_dir_entry->size)
return FALSE;
else {
const int top = cli_header.coff.coff_sections;
int addr = debug_dir_entry->rva;
int i = 0;
for (i = 0; i < top; i++){
MonoSectionTable t;
if (ret + sizeof (MonoSectionTable) > raw_data_len) {
return FALSE;
}
memcpy (&t, raw_data + ret, sizeof (MonoSectionTable));
ret += sizeof (MonoSectionTable);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
t.st_virtual_address = GUINT32_FROM_LE (t.st_virtual_address);
t.st_raw_data_size = GUINT32_FROM_LE (t.st_raw_data_size);
t.st_raw_data_ptr = GUINT32_FROM_LE (t.st_raw_data_ptr);
#endif
/* consistency checks here */
if ((addr >= t.st_virtual_address) &&
(addr < t.st_virtual_address + t.st_raw_data_size)){
addr = addr - t.st_virtual_address + t.st_raw_data_ptr;
break;
}
}
for (idx = 0; idx < debug_dir_entry->size / sizeof (ImageDebugDirectory); ++idx) {
data = (guint8 *) ((ImageDebugDirectory *) (raw_data + addr) + idx);
debug_dir.characteristics = read32(data);
debug_dir.time_date_stamp = read32(data + 4);
debug_dir.major_version = read16(data + 8);
debug_dir.minor_version = read16(data + 10);
debug_dir.type = read32(data + 12);
if (debug_dir.type == DEBUG_DIR_PDB_CHECKSUM || debug_dir.type == DEBUG_DIR_REPRODUCIBLE)
return TRUE;
}
}
}
return FALSE;
}
gboolean
mono_image_load_pe_data (MonoImage *image)
{
return ((MonoImageLoader*)image->loader)->load_pe_data (image);
}
static gboolean
pe_image_load_pe_data (MonoImage *image)
{
MonoCLIImageInfo *iinfo;
MonoDotNetHeader *header;
MonoMSDOSHeader msdos;
gint32 offset = 0;
iinfo = image->image_info;
header = &iinfo->cli_header;
#ifdef HOST_WIN32
if (!m_image_is_module_handle (image))
#endif
if (offset + sizeof (msdos) > image->raw_data_len)
goto invalid_image;
memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
goto invalid_image;
msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
offset = msdos.pe_offset;
offset = do_load_header (image, header, offset);
if (offset < 0)
goto invalid_image;
/*
* this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
* we skip this test.
if (header->coff.coff_machine != 0x14c)
goto invalid_image;
*/
#if 0
/*
* The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
* which produces binaries with 7.0. From Sergey:
*
* The reason is that MSVC7 uses traditional compile/link
* sequence for CIL executables, and VS.NET (and Framework
* SDK) includes linker version 7, that puts 7.0 in this
* field. That's why it's currently not possible to load VC
* binaries with Mono. This field is pretty much meaningless
* anyway (what linker?).
*/
if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
goto invalid_image;
#endif
/*
* FIXME: byte swap all addresses here for header.
*/
if (!load_section_tables (image, iinfo, offset))
goto invalid_image;
return TRUE;
invalid_image:
return FALSE;
}
gboolean
mono_image_load_cli_data (MonoImage *image)
{
return ((MonoImageLoader*)image->loader)->load_cli_data (image);
}
static gboolean
pe_image_load_cli_data (MonoImage *image)
{
MonoCLIImageInfo *iinfo;
iinfo = image->image_info;
/* Load the CLI header */
if (!mono_image_load_cli_header (image, iinfo))
return FALSE;
if (!mono_image_load_metadata (image, iinfo))
return FALSE;
return TRUE;
}
static void
mono_image_load_time_date_stamp (MonoImage *image)
{
image->time_date_stamp = 0;
#ifndef HOST_WIN32
if (!image->filename)
return;
gunichar2 *uni_name = g_utf8_to_utf16 (image->filename, -1, NULL, NULL, NULL);
mono_pe_file_time_date_stamp (uni_name, &image->time_date_stamp);
g_free (uni_name);
#endif
}
void
mono_image_load_names (MonoImage *image)
{
/* modules don't have an assembly table row */
if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY])) {
image->assembly_name = mono_metadata_string_heap (image,
mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
0, MONO_ASSEMBLY_NAME));
}
/* Portable pdb images don't have a MODULE row */
/* Minimal ENC delta images index the combined string heap of the base and delta image,
* so the module index is out of bounds here.
*/
if (table_info_get_rows (&image->tables [MONO_TABLE_MODULE]) && !image->minimal_delta) {
image->module_name = mono_metadata_string_heap (image,
mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
0, MONO_MODULE_NAME));
}
}
static gboolean
pe_image_load_tables (MonoImage *image)
{
return TRUE;
}
static gboolean
pe_image_match (MonoImage *image)
{
if (image->raw_data [0] == 'M' && image->raw_data [1] == 'Z')
return TRUE;
return FALSE;
}
static const MonoImageLoader pe_loader = {
pe_image_match,
pe_image_load_pe_data,
pe_image_load_cli_data,
pe_image_load_tables,
};
static void
install_pe_loader (void)
{
mono_install_image_loader (&pe_loader);
}
/*
Equivalent C# code:
static void Main () {
string str = "...";
int h = 5381;
for (int i = 0; i < str.Length; ++i)
h = ((h << 5) + h) ^ str[i];
Console.WriteLine ("{0:X}", h);
}
*/
static int
hash_guid (const char *str)
{
int h = 5381;
while (*str) {
h = ((h << 5) + h) ^ *str;
++str;
}
return h;
}
static void
dump_encmap (MonoImage *image)
{
MonoTableInfo *encmap = &image->tables [MONO_TABLE_ENCMAP];
if (!encmap || !table_info_get_rows (encmap))
return;
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ENCMAP for %s", image->filename);
for (int i = 0; i < table_info_get_rows (encmap); ++i) {
guint32 cols [MONO_ENCMAP_SIZE];
mono_metadata_decode_row (encmap, i, cols, MONO_ENCMAP_SIZE);
int token = cols [MONO_ENCMAP_TOKEN];
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%08x: 0x%08x table: %s", i+1, token, mono_meta_table_name (mono_metadata_token_table (token)));
}
}
}
static MonoImage *
do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
gboolean care_about_cli, gboolean care_about_pecoff)
{
ERROR_DECL (error);
GSList *l;
MONO_PROFILER_RAISE (image_loading, (image));
mono_image_init (image);
if (!image->metadata_only) {
for (l = image_loaders; l; l = l->next) {
MonoImageLoader *loader = (MonoImageLoader *)l->data;
if (loader->match (image)) {
image->loader = loader;
break;
}
}
if (!image->loader) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
goto invalid_image;
}
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
if (care_about_pecoff == FALSE)
goto done;
if (!mono_image_load_pe_data (image))
goto invalid_image;
} else {
image->loader = (MonoImageLoader*)&pe_loader;
}
if (care_about_cli == FALSE) {
goto done;
}
if (!mono_image_load_cli_data (image))
goto invalid_image;
dump_encmap (image);
mono_image_load_names (image);
mono_image_load_time_date_stamp (image);
done:
MONO_PROFILER_RAISE (image_loaded, (image));
if (status)
*status = MONO_IMAGE_OK;
return image;
invalid_image:
if (!is_ok (error)) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Could not load image %s due to %s", image->name, mono_error_get_message (error));
mono_error_cleanup (error);
}
MONO_PROFILER_RAISE (image_failed, (image));
mono_image_close (image);
return NULL;
}
static gboolean
mono_image_storage_trypublish (MonoImageStorage *candidate, MonoImageStorage **out_storage)
{
gboolean result;
mono_images_storage_lock ();
MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, candidate->key);
if (val && !mono_refcount_tryinc (val)) {
// We raced against a mono_image_storage_dtor in progress.
val = NULL;
}
if (val) {
*out_storage = val;
result = FALSE;
} else {
g_hash_table_insert (images_storage_hash, candidate->key, candidate);
result = TRUE;
}
mono_images_storage_unlock ();
return result;
}
static void
mono_image_storage_unpublish (MonoImageStorage *storage)
{
mono_images_storage_lock ();
g_assert (storage->ref.ref == 0);
MonoImageStorage *published = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, storage->key);
if (published == storage) {
g_hash_table_remove (images_storage_hash, storage->key);
}
mono_images_storage_unlock ();
}
static gboolean
mono_image_storage_tryaddref (const char *key, MonoImageStorage **found)
{
gboolean result = FALSE;
mono_images_storage_lock ();
MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, key);
if (val && !mono_refcount_tryinc (val)) {
// We raced against a mono_image_storage_dtor in progress.
val = NULL;
}
if (val) {
*found = val;
result = TRUE;
}
mono_images_storage_unlock ();
return result;
}
static void
mono_image_storage_dtor (gpointer self)
{
MonoImageStorage *storage = (MonoImageStorage *)self;
mono_image_storage_unpublish (storage);
#ifdef HOST_WIN32
if (storage->is_module_handle && !storage->has_entry_point) {
mono_images_lock ();
FreeLibrary ((HMODULE) storage->raw_data);
mono_images_unlock ();
}
#endif
if (storage->raw_buffer_used) {
if (storage->raw_data != NULL) {
#ifndef HOST_WIN32
if (storage->fileio_used)
mono_file_unmap_fileio (storage->raw_data, storage->raw_data_handle);
else
#endif
mono_file_unmap (storage->raw_data, storage->raw_data_handle);
}
}
if (storage->raw_data_allocated) {
g_free (storage->raw_data);
}
g_free (storage->key);
g_free (storage);
}
static void
mono_image_storage_close (MonoImageStorage *storage)
{
mono_refcount_dec (storage);
}
static gboolean
mono_image_init_raw_data (MonoImage *image, const MonoImageStorage *storage)
{
if (!storage)
return FALSE;
image->raw_data = storage->raw_data;
image->raw_data_len = storage->raw_data_len;
return TRUE;
}
static MonoImageStorage *
mono_image_storage_open (const char *fname)
{
char *key = NULL;
key = mono_path_resolve_symlinks (fname);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoFileMap *filed;
if ((filed = mono_file_map_open (fname)) == NULL){
g_free (key);
return NULL;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_buffer_used = TRUE;
storage->raw_data_len = mono_file_map_size (filed);
storage->raw_data = (char*)mono_file_map (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle);
#if defined(HAVE_MMAP) && !defined (HOST_WIN32)
if (!storage->raw_data) {
storage->fileio_used = TRUE;
storage->raw_data = (char *)mono_file_map_fileio (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle);
}
#endif
mono_file_map_close (filed);
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
static MonoImageStorage *
mono_image_storage_new_raw_data (char *datac, guint32 data_len, gboolean raw_data_allocated, const char *name)
{
char *key = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_data = datac;
storage->raw_data_len = data_len;
storage->raw_data_allocated = raw_data_allocated;
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
static MonoImage *
do_mono_image_open (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status,
gboolean care_about_cli, gboolean care_about_pecoff, gboolean metadata_only)
{
MonoCLIImageInfo *iinfo;
MonoImage *image;
MonoImageStorage *storage = mono_image_storage_open (fname);
if (!storage) {
if (status)
*status = MONO_IMAGE_ERROR_ERRNO;
return NULL;
}
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
if (!image->raw_data) {
mono_image_storage_close (image->storage);
g_free (image);
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->name = mono_path_resolve_symlinks (fname);
image->filename = g_strdup (image->name);
image->metadata_only = metadata_only;
image->ref_count = 1;
image->alc = alc;
return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
}
/**
* mono_image_loaded_full:
* \param name path or assembly name of the image to load
* \param refonly Check with respect to reflection-only loads?
*
* This routine verifies that the given image is loaded.
* It checks either reflection-only loads only, or normal loads only, as specified by parameter.
*
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded_full (const char *name, gboolean refonly)
{
if (refonly)
return NULL;
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_loaded_internal (mono_alc_get_default (), name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_loaded_internal:
* \param alc The AssemblyLoadContext that should be checked
* \param name path or assembly name of the image to load
* \param refonly Check with respect to reflection-only loads?
*
* This routine verifies that the given image is loaded.
* It checks either reflection-only loads only, or normal loads only, as specified by parameter.
*
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded_internal (MonoAssemblyLoadContext *alc, const char *name)
{
MonoLoadedImages *li = mono_alc_get_loaded_images (alc);
MonoImage *res;
mono_images_lock ();
res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_hash (li), name);
if (!res)
res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_by_name_hash (li), name);
mono_images_unlock ();
return res;
}
/**
* mono_image_loaded:
* \param name path or assembly name of the image to load
* This routine verifies that the given image is loaded. Reflection-only loads do not count.
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded (const char *name)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_loaded_internal (mono_alc_get_default (), name);
MONO_EXIT_GC_UNSAFE;
return result;
}
typedef struct {
MonoImage *res;
const char* guid;
} GuidData;
static void
find_by_guid (gpointer key, gpointer val, gpointer user_data)
{
GuidData *data = (GuidData *)user_data;
MonoImage *image;
if (data->res)
return;
image = (MonoImage *)val;
if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
data->res = image;
}
static MonoImage *
mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly);
/**
* mono_image_loaded_by_guid_full:
*
* Looks only in the global loaded images hash, will miss assemblies loaded
* into an AssemblyLoadContext.
*/
MonoImage *
mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
{
return mono_image_loaded_by_guid_internal (guid, refonly);
}
/**
* mono_image_loaded_by_guid_internal:
*
* Do not use. Looks only in the global loaded images hash, will miss Assembly
* Load Contexts.
*/
static MonoImage *
mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly)
{
/* TODO: Maybe implement this for netcore by searching only the default ALC of the current domain */
return NULL;
}
/**
* mono_image_loaded_by_guid:
*
* Looks only in the global loaded images hash, will miss assemblies loaded
* into an AssemblyLoadContext.
*/
MonoImage *
mono_image_loaded_by_guid (const char *guid)
{
return mono_image_loaded_by_guid_internal (guid, FALSE);
}
static MonoImage *
register_image (MonoLoadedImages *li, MonoImage *image)
{
MonoImage *image2;
char *name = image->name;
GHashTable *loaded_images = mono_loaded_images_get_hash (li);
mono_images_lock ();
image2 = (MonoImage *)g_hash_table_lookup (loaded_images, name);
if (image2) {
/* Somebody else beat us to it */
mono_image_addref (image2);
mono_images_unlock ();
mono_image_close (image);
return image2;
}
GHashTable *loaded_images_by_name = mono_loaded_images_get_by_name_hash (li);
g_hash_table_insert (loaded_images, name, image);
if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == NULL))
g_hash_table_insert (loaded_images_by_name, (char *) image->assembly_name, image);
mono_images_unlock ();
return image;
}
MonoImage *
mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename)
{
MonoCLIImageInfo *iinfo;
MonoImage *image;
char *datac;
if (!data || !data_len) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
datac = data;
if (need_copy) {
datac = (char *)g_try_malloc (data_len);
if (!datac) {
if (status)
*status = MONO_IMAGE_ERROR_ERRNO;
return NULL;
}
memcpy (datac, data, data_len);
}
MonoImageStorage *storage = mono_image_storage_new_raw_data (datac, data_len, need_copy, filename);
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name);
image->filename = filename ? g_strdup (filename) : NULL;
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->metadata_only = metadata_only;
image->ref_count = 1;
image->alc = alc;
image = do_mono_image_load (image, status, TRUE, TRUE);
if (image == NULL)
return NULL;
return register_image (mono_alc_get_loaded_images (alc), image);
}
MonoImage *
mono_image_open_from_data_alc (MonoAssemblyLoadContextGCHandle alc_gchandle, char *data, uint32_t data_len, mono_bool need_copy, MonoImageOpenStatus *status, const char *name)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
MonoAssemblyLoadContext *alc = mono_alc_from_gchandle (alc_gchandle);
result = mono_image_open_from_data_internal (alc, data, data_len, need_copy, status, FALSE, name, name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data_with_name:
*/
MonoImage *
mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
{
if (refonly) {
if (status) {
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
}
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, name, name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data_full:
*/
MonoImage *
mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
{
if (refonly) {
if (status) {
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
}
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data:
*/
MonoImage *
mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL);
MONO_EXIT_GC_UNSAFE;
return result;
}
#ifdef HOST_WIN32
static MonoImageStorage *
mono_image_storage_open_from_module_handle (HMODULE module_handle, const char *fname, gboolean has_entry_point)
{
char *key = g_strdup (fname);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_data = (char*) module_handle;
storage->is_module_handle = TRUE;
storage->has_entry_point = has_entry_point;
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
/* fname is not duplicated. */
MonoImage*
mono_image_open_from_module_handle (MonoAssemblyLoadContext *alc, HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
{
MonoImage* image;
MonoCLIImageInfo* iinfo;
MonoImageStorage *storage = mono_image_storage_open_from_module_handle (module_handle, fname, has_entry_point);
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->name = fname;
image->filename = g_strdup (image->name);
image->ref_count = has_entry_point ? 0 : 1;
image->alc = alc;
image = do_mono_image_load (image, status, TRUE, TRUE);
if (image == NULL)
return NULL;
return register_image (mono_alc_get_loaded_images (alc), image);
}
#endif
/**
* mono_image_open_full:
*/
MonoImage *
mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
{
if (refonly) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
return mono_image_open_a_lot (mono_alc_get_default (), fname, status);
}
static MonoImage *
mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
MonoImage *image;
GHashTable *loaded_images = mono_loaded_images_get_hash (li);
char *absfname;
g_return_val_if_fail (fname != NULL, NULL);
#ifdef HOST_WIN32
// Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll),
// then assemblies need to be loaded with LoadLibrary:
if (coree_module_handle) {
HMODULE module_handle;
gunichar2 *fname_utf16;
DWORD last_error;
absfname = mono_path_resolve_symlinks (fname);
fname_utf16 = NULL;
/* There is little overhead because the OS loader lock is held by LoadLibrary. */
mono_images_lock ();
image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname);
if (image) { // Image already loaded
g_assert (m_image_is_module_handle (image));
if (m_image_has_entry_point (image) && image->ref_count == 0) {
/* Increment reference count on images loaded outside of the runtime. */
fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
/* The image is already loaded because _CorDllMain removes images from the hash. */
module_handle = LoadLibrary (fname_utf16);
g_assert (module_handle == (HMODULE) image->raw_data);
}
mono_image_addref (image);
mono_images_unlock ();
if (fname_utf16)
g_free (fname_utf16);
g_free (absfname);
return image;
}
// Image not loaded, load it now
fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
module_handle = MonoLoadImage (fname_utf16);
if (status && module_handle == NULL)
last_error = mono_w32error_get_last ();
/* mono_image_open_from_module_handle is called by _CorDllMain. */
image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname);
if (image)
mono_image_addref (image);
mono_images_unlock ();
g_free (fname_utf16);
if (module_handle == NULL) {
g_assert (!image);
g_free (absfname);
if (status) {
if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
} else {
if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
mono_set_errno (ENOENT);
else
mono_set_errno (0);
}
}
return NULL;
}
if (image) {
g_assert (m_image_is_module_handle (image));
g_assert (m_image_has_entry_point (image));
g_free (absfname);
return image;
}
return mono_image_open_from_module_handle (alc, module_handle, absfname, FALSE, status);
}
#endif
absfname = mono_path_resolve_symlinks (fname);
/*
* The easiest solution would be to do all the loading inside the mutex,
* but that would lead to scalability problems. So we let the loading
* happen outside the mutex, and if multiple threads happen to load
* the same image, we discard all but the first copy.
*/
mono_images_lock ();
image = (MonoImage *)g_hash_table_lookup (loaded_images, absfname);
g_free (absfname);
if (image) { // Image already loaded
mono_image_addref (image);
mono_images_unlock ();
return image;
}
mono_images_unlock ();
// Image not loaded, load it now
image = do_mono_image_open (alc, fname, status, TRUE, TRUE, FALSE);
if (image == NULL)
return NULL;
return register_image (li, image);
}
MonoImage *
mono_image_open_a_lot (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
MonoLoadedImages *li = mono_alc_get_loaded_images (alc);
return mono_image_open_a_lot_parameterized (li, alc, fname, status);
}
/**
* mono_image_open:
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns An open image of type \c MonoImage or NULL on error.
* The caller holds a temporary reference to the returned image which should be cleared
* when no longer needed by calling \c mono_image_close.
* if NULL, then check the value of \p status for details on the error
*/
MonoImage *
mono_image_open (const char *fname, MonoImageOpenStatus *status)
{
return mono_image_open_a_lot (mono_alc_get_default (), fname, status);
}
/**
* mono_pe_file_open:
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns An open image of type \c MonoImage or NULL on error. if
* NULL, then check the value of \p status for details on the error.
* This variant for \c mono_image_open DOES NOT SET UP CLI METADATA.
* It's just a PE file loader, used for \c FileVersionInfo. It also does
* not use the image cache.
*/
MonoImage *
mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
{
g_return_val_if_fail (fname != NULL, NULL);
return do_mono_image_open (mono_alc_get_default (), fname, status, FALSE, TRUE, FALSE);
}
/**
* mono_image_open_raw
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns an image without loading neither pe or cli data.
* Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
*/
MonoImage *
mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
g_return_val_if_fail (fname != NULL, NULL);
return do_mono_image_open (alc, fname, status, FALSE, FALSE, FALSE);
}
/*
* mono_image_open_metadata_only:
*
* Open an image which contains metadata only without a PE header.
*/
MonoImage *
mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
return do_mono_image_open (alc, fname, status, TRUE, TRUE, TRUE);
}
/**
* mono_image_fixup_vtable:
*/
void
mono_image_fixup_vtable (MonoImage *image)
{
#ifdef HOST_WIN32
MonoCLIImageInfo *iinfo;
MonoPEDirEntry *de;
MonoVTableFixup *vtfixup;
int count;
gpointer slot;
guint16 slot_type;
int slot_count;
g_assert (m_image_is_module_handle (image));
iinfo = image->image_info;
de = &iinfo->cli_cli_header.ch_vtable_fixups;
if (!de->rva || !de->size)
return;
vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
if (!vtfixup)
return;
count = de->size / sizeof (MonoVTableFixup);
while (count--) {
if (!vtfixup->rva || !vtfixup->count)
continue;
slot = mono_image_rva_map (image, vtfixup->rva);
g_assert (slot);
slot_type = vtfixup->type;
slot_count = vtfixup->count;
if (slot_type & VTFIXUP_TYPE_32BIT)
while (slot_count--) {
*((guint32*) slot) = (guint32)(gsize)mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
slot = ((guint32*) slot) + 1;
}
else if (slot_type & VTFIXUP_TYPE_64BIT)
while (slot_count--) {
*((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
slot = ((guint32*) slot) + 1;
}
else
g_assert_not_reached();
vtfixup++;
}
#else
g_assert_not_reached();
#endif
}
static void
free_hash_table (gpointer key, gpointer val, gpointer user_data)
{
g_hash_table_destroy ((GHashTable*)val);
}
/*
static void
free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
{
mono_metadata_free_method_signature ((MonoMethodSignature*)val);
}
*/
static void
free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_slist_free ((GSList*)val);
}
/**
* mono_image_addref:
* \param image The image file we wish to add a reference to
* Increases the reference count of an image.
*/
void
mono_image_addref (MonoImage *image)
{
mono_atomic_inc_i32 (&image->ref_count);
}
void
mono_dynamic_stream_reset (MonoDynamicStream* stream)
{
stream->alloc_size = stream->index = stream->offset = 0;
g_free (stream->data);
stream->data = NULL;
if (stream->hash) {
g_hash_table_destroy (stream->hash);
stream->hash = NULL;
}
}
static void
free_hash (GHashTable *hash)
{
if (hash)
g_hash_table_destroy (hash);
}
void
mono_wrapper_caches_free (MonoWrapperCaches *cache)
{
free_hash (cache->delegate_invoke_cache);
free_hash (cache->delegate_begin_invoke_cache);
free_hash (cache->delegate_end_invoke_cache);
free_hash (cache->delegate_bound_static_invoke_cache);
free_hash (cache->runtime_invoke_signature_cache);
free_hash (cache->delegate_abstract_invoke_cache);
free_hash (cache->runtime_invoke_method_cache);
free_hash (cache->managed_wrapper_cache);
free_hash (cache->native_wrapper_cache);
free_hash (cache->native_wrapper_aot_cache);
free_hash (cache->native_wrapper_check_cache);
free_hash (cache->native_wrapper_aot_check_cache);
free_hash (cache->native_func_wrapper_aot_cache);
free_hash (cache->native_func_wrapper_indirect_cache);
free_hash (cache->synchronized_cache);
free_hash (cache->unbox_wrapper_cache);
free_hash (cache->cominterop_invoke_cache);
free_hash (cache->cominterop_wrapper_cache);
free_hash (cache->thunk_invoke_cache);
}
static void
mono_image_close_except_pools_all (MonoImage**images, int image_count)
{
for (int i = 0; i < image_count; ++i) {
if (images [i]) {
if (!mono_image_close_except_pools (images [i]))
images [i] = NULL;
}
}
}
/*
* Returns whether mono_image_close_finish() must be called as well.
* We must unload images in two steps because clearing the domain in
* SGen requires the class metadata to be intact, but we need to free
* the mono_g_hash_tables in case a collection occurs during domain
* unloading and the roots would trip up the GC.
*/
gboolean
mono_image_close_except_pools (MonoImage *image)
{
int i;
g_return_val_if_fail (image != NULL, FALSE);
if (!mono_loaded_images_remove_image (image))
return FALSE;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image) && m_image_has_entry_point (image)) {
mono_images_lock ();
if (image->ref_count == 0) {
/* Image will be closed by _CorDllMain. */
FreeLibrary ((HMODULE) image->raw_data);
mono_images_unlock ();
return FALSE;
}
mono_images_unlock ();
}
#endif
MONO_PROFILER_RAISE (image_unloading, (image));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
mono_image_invoke_unload_hook (image);
mono_metadata_update_cleanup_on_close (image);
/*
* The caches inside a MonoImage might refer to metadata which is stored in referenced
* assemblies, so we can't release these references in mono_assembly_close () since the
* MonoImage might outlive its associated MonoAssembly.
*/
if (image->references && !image_is_dynamic (image)) {
for (i = 0; i < image->nreferences; i++) {
if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
if (!mono_assembly_close_except_image_pools (image->references [i]))
image->references [i] = NULL;
}
}
} else {
if (image->references) {
g_free (image->references);
image->references = NULL;
}
}
/* a MonoDynamicImage doesn't have any storage */
g_assert (image_is_dynamic (image) || image->storage != NULL);
if (image->storage && m_image_is_raw_data_allocated (image)) {
/* FIXME: do we need this? (image is disposed anyway) */
/* image->raw_metadata and cli_sections might lie inside image->raw_data */
MonoCLIImageInfo *ii = image->image_info;
if ((image->raw_metadata > image->raw_data) &&
(image->raw_metadata <= (image->raw_data + image->raw_data_len)))
image->raw_metadata = NULL;
for (i = 0; i < ii->cli_section_count; i++)
if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
ii->cli_sections [i] = NULL;
}
if (image->storage)
mono_image_storage_close (image->storage);
if (debug_assembly_unload) {
char *old_name = image->name;
image->name = g_strdup_printf ("%s - UNLOADED", old_name);
g_free (old_name);
g_free (image->filename);
image->filename = NULL;
} else {
g_free (image->name);
g_free (image->filename);
g_free (image->guid);
g_free (image->version);
}
if (image->method_cache)
g_hash_table_destroy (image->method_cache);
if (image->methodref_cache)
g_hash_table_destroy (image->methodref_cache);
mono_internal_hash_table_destroy (&image->class_cache);
mono_conc_hashtable_destroy (image->field_cache);
if (image->array_cache) {
g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
g_hash_table_destroy (image->array_cache);
}
if (image->szarray_cache)
g_hash_table_destroy (image->szarray_cache);
if (image->ptr_cache)
g_hash_table_destroy (image->ptr_cache);
if (image->name_cache) {
g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
g_hash_table_destroy (image->name_cache);
}
free_hash (image->icall_wrapper_cache);
if (image->var_gparam_cache)
mono_conc_hashtable_destroy (image->var_gparam_cache);
if (image->mvar_gparam_cache)
mono_conc_hashtable_destroy (image->mvar_gparam_cache);
free_hash (image->wrapper_param_names);
free_hash (image->native_func_wrapper_cache);
mono_conc_hashtable_destroy (image->typespec_cache);
free_hash (image->weak_field_indexes);
mono_wrapper_caches_free (&image->wrapper_caches);
/* The ownership of signatures is not well defined */
g_hash_table_destroy (image->memberref_signatures);
g_hash_table_destroy (image->method_signatures);
if (image->rgctx_template_hash)
g_hash_table_destroy (image->rgctx_template_hash);
if (image->property_hash)
mono_property_hash_destroy (image->property_hash);
/*
reflection_info_unregister_classes is only required by dynamic images, which will not be properly
cleared during shutdown as we don't perform regular appdomain unload for the root one.
*/
g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
image->reflection_info_unregister_classes = NULL;
if (image->interface_bitset) {
mono_unload_interface_ids (image->interface_bitset);
mono_bitset_free (image->interface_bitset);
}
if (image->image_info){
MonoCLIImageInfo *ii = image->image_info;
g_free (ii->cli_section_tables);
g_free (ii->cli_sections);
g_free (image->image_info);
}
mono_image_close_except_pools_all (image->files, image->file_count);
mono_image_close_except_pools_all (image->modules, image->module_count);
g_free (image->modules_loaded);
if (image->has_updates)
mono_metadata_update_image_close_except_pools_all (image);
mono_os_mutex_destroy (&image->szarray_cache_lock);
mono_os_mutex_destroy (&image->lock);
/*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
if (image_is_dynamic (image)) {
/* Dynamic images are GC_MALLOCed */
g_free ((char*)image->module_name);
mono_dynamic_image_free ((MonoDynamicImage*)image);
}
MONO_PROFILER_RAISE (image_unloaded, (image));
return TRUE;
}
static void
mono_image_close_all (MonoImage**images, int image_count)
{
for (int i = 0; i < image_count; ++i) {
if (images [i])
mono_image_close_finish (images [i]);
}
if (images)
g_free (images);
}
void
mono_image_close_finish (MonoImage *image)
{
int i;
if (image->references && !image_is_dynamic (image)) {
for (i = 0; i < image->nreferences; i++) {
if (image->references [i] && image->references [i] != REFERENCE_MISSING)
mono_assembly_close_finish (image->references [i]);
}
g_free (image->references);
image->references = NULL;
}
mono_image_close_all (image->files, image->file_count);
mono_image_close_all (image->modules, image->module_count);
mono_metadata_update_image_close_all (image);
#ifndef DISABLE_PERFCOUNTERS
/* FIXME: use an explicit subtraction method as soon as it's available */
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (image->mempool));
#endif
if (!image_is_dynamic (image)) {
if (debug_assembly_unload)
mono_mempool_invalidate (image->mempool);
else {
mono_mempool_destroy (image->mempool);
g_free (image);
}
} else {
if (debug_assembly_unload)
mono_mempool_invalidate (image->mempool);
else {
mono_mempool_destroy (image->mempool);
mono_dynamic_image_free_image ((MonoDynamicImage*)image);
}
}
}
/**
* mono_image_close:
* \param image The image file we wish to close
* Closes an image file, deallocates all memory consumed and
* unmaps all possible sections of the file
*/
void
mono_image_close (MonoImage *image)
{
if (mono_image_close_except_pools (image))
mono_image_close_finish (image);
}
/**
* mono_image_strerror:
* \param status an code indicating the result from a recent operation
* \returns a string describing the error
*/
const char *
mono_image_strerror (MonoImageOpenStatus status)
{
switch (status){
case MONO_IMAGE_OK:
return "success";
case MONO_IMAGE_ERROR_ERRNO:
return strerror (errno);
case MONO_IMAGE_IMAGE_INVALID:
return "File does not contain a valid CIL image";
case MONO_IMAGE_MISSING_ASSEMBLYREF:
return "An assembly was referenced, but could not be found";
}
return "Internal error";
}
static gpointer
mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
guint32 lang_id, gunichar2 *name,
MonoPEResourceDirEntry *entry,
MonoPEResourceDir *root, guint32 level)
{
gboolean is_string, is_dir;
guint32 name_offset, dir_offset;
/* Level 0 holds a directory entry for each type of resource
* (identified by ID or name).
*
* Level 1 holds a directory entry for each named resource
* item, and each "anonymous" item of a particular type of
* resource.
*
* Level 2 holds a directory entry for each language pointing to
* the actual data.
*/
is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
if(level==0) {
if (is_string)
return NULL;
} else if (level==1) {
if (res_id != name_offset)
return NULL;
#if 0
if(name!=NULL &&
is_string==TRUE && name!=lookup (name_offset)) {
return(NULL);
}
#endif
} else if (level==2) {
if (is_string || (lang_id != 0 && name_offset != lang_id))
return NULL;
} else {
g_assert_not_reached ();
}
if (is_dir) {
MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
guint32 entries, i;
entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
for(i=0; i<entries; i++) {
MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
gpointer ret;
ret=mono_image_walk_resource_tree (info, res_id,
lang_id, name,
sub_entry, root,
level+1);
if(ret!=NULL) {
return(ret);
}
}
return(NULL);
} else {
MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
MonoPEResourceDataEntry *res;
res = g_new0 (MonoPEResourceDataEntry, 1);
res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
return (res);
}
}
/**
* mono_image_lookup_resource:
* \param image the image to look up the resource in
* \param res_id A \c MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
* \param lang_id The language id.
* \param name the resource name to lookup.
* \returns NULL if not found, otherwise a pointer to the in-memory representation
* of the given resource. The caller should free it using \c g_free when no longer
* needed.
*/
gpointer
mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
{
MonoCLIImageInfo *info;
MonoDotNetHeader *header;
MonoPEDatadir *datadir;
MonoPEDirEntry *rsrc;
MonoPEResourceDir *resource_dir;
MonoPEResourceDirEntry *res_entries;
guint32 entries, i;
if(image==NULL) {
return(NULL);
}
mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
info = (MonoCLIImageInfo *)image->image_info;
if(info==NULL) {
return(NULL);
}
header=&info->cli_header;
if(header==NULL) {
return(NULL);
}
datadir=&header->datadir;
if(datadir==NULL) {
return(NULL);
}
rsrc=&datadir->pe_resource_table;
if(rsrc==NULL) {
return(NULL);
}
resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
if(resource_dir==NULL) {
return(NULL);
}
entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
for(i=0; i<entries; i++) {
MonoPEResourceDirEntry *entry=&res_entries[i];
gpointer ret;
ret=mono_image_walk_resource_tree (info, res_id, lang_id,
name, entry, resource_dir,
0);
if(ret!=NULL) {
return(ret);
}
}
return(NULL);
}
/**
* mono_image_get_entry_point:
* \param image the image where the entry point will be looked up.
* Use this routine to determine the metadata token for method that
* has been flagged as the entry point.
* \returns the token for the entry point method in the image
*/
guint32
mono_image_get_entry_point (MonoImage *image)
{
return image->image_info->cli_cli_header.ch_entry_point;
}
/**
* mono_image_get_resource:
* \param image the image where the resource will be looked up.
* \param offset The offset to add to the resource
* \param size a pointer to an int where the size of the resource will be stored
*
* This is a low-level routine that fetches a resource from the
* metadata that starts at a given \p offset. The \p size parameter is
* filled with the data field as encoded in the metadata.
*
* \returns the pointer to the resource whose offset is \p offset.
*/
const char*
mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoCLIHeader *ch = &iinfo->cli_cli_header;
const char* data;
if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
return NULL;
data = mono_image_rva_map (image, ch->ch_resources.rva);
if (!data)
return NULL;
data += offset;
if (size)
*size = read32 (data);
data += 4;
return data;
}
// Returning NULL with no error set will be interpeted as "not found"
MonoImage*
mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error)
{
char *base_dir, *name;
MonoImage *res;
MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
const char *fname;
guint32 fname_id;
error_init (error);
if (fileidx < 1 || fileidx > table_info_get_rows (t))
return NULL;
mono_image_lock (image);
if (image->files && image->files [fileidx - 1]) {
mono_image_unlock (image);
return image->files [fileidx - 1];
}
mono_image_unlock (image);
fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
fname = mono_metadata_string_heap (image, fname_id);
base_dir = g_path_get_dirname (image->name);
name = g_build_filename (base_dir, fname, (const char*)NULL);
res = mono_image_open (name, NULL);
if (!res)
goto done;
mono_image_lock (image);
if (image->files && image->files [fileidx - 1]) {
MonoImage *old = res;
res = image->files [fileidx - 1];
mono_image_unlock (image);
mono_image_close (old);
} else {
int i;
/* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
if (!assign_assembly_parent_for_netmodule (res, image, error)) {
mono_image_unlock (image);
mono_image_close (res);
return NULL;
}
for (i = 0; i < res->module_count; ++i) {
if (res->modules [i] && !res->modules [i]->assembly)
res->modules [i]->assembly = image->assembly;
}
if (!image->files) {
int n = table_info_get_rows (t);
image->files = g_new0 (MonoImage*, n);
image->file_count = n;
}
image->files [fileidx - 1] = res;
mono_image_unlock (image);
/* vtable fixup can't happen with the image lock held */
#ifdef HOST_WIN32
if (m_image_is_module_handle (res))
mono_image_fixup_vtable (res);
#endif
}
done:
g_free (name);
g_free (base_dir);
return res;
}
/**
* mono_image_load_file_for_image:
*/
MonoImage*
mono_image_load_file_for_image (MonoImage *image, int fileidx)
{
ERROR_DECL (error);
MonoImage *result = mono_image_load_file_for_image_checked (image, fileidx, error);
mono_error_assert_ok (error);
return result;
}
/**
* mono_image_get_strong_name:
* \param image a MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* If the image has a strong name, and \p size is not NULL, the value
* pointed to by size will have the size of the strong name.
*
* \returns NULL if the image does not have a strong name, or a
* pointer to the public key.
*/
const char*
mono_image_get_strong_name (MonoImage *image, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
const char* data;
if (!de->size || !de->rva)
return NULL;
data = mono_image_rva_map (image, de->rva);
if (!data)
return NULL;
if (size)
*size = de->size;
return data;
}
/**
* mono_image_strong_name_position:
* \param image a \c MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* If the image has a strong name, and \p size is not NULL, the value
* pointed to by size will have the size of the strong name.
*
* \returns the position within the image file where the strong name
* is stored.
*/
guint32
mono_image_strong_name_position (MonoImage *image, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
guint32 pos;
if (size)
*size = de->size;
if (!de->size || !de->rva)
return 0;
pos = mono_cli_rva_image_map (image, de->rva);
return pos == INVALID_ADDRESS ? 0 : pos;
}
/**
* mono_image_get_public_key:
* \param image a \c MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* This is used to obtain the public key in the \p image.
*
* If the image has a public key, and \p size is not NULL, the value
* pointed to by size will have the size of the public key.
*
* \returns NULL if the image does not have a public key, or a pointer
* to the public key.
*/
const char*
mono_image_get_public_key (MonoImage *image, guint32 *size)
{
const char *pubkey;
guint32 len, tok;
if (image_is_dynamic (image)) {
if (size)
*size = ((MonoDynamicImage*)image)->public_key_len;
return (char*)((MonoDynamicImage*)image)->public_key;
}
if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY]) != 1)
return NULL;
tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
if (!tok)
return NULL;
pubkey = mono_metadata_blob_heap (image, tok);
len = mono_metadata_decode_blob_size (pubkey, &pubkey);
if (size)
*size = len;
return pubkey;
}
/**
* mono_image_get_name:
* \param name a \c MonoImage
* \returns the name of the assembly.
*/
const char*
mono_image_get_name (MonoImage *image)
{
return image->assembly_name;
}
/**
* mono_image_get_filename:
* \param image a \c MonoImage
* Used to get the filename that hold the actual \c MonoImage
* \returns the filename.
*/
const char*
mono_image_get_filename (MonoImage *image)
{
return image->name;
}
/**
* mono_image_get_guid:
*/
const char*
mono_image_get_guid (MonoImage *image)
{
return image->guid;
}
/**
* mono_image_get_table_info:
*/
const MonoTableInfo*
mono_image_get_table_info (MonoImage *image, int table_id)
{
if (table_id < 0 || table_id >= MONO_TABLE_NUM)
return NULL;
return &image->tables [table_id];
}
/**
* mono_image_get_table_rows:
*/
int
mono_image_get_table_rows (MonoImage *image, int table_id)
{
if (table_id < 0 || table_id >= MONO_TABLE_NUM)
return 0;
return table_info_get_rows (&image->tables [table_id]);
}
/**
* mono_table_info_get_rows:
*/
int
mono_table_info_get_rows (const MonoTableInfo *table)
{
return table_info_get_rows (table);
}
/**
* mono_image_get_assembly:
* \param image the \c MonoImage .
* Use this routine to get the assembly that owns this image.
* \returns the assembly that holds this image.
*/
MonoAssembly*
mono_image_get_assembly (MonoImage *image)
{
return image->assembly;
}
/**
* mono_image_is_dynamic:
* \param image the \c MonoImage
*
* Determines if the given image was created dynamically through the
* \c System.Reflection.Emit API
* \returns TRUE if the image was created dynamically, FALSE if not.
*/
gboolean
mono_image_is_dynamic (MonoImage *image)
{
return image_is_dynamic (image);
}
/**
* mono_image_has_authenticode_entry:
* \param image the \c MonoImage
* Use this routine to determine if the image has a Authenticode
* Certificate Table.
* \returns TRUE if the image contains an authenticode entry in the PE
* directory.
*/
gboolean
mono_image_has_authenticode_entry (MonoImage *image)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoDotNetHeader *header = &iinfo->cli_header;
if (!header)
return FALSE;
MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
// the Authenticode "pre" (non ASN.1) header is 8 bytes long
return ((de->rva != 0) && (de->size > 8));
}
gpointer
mono_image_alloc (MonoImage *image, guint size)
{
gpointer res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
#endif
mono_image_lock (image);
res = mono_mempool_alloc (image->mempool, size);
mono_image_unlock (image);
return res;
}
gpointer
mono_image_alloc0 (MonoImage *image, guint size)
{
gpointer res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
#endif
mono_image_lock (image);
res = mono_mempool_alloc0 (image->mempool, size);
mono_image_unlock (image);
return res;
}
char*
mono_image_strdup (MonoImage *image, const char *s)
{
char *res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (s));
#endif
mono_image_lock (image);
res = mono_mempool_strdup (image->mempool, s);
mono_image_unlock (image);
return res;
}
char*
mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args)
{
char *buf;
mono_image_lock (image);
buf = mono_mempool_strdup_vprintf (image->mempool, format, args);
mono_image_unlock (image);
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (buf));
#endif
return buf;
}
char*
mono_image_strdup_printf (MonoImage *image, const char *format, ...)
{
char *buf;
va_list args;
va_start (args, format);
buf = mono_image_strdup_vprintf (image, format, args);
va_end (args);
return buf;
}
GList*
mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
{
GList *new_list;
new_list = (GList *)mono_image_alloc (image, sizeof (GList));
new_list->data = data;
new_list->prev = list ? list->prev : NULL;
new_list->next = list;
if (new_list->prev)
new_list->prev->next = new_list;
if (list)
list->prev = new_list;
return new_list;
}
GSList*
mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
{
GSList *new_list;
new_list = (GSList *)mono_image_alloc (image, sizeof (GSList));
new_list->data = data;
new_list->next = NULL;
return g_slist_concat (list, new_list);
}
void
mono_image_lock (MonoImage *image)
{
mono_locks_os_acquire (&image->lock, ImageDataLock);
}
void
mono_image_unlock (MonoImage *image)
{
mono_locks_os_release (&image->lock, ImageDataLock);
}
/**
* mono_image_property_lookup:
* Lookup a property on \p image . Used to store very rare fields of \c MonoClass and \c MonoMethod .
*
* LOCKING: Takes the image lock
*/
gpointer
mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
{
gpointer res;
mono_image_lock (image);
res = mono_property_hash_lookup (image->property_hash, subject, property);
mono_image_unlock (image);
return res;
}
/**
* mono_image_property_insert:
* Insert a new property \p property with value \p value on \p subject in \p
* image. Used to store very rare fields of \c MonoClass and \c MonoMethod.
*
* LOCKING: Takes the image lock
*/
void
mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
{
CHECKED_METADATA_STORE_LOCAL (image->mempool, value);
mono_image_lock (image);
mono_property_hash_insert (image->property_hash, subject, property, value);
mono_image_unlock (image);
}
/**
* mono_image_property_remove:
* Remove all properties associated with \p subject in \p image. Used to store very rare fields of \c MonoClass and \c MonoMethod .
*
* LOCKING: Takes the image lock
*/
void
mono_image_property_remove (MonoImage *image, gpointer subject)
{
mono_image_lock (image);
mono_property_hash_remove_object (image->property_hash, subject);
mono_image_unlock (image);
}
void
mono_image_append_class_to_reflection_info_set (MonoClass *klass)
{
MonoImage *image = m_class_get_image (klass);
g_assert (image_is_dynamic (image));
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, klass);
mono_image_unlock (image);
}
| /**
* \file
* Routines for manipulating an image stored in an
* extended PE/COFF file.
*
* 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 <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <mono/metadata/image.h>
#include "cil-coff.h"
#include "mono-endian.h"
#include "tabledefs.h"
#include <mono/metadata/tokentype.h>
#include "metadata-internals.h"
#include "metadata-update.h"
#include "profiler-private.h"
#include <mono/metadata/loader.h>
#include "marshal.h"
#include "coree.h"
#include <mono/metadata/exception-internals.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-errno.h>
#include <mono/utils/mono-path.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-proclib.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/image-internals.h>
#include <mono/metadata/loaded-images-internals.h>
#include <mono/metadata/metadata-update.h>
#include <mono/metadata/debug-internals.h>
#include <mono/metadata/mono-private-unstable.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <mono/metadata/w32error.h>
#define INVALID_ADDRESS 0xffffffff
// Amount initially reserved in each image's mempool.
// FIXME: This number is arbitrary, a more practical number should be found
#define INITIAL_IMAGE_SIZE 512
// Change the assembly set in `image` to the assembly set in `assemblyImage`. Halt if overwriting is attempted.
// Can be used on modules loaded through either the "file" or "module" mechanism
static gboolean
assign_assembly_parent_for_netmodule (MonoImage *image, MonoImage *assemblyImage, MonoError *error)
{
// Assembly to assign
MonoAssembly *assembly = assemblyImage->assembly;
while (1) {
// Assembly currently assigned
MonoAssembly *assemblyOld = image->assembly;
if (assemblyOld) {
if (assemblyOld == assembly)
return TRUE;
mono_error_set_bad_image (error, assemblyImage, "Attempted to load module %s which has already been loaded by assembly %s. This is not supported in Mono.", image->name, assemblyOld->image->name);
return FALSE;
}
gpointer result = mono_atomic_xchg_ptr((gpointer *)&image->assembly, assembly);
if (result == assembly)
return TRUE;
}
}
static gboolean debug_assembly_unload = FALSE;
#define mono_images_storage_lock() do { if (mutex_inited) mono_os_mutex_lock (&images_storage_mutex); } while (0)
#define mono_images_storage_unlock() do { if (mutex_inited) mono_os_mutex_unlock (&images_storage_mutex); } while (0)
static gboolean mutex_inited;
static mono_mutex_t images_mutex;
static mono_mutex_t images_storage_mutex;
void
mono_images_lock (void)
{
if (mutex_inited)
mono_os_mutex_lock (&images_mutex);
}
void
mono_images_unlock(void)
{
if (mutex_inited)
mono_os_mutex_unlock (&images_mutex);
}
static MonoImage *
mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
/* Maps string keys to MonoImageStorage values.
*
* The MonoImageStorage in the hash owns the key.
*/
static GHashTable *images_storage_hash;
static void install_pe_loader (void);
typedef struct ImageUnloadHook ImageUnloadHook;
struct ImageUnloadHook {
MonoImageUnloadFunc func;
gpointer user_data;
};
static GSList *image_unload_hooks;
void
mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
{
ImageUnloadHook *hook;
g_return_if_fail (func != NULL);
hook = g_new0 (ImageUnloadHook, 1);
hook->func = func;
hook->user_data = user_data;
image_unload_hooks = g_slist_prepend (image_unload_hooks, hook);
}
void
mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data)
{
GSList *l;
ImageUnloadHook *hook;
for (l = image_unload_hooks; l; l = l->next) {
hook = (ImageUnloadHook *)l->data;
if (hook->func == func && hook->user_data == user_data) {
g_free (hook);
image_unload_hooks = g_slist_delete_link (image_unload_hooks, l);
break;
}
}
}
static void
mono_image_invoke_unload_hook (MonoImage *image)
{
GSList *l;
ImageUnloadHook *hook;
for (l = image_unload_hooks; l; l = l->next) {
hook = (ImageUnloadHook *)l->data;
hook->func (image, hook->user_data);
}
}
static GSList *image_loaders;
void
mono_install_image_loader (const MonoImageLoader *loader)
{
image_loaders = g_slist_prepend (image_loaders, (MonoImageLoader*)loader);
}
/* returns offset relative to image->raw_data */
guint32
mono_cli_rva_image_map (MonoImage *image, guint32 addr)
{
MonoCLIImageInfo *iinfo = image->image_info;
const int top = iinfo->cli_section_count;
MonoSectionTable *tables = iinfo->cli_section_tables;
int i;
if (image->metadata_only)
return addr;
for (i = 0; i < top; i++){
if ((addr >= tables->st_virtual_address) &&
(addr < tables->st_virtual_address + tables->st_raw_data_size)){
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
return addr;
#endif
return addr - tables->st_virtual_address + tables->st_raw_data_ptr;
}
tables++;
}
return INVALID_ADDRESS;
}
/**
* mono_image_rva_map:
* \param image a \c MonoImage
* \param addr relative virtual address (RVA)
*
* This is a low-level routine used by the runtime to map relative
* virtual address (RVA) into their location in memory.
*
* \returns the address in memory for the given RVA, or NULL if the
* RVA is not valid for this image.
*/
char *
mono_image_rva_map (MonoImage *image, guint32 addr)
{
MonoCLIImageInfo *iinfo = image->image_info;
const int top = iinfo->cli_section_count;
MonoSectionTable *tables = iinfo->cli_section_tables;
int i;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image)) {
if (addr && addr < image->raw_data_len)
return image->raw_data + addr;
else
return NULL;
}
#endif
for (i = 0; i < top; i++){
if ((addr >= tables->st_virtual_address) &&
(addr < tables->st_virtual_address + tables->st_raw_data_size)){
if (!iinfo->cli_sections [i]) {
if (!mono_image_ensure_section_idx (image, i))
return NULL;
}
return (char*)iinfo->cli_sections [i] +
(addr - tables->st_virtual_address);
}
tables++;
}
return NULL;
}
/**
* mono_images_init:
*
* Initialize the global variables used by this module.
*/
void
mono_images_init (void)
{
mono_os_mutex_init (&images_storage_mutex);
mono_os_mutex_init_recursive (&images_mutex);
images_storage_hash = g_hash_table_new (g_str_hash, g_str_equal);
debug_assembly_unload = g_hasenv ("MONO_DEBUG_ASSEMBLY_UNLOAD");
install_pe_loader ();
mutex_inited = TRUE;
}
/**
* mono_images_cleanup:
*
* Free all resources used by this module.
*/
void
mono_images_cleanup (void)
{
}
/**
* mono_image_ensure_section_idx:
* \param image The image we are operating on
* \param section section number that we will load/map into memory
*
* This routine makes sure that we have an in-memory copy of
* an image section (<code>.text</code>, <code>.rsrc</code>, <code>.data</code>).
*
* \returns TRUE on success
*/
int
mono_image_ensure_section_idx (MonoImage *image, int section)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoSectionTable *sect;
g_return_val_if_fail (section < iinfo->cli_section_count, FALSE);
if (iinfo->cli_sections [section] != NULL)
return TRUE;
sect = &iinfo->cli_section_tables [section];
if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len)
return FALSE;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address;
else
#endif
/* FIXME: we ignore the writable flag since we don't patch the binary */
iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr;
return TRUE;
}
/**
* mono_image_ensure_section:
* \param image The image we are operating on
* \param section section name that we will load/map into memory
*
* This routine makes sure that we have an in-memory copy of
* an image section (.text, .rsrc, .data).
*
* \returns TRUE on success
*/
int
mono_image_ensure_section (MonoImage *image, const char *section)
{
MonoCLIImageInfo *ii = image->image_info;
int i;
for (i = 0; i < ii->cli_section_count; i++){
if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0)
continue;
return mono_image_ensure_section_idx (image, i);
}
return FALSE;
}
static int
load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset)
{
const int top = iinfo->cli_header.coff.coff_sections;
int i;
iinfo->cli_section_count = top;
iinfo->cli_section_tables = g_new0 (MonoSectionTable, top);
iinfo->cli_sections = g_new0 (void *, top);
for (i = 0; i < top; i++){
MonoSectionTable *t = &iinfo->cli_section_tables [i];
if (offset + sizeof (MonoSectionTable) > image->raw_data_len)
return FALSE;
memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable));
offset += sizeof (MonoSectionTable);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size);
t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address);
t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size);
t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr);
t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr);
t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr);
t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count);
t->st_line_count = GUINT16_FROM_LE (t->st_line_count);
t->st_flags = GUINT32_FROM_LE (t->st_flags);
#endif
/* consistency checks here */
}
return TRUE;
}
gboolean
mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo)
{
guint32 offset;
offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva);
if (offset == INVALID_ADDRESS)
return FALSE;
if (offset + sizeof (MonoCLIHeader) > image->raw_data_len)
return FALSE;
memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader));
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
SWAP32 (iinfo->cli_cli_header.ch_size);
SWAP32 (iinfo->cli_cli_header.ch_flags);
SWAP32 (iinfo->cli_cli_header.ch_entry_point);
SWAP16 (iinfo->cli_cli_header.ch_runtime_major);
SWAP16 (iinfo->cli_cli_header.ch_runtime_minor);
SWAPPDE (iinfo->cli_cli_header.ch_metadata);
SWAPPDE (iinfo->cli_cli_header.ch_resources);
SWAPPDE (iinfo->cli_cli_header.ch_strong_name);
SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table);
SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups);
SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps);
SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table);
SWAPPDE (iinfo->cli_cli_header.ch_helper_table);
SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info);
SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info);
SWAPPDE (iinfo->cli_cli_header.ch_module_image);
SWAPPDE (iinfo->cli_cli_header.ch_external_fixups);
SWAPPDE (iinfo->cli_cli_header.ch_ridmap);
SWAPPDE (iinfo->cli_cli_header.ch_debug_map);
SWAPPDE (iinfo->cli_cli_header.ch_ip_map);
#undef SWAP32
#undef SWAP16
#undef SWAPPDE
#endif
/* Catch new uses of the fields that are supposed to be zero */
if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) ||
(iinfo->cli_cli_header.ch_helper_table.rva != 0) ||
(iinfo->cli_cli_header.ch_dynamic_info.rva != 0) ||
(iinfo->cli_cli_header.ch_delay_load_info.rva != 0) ||
(iinfo->cli_cli_header.ch_module_image.rva != 0) ||
(iinfo->cli_cli_header.ch_external_fixups.rva != 0) ||
(iinfo->cli_cli_header.ch_ridmap.rva != 0) ||
(iinfo->cli_cli_header.ch_debug_map.rva != 0) ||
(iinfo->cli_cli_header.ch_ip_map.rva != 0)){
/*
* No need to scare people who are testing this, I am just
* labelling this as a LAMESPEC
*/
/* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */
}
return TRUE;
}
/**
* mono_metadata_module_mvid:
*
* Return the module mvid GUID or NULL if the image doesn't have a module table.
*/
static const guint8 *
mono_metadata_module_mvid (MonoImage *image)
{
if (!image->tables [MONO_TABLE_MODULE].base)
return NULL;
guint32 module_cols [MONO_MODULE_SIZE];
mono_metadata_decode_row (&image->tables [MONO_TABLE_MODULE], 0, module_cols, MONO_MODULE_SIZE);
return (const guint8*) mono_metadata_guid_heap (image, module_cols [MONO_MODULE_MVID]);
}
static gboolean
load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo)
{
guint32 offset, size;
guint16 streams;
int i;
guint32 pad;
char *ptr;
offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva);
if (offset == INVALID_ADDRESS)
return FALSE;
size = iinfo->cli_cli_header.ch_metadata.size;
if (offset + size > image->raw_data_len)
return FALSE;
image->raw_metadata = image->raw_data + offset;
/* 24.2.1: Metadata root starts here */
ptr = image->raw_metadata;
if (strncmp (ptr, "BSJB", 4) == 0){
guint32 version_string_len;
ptr += 4;
image->md_version_major = read16 (ptr);
ptr += 2;
image->md_version_minor = read16 (ptr);
ptr += 6;
version_string_len = read32 (ptr);
ptr += 4;
image->version = g_strndup (ptr, version_string_len);
ptr += version_string_len;
pad = ptr - image->raw_metadata;
if (pad % 4)
ptr += 4 - (pad % 4);
} else
return FALSE;
/* skip over flags */
ptr += 2;
streams = read16 (ptr);
ptr += 2;
for (i = 0; i < streams; i++){
if (strncmp (ptr + 8, "#~", 3) == 0){
image->heap_tables.data = image->raw_metadata + read32 (ptr);
image->heap_tables.size = read32 (ptr + 4);
ptr += 8 + 3;
} else if (strncmp (ptr + 8, "#Strings", 9) == 0){
image->heap_strings.data = image->raw_metadata + read32 (ptr);
image->heap_strings.size = read32 (ptr + 4);
ptr += 8 + 9;
} else if (strncmp (ptr + 8, "#US", 4) == 0){
image->heap_us.data = image->raw_metadata + read32 (ptr);
image->heap_us.size = read32 (ptr + 4);
ptr += 8 + 4;
} else if (strncmp (ptr + 8, "#Blob", 6) == 0){
image->heap_blob.data = image->raw_metadata + read32 (ptr);
image->heap_blob.size = read32 (ptr + 4);
ptr += 8 + 6;
} else if (strncmp (ptr + 8, "#GUID", 6) == 0){
image->heap_guid.data = image->raw_metadata + read32 (ptr);
image->heap_guid.size = read32 (ptr + 4);
ptr += 8 + 6;
} else if (strncmp (ptr + 8, "#-", 3) == 0) {
image->heap_tables.data = image->raw_metadata + read32 (ptr);
image->heap_tables.size = read32 (ptr + 4);
ptr += 8 + 3;
image->uncompressed_metadata = TRUE;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name);
} else if (strncmp (ptr + 8, "#Pdb", 5) == 0) {
image->heap_pdb.data = image->raw_metadata + read32 (ptr);
image->heap_pdb.size = read32 (ptr + 4);
ptr += 8 + 5;
} else if (strncmp (ptr + 8, "#JTD", 5) == 0) {
// See https://github.com/dotnet/runtime/blob/110282c71b3f7e1f91ea339953f4a0eba362a62c/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs#L165-L175
// skip read32(ptr) and read32(ptr + 4)
// ignore the content of this stream
image->minimal_delta = TRUE;
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Image '%s' has a minimal delta marker", image->name);
ptr += 8 + 5;
} else {
g_message ("Unknown heap type: %s\n", ptr + 8);
ptr += 8 + strlen (ptr + 8) + 1;
}
pad = ptr - image->raw_metadata;
if (pad % 4)
ptr += 4 - (pad % 4);
}
{
/* Compute the precise size of the string heap by walking back over the trailing nul padding.
*
* ENC minimal delta images require the precise size of the base image string heap to be known.
*/
const char *p;
p = image->heap_strings.data + image->heap_strings.size - 1;
pad = 0;
while (p [0] == '\0' && p [-1] == '\0') {
p--;
pad++;
}
image->heap_strings.size -= pad;
}
i = ((MonoImageLoader*)image->loader)->load_tables (image);
if (!image->metadata_only) {
g_assert (image->heap_guid.data);
g_assert (image->heap_guid.size >= 16);
image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data);
} else {
const guint8 *guid = mono_metadata_module_mvid (image);
if (guid)
image->guid = mono_guid_to_string (guid);
else {
/* PPDB files have no guid */
guint8 empty_guid [16];
memset (empty_guid, 0, sizeof (empty_guid));
image->guid = mono_guid_to_string (empty_guid);
}
}
return i;
}
/*
* Load representation of logical metadata tables, from the "#~" or "#-" stream
*/
static gboolean
load_tables (MonoImage *image)
{
const char *heap_tables = image->heap_tables.data;
const guint32 *rows;
guint64 valid_mask;
int valid = 0, table;
int heap_sizes;
heap_sizes = heap_tables [6];
image->idx_string_wide = ((heap_sizes & 0x01) == 1);
image->idx_guid_wide = ((heap_sizes & 0x02) == 2);
image->idx_blob_wide = ((heap_sizes & 0x04) == 4);
if (G_UNLIKELY (image->minimal_delta)) {
/* sanity check */
g_assert (image->idx_string_wide);
g_assert (image->idx_guid_wide);
g_assert (image->idx_blob_wide);
}
valid_mask = read64 (heap_tables + 8);
rows = (const guint32 *) (heap_tables + 24);
for (table = 0; table < 64; table++){
if ((valid_mask & ((guint64) 1 << table)) == 0){
if (table > MONO_TABLE_LAST)
continue;
image->tables [table].rows_ = 0;
continue;
}
if (table > MONO_TABLE_LAST) {
g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)");
} else {
image->tables [table].rows_ = read32 (rows);
}
rows++;
valid++;
}
image->tables_base = (heap_tables + 24) + (4 * valid);
/* They must be the same */
g_assert ((const void *) image->tables_base == (const void *) rows);
if (image->heap_pdb.size) {
/*
* Obtain token sizes from the pdb stream.
*/
/* 24 = guid + entry point */
int pos = 24;
image->referenced_tables = read64 (image->heap_pdb.data + pos);
pos += 8;
image->referenced_table_rows = g_new0 (int, 64);
for (int i = 0; i < 64; ++i) {
if (image->referenced_tables & ((guint64)1 << i)) {
image->referenced_table_rows [i] = read32 (image->heap_pdb.data + pos);
pos += 4;
}
}
}
mono_metadata_compute_table_bases (image);
return TRUE;
}
gboolean
mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo)
{
if (!load_metadata_ptrs (image, iinfo))
return FALSE;
return load_tables (image);
}
void
mono_image_check_for_module_cctor (MonoImage *image)
{
MonoTableInfo *t, *mt;
t = &image->tables [MONO_TABLE_TYPEDEF];
mt = &image->tables [MONO_TABLE_METHOD];
if (image_is_dynamic (image)) {
/* FIXME: */
image->checked_module_cctor = TRUE;
return;
}
if (table_info_get_rows (t) >= 1) {
guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME);
const char *name = mono_metadata_string_heap (image, nameidx);
if (strcmp (name, "<Module>") == 0) {
guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1;
guint32 last_method;
if (table_info_get_rows (t) > 1)
last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1;
else
last_method = table_info_get_rows (mt);
for (; first_method < last_method; first_method++) {
nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME);
name = mono_metadata_string_heap (image, nameidx);
if (strcmp (name, ".cctor") == 0) {
image->has_module_cctor = TRUE;
image->checked_module_cctor = TRUE;
return;
}
}
}
}
image->has_module_cctor = FALSE;
image->checked_module_cctor = TRUE;
}
/**
* mono_image_load_module_checked:
*
* Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
* it cannot be loaded. NULL without MonoError being set will be interpreted as "not found".
*/
MonoImage*
mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error)
{
error_init (error);
if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
return NULL;
if (image->modules_loaded [idx - 1])
return image->modules [idx - 1];
/* SRE still uses image->modules, but they are not loaded from files, so the rest of this function is dead code for netcore */
g_assert_not_reached ();
}
/**
* mono_image_load_module:
*/
MonoImage*
mono_image_load_module (MonoImage *image, int idx)
{
ERROR_DECL (error);
MonoImage *result = mono_image_load_module_checked (image, idx, error);
mono_error_assert_ok (error);
return result;
}
static gpointer
class_key_extract (gpointer value)
{
MonoClass *klass = (MonoClass *)value;
return GUINT_TO_POINTER (m_class_get_type_token (klass));
}
static gpointer*
class_next_value (gpointer value)
{
MonoClassDef *klass = (MonoClassDef *)value;
return (gpointer*)m_classdef_get_next_class_cache (klass);
}
/**
* mono_image_init:
*/
void
mono_image_init (MonoImage *image)
{
mono_os_mutex_init_recursive (&image->lock);
mono_os_mutex_init_recursive (&image->szarray_cache_lock);
image->mempool = mono_mempool_new_size (INITIAL_IMAGE_SIZE);
mono_internal_hash_table_init (&image->class_cache,
g_direct_hash,
class_key_extract,
class_next_value);
image->field_cache = mono_conc_hashtable_new (NULL, NULL);
image->typespec_cache = mono_conc_hashtable_new (NULL, NULL);
image->memberref_signatures = g_hash_table_new (NULL, NULL);
image->method_signatures = g_hash_table_new (NULL, NULL);
image->property_hash = mono_property_hash_new ();
}
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
#define SWAP64(x) (x) = GUINT64_FROM_LE ((x))
#define SWAP32(x) (x) = GUINT32_FROM_LE ((x))
#define SWAP16(x) (x) = GUINT16_FROM_LE ((x))
#define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0)
#else
#define SWAP64(x)
#define SWAP32(x)
#define SWAP16(x)
#define SWAPPDE(x)
#endif
static int
do_load_header_internal (const char *raw_data, guint32 raw_data_len, MonoDotNetHeader *header, int offset, gboolean image_is_module_handle)
{
MonoDotNetHeader64 header64;
#ifdef HOST_WIN32
if (!image_is_module_handle)
#endif
if (offset + sizeof (MonoDotNetHeader32) > raw_data_len)
return -1;
memcpy (header, raw_data + offset, sizeof (MonoDotNetHeader));
if (header->pesig [0] != 'P' || header->pesig [1] != 'E' || header->pesig [2] || header->pesig [3])
return -1;
/* endian swap the fields common between PE and PE+ */
SWAP32 (header->coff.coff_time);
SWAP32 (header->coff.coff_symptr);
SWAP32 (header->coff.coff_symcount);
SWAP16 (header->coff.coff_machine);
SWAP16 (header->coff.coff_sections);
SWAP16 (header->coff.coff_opt_header_size);
SWAP16 (header->coff.coff_attributes);
/* MonoPEHeader */
SWAP32 (header->pe.pe_code_size);
SWAP32 (header->pe.pe_uninit_data_size);
SWAP32 (header->pe.pe_rva_entry_point);
SWAP32 (header->pe.pe_rva_code_base);
SWAP32 (header->pe.pe_rva_data_base);
SWAP16 (header->pe.pe_magic);
/* now we are ready for the basic tests */
if (header->pe.pe_magic == 0x10B) {
offset += sizeof (MonoDotNetHeader);
SWAP32 (header->pe.pe_data_size);
if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4))
return -1;
SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */
SWAP32 (header->nt.pe_stack_reserve);
SWAP32 (header->nt.pe_stack_commit);
SWAP32 (header->nt.pe_heap_reserve);
SWAP32 (header->nt.pe_heap_commit);
} else if (header->pe.pe_magic == 0x20B) {
/* PE32+ file format */
if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4))
return -1;
memcpy (&header64, raw_data + offset, sizeof (MonoDotNetHeader64));
offset += sizeof (MonoDotNetHeader64);
/* copy the fields already swapped. the last field, pe_data_size, is missing */
memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4);
/* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much.
* will be fixed when we change MonoDotNetHeader to not match the 32 bit variant
*/
SWAP64 (header64.nt.pe_image_base);
header->nt.pe_image_base = header64.nt.pe_image_base;
SWAP64 (header64.nt.pe_stack_reserve);
header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve;
SWAP64 (header64.nt.pe_stack_commit);
header->nt.pe_stack_commit = header64.nt.pe_stack_commit;
SWAP64 (header64.nt.pe_heap_reserve);
header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve;
SWAP64 (header64.nt.pe_heap_commit);
header->nt.pe_heap_commit = header64.nt.pe_heap_commit;
header->nt.pe_section_align = header64.nt.pe_section_align;
header->nt.pe_file_alignment = header64.nt.pe_file_alignment;
header->nt.pe_os_major = header64.nt.pe_os_major;
header->nt.pe_os_minor = header64.nt.pe_os_minor;
header->nt.pe_user_major = header64.nt.pe_user_major;
header->nt.pe_user_minor = header64.nt.pe_user_minor;
header->nt.pe_subsys_major = header64.nt.pe_subsys_major;
header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor;
header->nt.pe_reserved_1 = header64.nt.pe_reserved_1;
header->nt.pe_image_size = header64.nt.pe_image_size;
header->nt.pe_header_size = header64.nt.pe_header_size;
header->nt.pe_checksum = header64.nt.pe_checksum;
header->nt.pe_subsys_required = header64.nt.pe_subsys_required;
header->nt.pe_dll_flags = header64.nt.pe_dll_flags;
header->nt.pe_loader_flags = header64.nt.pe_loader_flags;
header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count;
/* copy the datadir */
memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir));
} else {
return -1;
}
/* MonoPEHeaderNT: not used yet */
SWAP32 (header->nt.pe_section_align); /* must be 8192 */
SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */
SWAP16 (header->nt.pe_os_major); /* must be 4 */
SWAP16 (header->nt.pe_os_minor); /* must be 0 */
SWAP16 (header->nt.pe_user_major);
SWAP16 (header->nt.pe_user_minor);
SWAP16 (header->nt.pe_subsys_major);
SWAP16 (header->nt.pe_subsys_minor);
SWAP32 (header->nt.pe_reserved_1);
SWAP32 (header->nt.pe_image_size);
SWAP32 (header->nt.pe_header_size);
SWAP32 (header->nt.pe_checksum);
SWAP16 (header->nt.pe_subsys_required);
SWAP16 (header->nt.pe_dll_flags);
SWAP32 (header->nt.pe_loader_flags);
SWAP32 (header->nt.pe_data_dir_count);
/* MonoDotNetHeader: mostly unused */
SWAPPDE (header->datadir.pe_export_table);
SWAPPDE (header->datadir.pe_import_table);
SWAPPDE (header->datadir.pe_resource_table);
SWAPPDE (header->datadir.pe_exception_table);
SWAPPDE (header->datadir.pe_certificate_table);
SWAPPDE (header->datadir.pe_reloc_table);
SWAPPDE (header->datadir.pe_debug);
SWAPPDE (header->datadir.pe_copyright);
SWAPPDE (header->datadir.pe_global_ptr);
SWAPPDE (header->datadir.pe_tls_table);
SWAPPDE (header->datadir.pe_load_config_table);
SWAPPDE (header->datadir.pe_bound_import);
SWAPPDE (header->datadir.pe_iat);
SWAPPDE (header->datadir.pe_delay_import_desc);
SWAPPDE (header->datadir.pe_cli_header);
SWAPPDE (header->datadir.pe_reserved);
return offset;
}
/*
* Returns < 0 to indicate an error.
*/
static int
do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset)
{
offset = do_load_header_internal (image->raw_data, image->raw_data_len, header, offset,
#ifdef HOST_WIN32
m_image_is_module_handle (image));
#else
FALSE);
#endif
#ifdef HOST_WIN32
if (m_image_is_module_handle (image))
image->storage->raw_data_len = header->nt.pe_image_size;
#endif
return offset;
}
mono_bool
mono_has_pdb_checksum (char *raw_data, uint32_t raw_data_len)
{
MonoDotNetHeader cli_header;
MonoMSDOSHeader msdos;
int idx;
guint8 *data;
int offset = 0;
memcpy (&msdos, raw_data + offset, sizeof (msdos));
if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) {
return FALSE;
}
msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
offset = msdos.pe_offset;
int ret = do_load_header_internal (raw_data, raw_data_len, &cli_header, offset, FALSE);
if ( ret >= 0 ) {
MonoPEDirEntry *debug_dir_entry = (MonoPEDirEntry *) &cli_header.datadir.pe_debug;
ImageDebugDirectory debug_dir;
if (!debug_dir_entry->size)
return FALSE;
else {
const int top = cli_header.coff.coff_sections;
int addr = debug_dir_entry->rva;
int i = 0;
for (i = 0; i < top; i++){
MonoSectionTable t;
if (ret + sizeof (MonoSectionTable) > raw_data_len) {
return FALSE;
}
memcpy (&t, raw_data + ret, sizeof (MonoSectionTable));
ret += sizeof (MonoSectionTable);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
t.st_virtual_address = GUINT32_FROM_LE (t.st_virtual_address);
t.st_raw_data_size = GUINT32_FROM_LE (t.st_raw_data_size);
t.st_raw_data_ptr = GUINT32_FROM_LE (t.st_raw_data_ptr);
#endif
/* consistency checks here */
if ((addr >= t.st_virtual_address) &&
(addr < t.st_virtual_address + t.st_raw_data_size)){
addr = addr - t.st_virtual_address + t.st_raw_data_ptr;
break;
}
}
for (idx = 0; idx < debug_dir_entry->size / sizeof (ImageDebugDirectory); ++idx) {
data = (guint8 *) ((ImageDebugDirectory *) (raw_data + addr) + idx);
debug_dir.characteristics = read32(data);
debug_dir.time_date_stamp = read32(data + 4);
debug_dir.major_version = read16(data + 8);
debug_dir.minor_version = read16(data + 10);
debug_dir.type = read32(data + 12);
if (debug_dir.type == DEBUG_DIR_PDB_CHECKSUM || debug_dir.type == DEBUG_DIR_REPRODUCIBLE)
return TRUE;
}
}
}
return FALSE;
}
gboolean
mono_image_load_pe_data (MonoImage *image)
{
return ((MonoImageLoader*)image->loader)->load_pe_data (image);
}
static gboolean
pe_image_load_pe_data (MonoImage *image)
{
MonoCLIImageInfo *iinfo;
MonoDotNetHeader *header;
MonoMSDOSHeader msdos;
gint32 offset = 0;
iinfo = image->image_info;
header = &iinfo->cli_header;
#ifdef HOST_WIN32
if (!m_image_is_module_handle (image))
#endif
if (offset + sizeof (msdos) > image->raw_data_len)
goto invalid_image;
memcpy (&msdos, image->raw_data + offset, sizeof (msdos));
if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z'))
goto invalid_image;
msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset);
offset = msdos.pe_offset;
offset = do_load_header (image, header, offset);
if (offset < 0)
goto invalid_image;
/*
* this tests for a x86 machine type, but itanium, amd64 and others could be used, too.
* we skip this test.
if (header->coff.coff_machine != 0x14c)
goto invalid_image;
*/
#if 0
/*
* The spec says that this field should contain 6.0, but Visual Studio includes a new compiler,
* which produces binaries with 7.0. From Sergey:
*
* The reason is that MSVC7 uses traditional compile/link
* sequence for CIL executables, and VS.NET (and Framework
* SDK) includes linker version 7, that puts 7.0 in this
* field. That's why it's currently not possible to load VC
* binaries with Mono. This field is pretty much meaningless
* anyway (what linker?).
*/
if (header->pe.pe_major != 6 || header->pe.pe_minor != 0)
goto invalid_image;
#endif
/*
* FIXME: byte swap all addresses here for header.
*/
if (!load_section_tables (image, iinfo, offset))
goto invalid_image;
return TRUE;
invalid_image:
return FALSE;
}
gboolean
mono_image_load_cli_data (MonoImage *image)
{
return ((MonoImageLoader*)image->loader)->load_cli_data (image);
}
static gboolean
pe_image_load_cli_data (MonoImage *image)
{
MonoCLIImageInfo *iinfo;
iinfo = image->image_info;
/* Load the CLI header */
if (!mono_image_load_cli_header (image, iinfo))
return FALSE;
if (!mono_image_load_metadata (image, iinfo))
return FALSE;
return TRUE;
}
static void
mono_image_load_time_date_stamp (MonoImage *image)
{
image->time_date_stamp = 0;
#ifndef HOST_WIN32
if (!image->filename)
return;
gunichar2 *uni_name = g_utf8_to_utf16 (image->filename, -1, NULL, NULL, NULL);
mono_pe_file_time_date_stamp (uni_name, &image->time_date_stamp);
g_free (uni_name);
#endif
}
void
mono_image_load_names (MonoImage *image)
{
/* modules don't have an assembly table row */
if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY])) {
image->assembly_name = mono_metadata_string_heap (image,
mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY],
0, MONO_ASSEMBLY_NAME));
}
/* Portable pdb images don't have a MODULE row */
/* Minimal ENC delta images index the combined string heap of the base and delta image,
* so the module index is out of bounds here.
*/
if (table_info_get_rows (&image->tables [MONO_TABLE_MODULE]) && !image->minimal_delta) {
image->module_name = mono_metadata_string_heap (image,
mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE],
0, MONO_MODULE_NAME));
}
}
static gboolean
pe_image_load_tables (MonoImage *image)
{
return TRUE;
}
static gboolean
pe_image_match (MonoImage *image)
{
if (image->raw_data [0] == 'M' && image->raw_data [1] == 'Z')
return TRUE;
return FALSE;
}
static const MonoImageLoader pe_loader = {
pe_image_match,
pe_image_load_pe_data,
pe_image_load_cli_data,
pe_image_load_tables,
};
static void
install_pe_loader (void)
{
mono_install_image_loader (&pe_loader);
}
/*
Equivalent C# code:
static void Main () {
string str = "...";
int h = 5381;
for (int i = 0; i < str.Length; ++i)
h = ((h << 5) + h) ^ str[i];
Console.WriteLine ("{0:X}", h);
}
*/
static int
hash_guid (const char *str)
{
int h = 5381;
while (*str) {
h = ((h << 5) + h) ^ *str;
++str;
}
return h;
}
static void
dump_encmap (MonoImage *image)
{
MonoTableInfo *encmap = &image->tables [MONO_TABLE_ENCMAP];
if (!encmap || !table_info_get_rows (encmap))
return;
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ENCMAP for %s", image->filename);
for (int i = 0; i < table_info_get_rows (encmap); ++i) {
guint32 cols [MONO_ENCMAP_SIZE];
mono_metadata_decode_row (encmap, i, cols, MONO_ENCMAP_SIZE);
int token = cols [MONO_ENCMAP_TOKEN];
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%08x: 0x%08x table: %s", i+1, token, mono_meta_table_name (mono_metadata_token_table (token)));
}
}
}
static MonoImage *
do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status,
gboolean care_about_cli, gboolean care_about_pecoff)
{
ERROR_DECL (error);
GSList *l;
MONO_PROFILER_RAISE (image_loading, (image));
mono_image_init (image);
if (!image->metadata_only) {
for (l = image_loaders; l; l = l->next) {
MonoImageLoader *loader = (MonoImageLoader *)l->data;
if (loader->match (image)) {
image->loader = loader;
break;
}
}
if (!image->loader) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
goto invalid_image;
}
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
if (care_about_pecoff == FALSE)
goto done;
if (!mono_image_load_pe_data (image))
goto invalid_image;
} else {
image->loader = (MonoImageLoader*)&pe_loader;
}
if (care_about_cli == FALSE) {
goto done;
}
if (!mono_image_load_cli_data (image))
goto invalid_image;
dump_encmap (image);
mono_image_load_names (image);
mono_image_load_time_date_stamp (image);
done:
MONO_PROFILER_RAISE (image_loaded, (image));
if (status)
*status = MONO_IMAGE_OK;
return image;
invalid_image:
if (!is_ok (error)) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Could not load image %s due to %s", image->name, mono_error_get_message (error));
mono_error_cleanup (error);
}
MONO_PROFILER_RAISE (image_failed, (image));
mono_image_close (image);
return NULL;
}
static gboolean
mono_image_storage_trypublish (MonoImageStorage *candidate, MonoImageStorage **out_storage)
{
gboolean result;
mono_images_storage_lock ();
MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, candidate->key);
if (val && !mono_refcount_tryinc (val)) {
// We raced against a mono_image_storage_dtor in progress.
val = NULL;
}
if (val) {
*out_storage = val;
result = FALSE;
} else {
g_hash_table_insert (images_storage_hash, candidate->key, candidate);
result = TRUE;
}
mono_images_storage_unlock ();
return result;
}
static void
mono_image_storage_unpublish (MonoImageStorage *storage)
{
mono_images_storage_lock ();
g_assert (storage->ref.ref == 0);
MonoImageStorage *published = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, storage->key);
if (published == storage) {
g_hash_table_remove (images_storage_hash, storage->key);
}
mono_images_storage_unlock ();
}
static gboolean
mono_image_storage_tryaddref (const char *key, MonoImageStorage **found)
{
gboolean result = FALSE;
mono_images_storage_lock ();
MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, key);
if (val && !mono_refcount_tryinc (val)) {
// We raced against a mono_image_storage_dtor in progress.
val = NULL;
}
if (val) {
*found = val;
result = TRUE;
}
mono_images_storage_unlock ();
return result;
}
static void
mono_image_storage_dtor (gpointer self)
{
MonoImageStorage *storage = (MonoImageStorage *)self;
mono_image_storage_unpublish (storage);
#ifdef HOST_WIN32
if (storage->is_module_handle && !storage->has_entry_point) {
mono_images_lock ();
FreeLibrary ((HMODULE) storage->raw_data);
mono_images_unlock ();
}
#endif
if (storage->raw_buffer_used) {
if (storage->raw_data != NULL) {
#ifndef HOST_WIN32
if (storage->fileio_used)
mono_file_unmap_fileio (storage->raw_data, storage->raw_data_handle);
else
#endif
mono_file_unmap (storage->raw_data, storage->raw_data_handle);
}
}
if (storage->raw_data_allocated) {
g_free (storage->raw_data);
}
g_free (storage->key);
g_free (storage);
}
static void
mono_image_storage_close (MonoImageStorage *storage)
{
mono_refcount_dec (storage);
}
static gboolean
mono_image_init_raw_data (MonoImage *image, const MonoImageStorage *storage)
{
if (!storage)
return FALSE;
image->raw_data = storage->raw_data;
image->raw_data_len = storage->raw_data_len;
return TRUE;
}
static MonoImageStorage *
mono_image_storage_open (const char *fname)
{
char *key = NULL;
key = mono_path_resolve_symlinks (fname);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoFileMap *filed;
if ((filed = mono_file_map_open (fname)) == NULL){
g_free (key);
return NULL;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_buffer_used = TRUE;
storage->raw_data_len = mono_file_map_size (filed);
storage->raw_data = (char*)mono_file_map (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle);
#if defined(HAVE_MMAP) && !defined (HOST_WIN32)
if (!storage->raw_data) {
storage->fileio_used = TRUE;
storage->raw_data = (char *)mono_file_map_fileio (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle);
}
#endif
mono_file_map_close (filed);
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
static MonoImageStorage *
mono_image_storage_new_raw_data (char *datac, guint32 data_len, gboolean raw_data_allocated, const char *name)
{
char *key = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_data = datac;
storage->raw_data_len = data_len;
storage->raw_data_allocated = raw_data_allocated;
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
static MonoImage *
do_mono_image_open (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status,
gboolean care_about_cli, gboolean care_about_pecoff, gboolean metadata_only)
{
MonoCLIImageInfo *iinfo;
MonoImage *image;
MonoImageStorage *storage = mono_image_storage_open (fname);
if (!storage) {
if (status)
*status = MONO_IMAGE_ERROR_ERRNO;
return NULL;
}
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
if (!image->raw_data) {
mono_image_storage_close (image->storage);
g_free (image);
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->name = mono_path_resolve_symlinks (fname);
image->filename = g_strdup (image->name);
image->metadata_only = metadata_only;
image->ref_count = 1;
image->alc = alc;
return do_mono_image_load (image, status, care_about_cli, care_about_pecoff);
}
/**
* mono_image_loaded_full:
* \param name path or assembly name of the image to load
* \param refonly Check with respect to reflection-only loads?
*
* This routine verifies that the given image is loaded.
* It checks either reflection-only loads only, or normal loads only, as specified by parameter.
*
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded_full (const char *name, gboolean refonly)
{
if (refonly)
return NULL;
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_loaded_internal (mono_alc_get_default (), name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_loaded_internal:
* \param alc The AssemblyLoadContext that should be checked
* \param name path or assembly name of the image to load
* \param refonly Check with respect to reflection-only loads?
*
* This routine verifies that the given image is loaded.
* It checks either reflection-only loads only, or normal loads only, as specified by parameter.
*
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded_internal (MonoAssemblyLoadContext *alc, const char *name)
{
MonoLoadedImages *li = mono_alc_get_loaded_images (alc);
MonoImage *res;
mono_images_lock ();
res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_hash (li), name);
if (!res)
res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_by_name_hash (li), name);
mono_images_unlock ();
return res;
}
/**
* mono_image_loaded:
* \param name path or assembly name of the image to load
* This routine verifies that the given image is loaded. Reflection-only loads do not count.
* \returns the loaded \c MonoImage, or NULL on failure.
*/
MonoImage *
mono_image_loaded (const char *name)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_loaded_internal (mono_alc_get_default (), name);
MONO_EXIT_GC_UNSAFE;
return result;
}
typedef struct {
MonoImage *res;
const char* guid;
} GuidData;
static void
find_by_guid (gpointer key, gpointer val, gpointer user_data)
{
GuidData *data = (GuidData *)user_data;
MonoImage *image;
if (data->res)
return;
image = (MonoImage *)val;
if (strcmp (data->guid, mono_image_get_guid (image)) == 0)
data->res = image;
}
static MonoImage *
mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly);
/**
* mono_image_loaded_by_guid_full:
*
* Looks only in the global loaded images hash, will miss assemblies loaded
* into an AssemblyLoadContext.
*/
MonoImage *
mono_image_loaded_by_guid_full (const char *guid, gboolean refonly)
{
return mono_image_loaded_by_guid_internal (guid, refonly);
}
/**
* mono_image_loaded_by_guid_internal:
*
* Do not use. Looks only in the global loaded images hash, will miss Assembly
* Load Contexts.
*/
static MonoImage *
mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly)
{
/* TODO: Maybe implement this for netcore by searching only the default ALC of the current domain */
return NULL;
}
/**
* mono_image_loaded_by_guid:
*
* Looks only in the global loaded images hash, will miss assemblies loaded
* into an AssemblyLoadContext.
*/
MonoImage *
mono_image_loaded_by_guid (const char *guid)
{
return mono_image_loaded_by_guid_internal (guid, FALSE);
}
static MonoImage *
register_image (MonoLoadedImages *li, MonoImage *image)
{
MonoImage *image2;
char *name = image->name;
GHashTable *loaded_images = mono_loaded_images_get_hash (li);
mono_images_lock ();
image2 = (MonoImage *)g_hash_table_lookup (loaded_images, name);
if (image2) {
/* Somebody else beat us to it */
mono_image_addref (image2);
mono_images_unlock ();
mono_image_close (image);
return image2;
}
GHashTable *loaded_images_by_name = mono_loaded_images_get_by_name_hash (li);
g_hash_table_insert (loaded_images, name, image);
if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == NULL))
g_hash_table_insert (loaded_images_by_name, (char *) image->assembly_name, image);
mono_images_unlock ();
return image;
}
MonoImage *
mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename)
{
MonoCLIImageInfo *iinfo;
MonoImage *image;
char *datac;
if (!data || !data_len) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
datac = data;
if (need_copy) {
datac = (char *)g_try_malloc (data_len);
if (!datac) {
if (status)
*status = MONO_IMAGE_ERROR_ERRNO;
return NULL;
}
memcpy (datac, data, data_len);
}
MonoImageStorage *storage = mono_image_storage_new_raw_data (datac, data_len, need_copy, filename);
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name);
image->filename = filename ? g_strdup (filename) : NULL;
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->metadata_only = metadata_only;
image->ref_count = 1;
image->alc = alc;
image = do_mono_image_load (image, status, TRUE, TRUE);
if (image == NULL)
return NULL;
return register_image (mono_alc_get_loaded_images (alc), image);
}
MonoImage *
mono_image_open_from_data_alc (MonoAssemblyLoadContextGCHandle alc_gchandle, char *data, uint32_t data_len, mono_bool need_copy, MonoImageOpenStatus *status, const char *name)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
MonoAssemblyLoadContext *alc = mono_alc_from_gchandle (alc_gchandle);
result = mono_image_open_from_data_internal (alc, data, data_len, need_copy, status, FALSE, name, name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data_with_name:
*/
MonoImage *
mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name)
{
if (refonly) {
if (status) {
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
}
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, name, name);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data_full:
*/
MonoImage *
mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly)
{
if (refonly) {
if (status) {
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
}
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_image_open_from_data:
*/
MonoImage *
mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status)
{
MonoImage *result;
MONO_ENTER_GC_UNSAFE;
result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL);
MONO_EXIT_GC_UNSAFE;
return result;
}
#ifdef HOST_WIN32
static MonoImageStorage *
mono_image_storage_open_from_module_handle (HMODULE module_handle, const char *fname, gboolean has_entry_point)
{
char *key = g_strdup (fname);
MonoImageStorage *published_storage = NULL;
if (mono_image_storage_tryaddref (key, &published_storage)) {
g_free (key);
return published_storage;
}
MonoImageStorage *storage = g_new0 (MonoImageStorage, 1);
mono_refcount_init (storage, mono_image_storage_dtor);
storage->raw_data = (char*) module_handle;
storage->is_module_handle = TRUE;
storage->has_entry_point = has_entry_point;
storage->key = key;
MonoImageStorage *other_storage = NULL;
if (!mono_image_storage_trypublish (storage, &other_storage)) {
mono_image_storage_close (storage);
storage = other_storage;
}
return storage;
}
/* fname is not duplicated. */
MonoImage*
mono_image_open_from_module_handle (MonoAssemblyLoadContext *alc, HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status)
{
MonoImage* image;
MonoCLIImageInfo* iinfo;
MonoImageStorage *storage = mono_image_storage_open_from_module_handle (module_handle, fname, has_entry_point);
image = g_new0 (MonoImage, 1);
image->storage = storage;
mono_image_init_raw_data (image, storage);
iinfo = g_new0 (MonoCLIImageInfo, 1);
image->image_info = iinfo;
image->name = fname;
image->filename = g_strdup (image->name);
image->ref_count = has_entry_point ? 0 : 1;
image->alc = alc;
image = do_mono_image_load (image, status, TRUE, TRUE);
if (image == NULL)
return NULL;
return register_image (mono_alc_get_loaded_images (alc), image);
}
#endif
/**
* mono_image_open_full:
*/
MonoImage *
mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly)
{
if (refonly) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
return NULL;
}
return mono_image_open_a_lot (mono_alc_get_default (), fname, status);
}
static MonoImage *
mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
MonoImage *image;
GHashTable *loaded_images = mono_loaded_images_get_hash (li);
char *absfname;
g_return_val_if_fail (fname != NULL, NULL);
#ifdef HOST_WIN32
// Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll),
// then assemblies need to be loaded with LoadLibrary:
if (coree_module_handle) {
HMODULE module_handle;
gunichar2 *fname_utf16;
DWORD last_error;
absfname = mono_path_resolve_symlinks (fname);
fname_utf16 = NULL;
/* There is little overhead because the OS loader lock is held by LoadLibrary. */
mono_images_lock ();
image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname);
if (image) { // Image already loaded
g_assert (m_image_is_module_handle (image));
if (m_image_has_entry_point (image) && image->ref_count == 0) {
/* Increment reference count on images loaded outside of the runtime. */
fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
/* The image is already loaded because _CorDllMain removes images from the hash. */
module_handle = LoadLibrary (fname_utf16);
g_assert (module_handle == (HMODULE) image->raw_data);
}
mono_image_addref (image);
mono_images_unlock ();
if (fname_utf16)
g_free (fname_utf16);
g_free (absfname);
return image;
}
// Image not loaded, load it now
fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL);
module_handle = MonoLoadImage (fname_utf16);
if (status && module_handle == NULL)
last_error = mono_w32error_get_last ();
/* mono_image_open_from_module_handle is called by _CorDllMain. */
image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname);
if (image)
mono_image_addref (image);
mono_images_unlock ();
g_free (fname_utf16);
if (module_handle == NULL) {
g_assert (!image);
g_free (absfname);
if (status) {
if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT) {
if (status)
*status = MONO_IMAGE_IMAGE_INVALID;
} else {
if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND)
mono_set_errno (ENOENT);
else
mono_set_errno (0);
}
}
return NULL;
}
if (image) {
g_assert (m_image_is_module_handle (image));
g_assert (m_image_has_entry_point (image));
g_free (absfname);
return image;
}
return mono_image_open_from_module_handle (alc, module_handle, absfname, FALSE, status);
}
#endif
absfname = mono_path_resolve_symlinks (fname);
/*
* The easiest solution would be to do all the loading inside the mutex,
* but that would lead to scalability problems. So we let the loading
* happen outside the mutex, and if multiple threads happen to load
* the same image, we discard all but the first copy.
*/
mono_images_lock ();
image = (MonoImage *)g_hash_table_lookup (loaded_images, absfname);
g_free (absfname);
if (image) { // Image already loaded
mono_image_addref (image);
mono_images_unlock ();
return image;
}
mono_images_unlock ();
// Image not loaded, load it now
image = do_mono_image_open (alc, fname, status, TRUE, TRUE, FALSE);
if (image == NULL)
return NULL;
return register_image (li, image);
}
MonoImage *
mono_image_open_a_lot (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
MonoLoadedImages *li = mono_alc_get_loaded_images (alc);
return mono_image_open_a_lot_parameterized (li, alc, fname, status);
}
/**
* mono_image_open:
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns An open image of type \c MonoImage or NULL on error.
* The caller holds a temporary reference to the returned image which should be cleared
* when no longer needed by calling \c mono_image_close.
* if NULL, then check the value of \p status for details on the error
*/
MonoImage *
mono_image_open (const char *fname, MonoImageOpenStatus *status)
{
return mono_image_open_a_lot (mono_alc_get_default (), fname, status);
}
/**
* mono_pe_file_open:
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns An open image of type \c MonoImage or NULL on error. if
* NULL, then check the value of \p status for details on the error.
* This variant for \c mono_image_open DOES NOT SET UP CLI METADATA.
* It's just a PE file loader, used for \c FileVersionInfo. It also does
* not use the image cache.
*/
MonoImage *
mono_pe_file_open (const char *fname, MonoImageOpenStatus *status)
{
g_return_val_if_fail (fname != NULL, NULL);
return do_mono_image_open (mono_alc_get_default (), fname, status, FALSE, TRUE, FALSE);
}
/**
* mono_image_open_raw
* \param fname filename that points to the module we want to open
* \param status An error condition is returned in this field
* \returns an image without loading neither pe or cli data.
* Use mono_image_load_pe_data and mono_image_load_cli_data to load them.
*/
MonoImage *
mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
g_return_val_if_fail (fname != NULL, NULL);
return do_mono_image_open (alc, fname, status, FALSE, FALSE, FALSE);
}
/*
* mono_image_open_metadata_only:
*
* Open an image which contains metadata only without a PE header.
*/
MonoImage *
mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status)
{
return do_mono_image_open (alc, fname, status, TRUE, TRUE, TRUE);
}
/**
* mono_image_fixup_vtable:
*/
void
mono_image_fixup_vtable (MonoImage *image)
{
#ifdef HOST_WIN32
MonoCLIImageInfo *iinfo;
MonoPEDirEntry *de;
MonoVTableFixup *vtfixup;
int count;
gpointer slot;
guint16 slot_type;
int slot_count;
g_assert (m_image_is_module_handle (image));
iinfo = image->image_info;
de = &iinfo->cli_cli_header.ch_vtable_fixups;
if (!de->rva || !de->size)
return;
vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva);
if (!vtfixup)
return;
count = de->size / sizeof (MonoVTableFixup);
while (count--) {
if (!vtfixup->rva || !vtfixup->count)
continue;
slot = mono_image_rva_map (image, vtfixup->rva);
g_assert (slot);
slot_type = vtfixup->type;
slot_count = vtfixup->count;
if (slot_type & VTFIXUP_TYPE_32BIT)
while (slot_count--) {
*((guint32*) slot) = (guint32)(gsize)mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type);
slot = ((guint32*) slot) + 1;
}
else if (slot_type & VTFIXUP_TYPE_64BIT)
while (slot_count--) {
*((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type);
slot = ((guint32*) slot) + 1;
}
else
g_assert_not_reached();
vtfixup++;
}
#else
g_assert_not_reached();
#endif
}
static void
free_hash_table (gpointer key, gpointer val, gpointer user_data)
{
g_hash_table_destroy ((GHashTable*)val);
}
/*
static void
free_mr_signatures (gpointer key, gpointer val, gpointer user_data)
{
mono_metadata_free_method_signature ((MonoMethodSignature*)val);
}
*/
static void
free_array_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_slist_free ((GSList*)val);
}
/**
* mono_image_addref:
* \param image The image file we wish to add a reference to
* Increases the reference count of an image.
*/
void
mono_image_addref (MonoImage *image)
{
mono_atomic_inc_i32 (&image->ref_count);
}
void
mono_dynamic_stream_reset (MonoDynamicStream* stream)
{
stream->alloc_size = stream->index = stream->offset = 0;
g_free (stream->data);
stream->data = NULL;
if (stream->hash) {
g_hash_table_destroy (stream->hash);
stream->hash = NULL;
}
}
static void
free_hash (GHashTable *hash)
{
if (hash)
g_hash_table_destroy (hash);
}
void
mono_wrapper_caches_free (MonoWrapperCaches *cache)
{
free_hash (cache->delegate_invoke_cache);
free_hash (cache->delegate_begin_invoke_cache);
free_hash (cache->delegate_end_invoke_cache);
free_hash (cache->delegate_bound_static_invoke_cache);
free_hash (cache->runtime_invoke_signature_cache);
free_hash (cache->delegate_abstract_invoke_cache);
free_hash (cache->runtime_invoke_method_cache);
free_hash (cache->managed_wrapper_cache);
free_hash (cache->native_wrapper_cache);
free_hash (cache->native_wrapper_aot_cache);
free_hash (cache->native_wrapper_check_cache);
free_hash (cache->native_wrapper_aot_check_cache);
free_hash (cache->native_func_wrapper_aot_cache);
free_hash (cache->native_func_wrapper_indirect_cache);
free_hash (cache->synchronized_cache);
free_hash (cache->unbox_wrapper_cache);
free_hash (cache->cominterop_invoke_cache);
free_hash (cache->cominterop_wrapper_cache);
free_hash (cache->thunk_invoke_cache);
}
static void
mono_image_close_except_pools_all (MonoImage**images, int image_count)
{
for (int i = 0; i < image_count; ++i) {
if (images [i]) {
if (!mono_image_close_except_pools (images [i]))
images [i] = NULL;
}
}
}
/*
* Returns whether mono_image_close_finish() must be called as well.
* We must unload images in two steps because clearing the domain in
* SGen requires the class metadata to be intact, but we need to free
* the mono_g_hash_tables in case a collection occurs during domain
* unloading and the roots would trip up the GC.
*/
gboolean
mono_image_close_except_pools (MonoImage *image)
{
int i;
g_return_val_if_fail (image != NULL, FALSE);
if (!mono_loaded_images_remove_image (image))
return FALSE;
#ifdef HOST_WIN32
if (m_image_is_module_handle (image) && m_image_has_entry_point (image)) {
mono_images_lock ();
if (image->ref_count == 0) {
/* Image will be closed by _CorDllMain. */
FreeLibrary ((HMODULE) image->raw_data);
mono_images_unlock ();
return FALSE;
}
mono_images_unlock ();
}
#endif
MONO_PROFILER_RAISE (image_unloading, (image));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image);
mono_image_invoke_unload_hook (image);
mono_metadata_update_cleanup_on_close (image);
/*
* The caches inside a MonoImage might refer to metadata which is stored in referenced
* assemblies, so we can't release these references in mono_assembly_close () since the
* MonoImage might outlive its associated MonoAssembly.
*/
if (image->references && !image_is_dynamic (image)) {
for (i = 0; i < image->nreferences; i++) {
if (image->references [i] && image->references [i] != REFERENCE_MISSING) {
if (!mono_assembly_close_except_image_pools (image->references [i]))
image->references [i] = NULL;
}
}
} else {
if (image->references) {
g_free (image->references);
image->references = NULL;
}
}
/* a MonoDynamicImage doesn't have any storage */
g_assert (image_is_dynamic (image) || image->storage != NULL);
if (image->storage && m_image_is_raw_data_allocated (image)) {
/* FIXME: do we need this? (image is disposed anyway) */
/* image->raw_metadata and cli_sections might lie inside image->raw_data */
MonoCLIImageInfo *ii = image->image_info;
if ((image->raw_metadata > image->raw_data) &&
(image->raw_metadata <= (image->raw_data + image->raw_data_len)))
image->raw_metadata = NULL;
for (i = 0; i < ii->cli_section_count; i++)
if (((char*)(ii->cli_sections [i]) > image->raw_data) &&
((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len)))
ii->cli_sections [i] = NULL;
}
if (image->storage)
mono_image_storage_close (image->storage);
if (debug_assembly_unload) {
char *old_name = image->name;
image->name = g_strdup_printf ("%s - UNLOADED", old_name);
g_free (old_name);
g_free (image->filename);
image->filename = NULL;
} else {
g_free (image->name);
g_free (image->filename);
g_free (image->guid);
g_free (image->version);
}
if (image->method_cache)
g_hash_table_destroy (image->method_cache);
if (image->methodref_cache)
g_hash_table_destroy (image->methodref_cache);
mono_internal_hash_table_destroy (&image->class_cache);
mono_conc_hashtable_destroy (image->field_cache);
if (image->array_cache) {
g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL);
g_hash_table_destroy (image->array_cache);
}
if (image->szarray_cache)
g_hash_table_destroy (image->szarray_cache);
if (image->ptr_cache)
g_hash_table_destroy (image->ptr_cache);
if (image->name_cache) {
g_hash_table_foreach (image->name_cache, free_hash_table, NULL);
g_hash_table_destroy (image->name_cache);
}
free_hash (image->icall_wrapper_cache);
if (image->var_gparam_cache)
mono_conc_hashtable_destroy (image->var_gparam_cache);
if (image->mvar_gparam_cache)
mono_conc_hashtable_destroy (image->mvar_gparam_cache);
free_hash (image->wrapper_param_names);
free_hash (image->native_func_wrapper_cache);
mono_conc_hashtable_destroy (image->typespec_cache);
#ifdef ENABLE_WEAK_ATTR
free_hash (image->weak_field_indexes);
#endif
mono_wrapper_caches_free (&image->wrapper_caches);
/* The ownership of signatures is not well defined */
g_hash_table_destroy (image->memberref_signatures);
g_hash_table_destroy (image->method_signatures);
if (image->rgctx_template_hash)
g_hash_table_destroy (image->rgctx_template_hash);
if (image->property_hash)
mono_property_hash_destroy (image->property_hash);
/*
reflection_info_unregister_classes is only required by dynamic images, which will not be properly
cleared during shutdown as we don't perform regular appdomain unload for the root one.
*/
g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ());
image->reflection_info_unregister_classes = NULL;
if (image->interface_bitset) {
mono_unload_interface_ids (image->interface_bitset);
mono_bitset_free (image->interface_bitset);
}
if (image->image_info){
MonoCLIImageInfo *ii = image->image_info;
g_free (ii->cli_section_tables);
g_free (ii->cli_sections);
g_free (image->image_info);
}
mono_image_close_except_pools_all (image->files, image->file_count);
mono_image_close_except_pools_all (image->modules, image->module_count);
g_free (image->modules_loaded);
if (image->has_updates)
mono_metadata_update_image_close_except_pools_all (image);
mono_os_mutex_destroy (&image->szarray_cache_lock);
mono_os_mutex_destroy (&image->lock);
/*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/
if (image_is_dynamic (image)) {
/* Dynamic images are GC_MALLOCed */
g_free ((char*)image->module_name);
mono_dynamic_image_free ((MonoDynamicImage*)image);
}
MONO_PROFILER_RAISE (image_unloaded, (image));
return TRUE;
}
static void
mono_image_close_all (MonoImage**images, int image_count)
{
for (int i = 0; i < image_count; ++i) {
if (images [i])
mono_image_close_finish (images [i]);
}
if (images)
g_free (images);
}
void
mono_image_close_finish (MonoImage *image)
{
int i;
if (image->references && !image_is_dynamic (image)) {
for (i = 0; i < image->nreferences; i++) {
if (image->references [i] && image->references [i] != REFERENCE_MISSING)
mono_assembly_close_finish (image->references [i]);
}
g_free (image->references);
image->references = NULL;
}
mono_image_close_all (image->files, image->file_count);
mono_image_close_all (image->modules, image->module_count);
mono_metadata_update_image_close_all (image);
#ifndef DISABLE_PERFCOUNTERS
/* FIXME: use an explicit subtraction method as soon as it's available */
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (image->mempool));
#endif
if (!image_is_dynamic (image)) {
if (debug_assembly_unload)
mono_mempool_invalidate (image->mempool);
else {
mono_mempool_destroy (image->mempool);
g_free (image);
}
} else {
if (debug_assembly_unload)
mono_mempool_invalidate (image->mempool);
else {
mono_mempool_destroy (image->mempool);
mono_dynamic_image_free_image ((MonoDynamicImage*)image);
}
}
}
/**
* mono_image_close:
* \param image The image file we wish to close
* Closes an image file, deallocates all memory consumed and
* unmaps all possible sections of the file
*/
void
mono_image_close (MonoImage *image)
{
if (mono_image_close_except_pools (image))
mono_image_close_finish (image);
}
/**
* mono_image_strerror:
* \param status an code indicating the result from a recent operation
* \returns a string describing the error
*/
const char *
mono_image_strerror (MonoImageOpenStatus status)
{
switch (status){
case MONO_IMAGE_OK:
return "success";
case MONO_IMAGE_ERROR_ERRNO:
return strerror (errno);
case MONO_IMAGE_IMAGE_INVALID:
return "File does not contain a valid CIL image";
case MONO_IMAGE_MISSING_ASSEMBLYREF:
return "An assembly was referenced, but could not be found";
}
return "Internal error";
}
static gpointer
mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id,
guint32 lang_id, gunichar2 *name,
MonoPEResourceDirEntry *entry,
MonoPEResourceDir *root, guint32 level)
{
gboolean is_string, is_dir;
guint32 name_offset, dir_offset;
/* Level 0 holds a directory entry for each type of resource
* (identified by ID or name).
*
* Level 1 holds a directory entry for each named resource
* item, and each "anonymous" item of a particular type of
* resource.
*
* Level 2 holds a directory entry for each language pointing to
* the actual data.
*/
is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry);
name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry);
is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry);
dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry);
if(level==0) {
if (is_string)
return NULL;
} else if (level==1) {
if (res_id != name_offset)
return NULL;
#if 0
if(name!=NULL &&
is_string==TRUE && name!=lookup (name_offset)) {
return(NULL);
}
#endif
} else if (level==2) {
if (is_string || (lang_id != 0 && name_offset != lang_id))
return NULL;
} else {
g_assert_not_reached ();
}
if (is_dir) {
MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset);
MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1);
guint32 entries, i;
entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries);
for(i=0; i<entries; i++) {
MonoPEResourceDirEntry *sub_entry=&sub_entries[i];
gpointer ret;
ret=mono_image_walk_resource_tree (info, res_id,
lang_id, name,
sub_entry, root,
level+1);
if(ret!=NULL) {
return(ret);
}
}
return(NULL);
} else {
MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset);
MonoPEResourceDataEntry *res;
res = g_new0 (MonoPEResourceDataEntry, 1);
res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset);
res->rde_size = GUINT32_TO_LE (data_entry->rde_size);
res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage);
res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved);
return (res);
}
}
/**
* mono_image_lookup_resource:
* \param image the image to look up the resource in
* \param res_id A \c MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup.
* \param lang_id The language id.
* \param name the resource name to lookup.
* \returns NULL if not found, otherwise a pointer to the in-memory representation
* of the given resource. The caller should free it using \c g_free when no longer
* needed.
*/
gpointer
mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name)
{
MonoCLIImageInfo *info;
MonoDotNetHeader *header;
MonoPEDatadir *datadir;
MonoPEDirEntry *rsrc;
MonoPEResourceDir *resource_dir;
MonoPEResourceDirEntry *res_entries;
guint32 entries, i;
if(image==NULL) {
return(NULL);
}
mono_image_ensure_section_idx (image, MONO_SECTION_RSRC);
info = (MonoCLIImageInfo *)image->image_info;
if(info==NULL) {
return(NULL);
}
header=&info->cli_header;
if(header==NULL) {
return(NULL);
}
datadir=&header->datadir;
if(datadir==NULL) {
return(NULL);
}
rsrc=&datadir->pe_resource_table;
if(rsrc==NULL) {
return(NULL);
}
resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva);
if(resource_dir==NULL) {
return(NULL);
}
entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries);
res_entries=(MonoPEResourceDirEntry *)(resource_dir+1);
for(i=0; i<entries; i++) {
MonoPEResourceDirEntry *entry=&res_entries[i];
gpointer ret;
ret=mono_image_walk_resource_tree (info, res_id, lang_id,
name, entry, resource_dir,
0);
if(ret!=NULL) {
return(ret);
}
}
return(NULL);
}
/**
* mono_image_get_entry_point:
* \param image the image where the entry point will be looked up.
* Use this routine to determine the metadata token for method that
* has been flagged as the entry point.
* \returns the token for the entry point method in the image
*/
guint32
mono_image_get_entry_point (MonoImage *image)
{
return image->image_info->cli_cli_header.ch_entry_point;
}
/**
* mono_image_get_resource:
* \param image the image where the resource will be looked up.
* \param offset The offset to add to the resource
* \param size a pointer to an int where the size of the resource will be stored
*
* This is a low-level routine that fetches a resource from the
* metadata that starts at a given \p offset. The \p size parameter is
* filled with the data field as encoded in the metadata.
*
* \returns the pointer to the resource whose offset is \p offset.
*/
const char*
mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoCLIHeader *ch = &iinfo->cli_cli_header;
const char* data;
if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size)
return NULL;
data = mono_image_rva_map (image, ch->ch_resources.rva);
if (!data)
return NULL;
data += offset;
if (size)
*size = read32 (data);
data += 4;
return data;
}
// Returning NULL with no error set will be interpeted as "not found"
MonoImage*
mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error)
{
char *base_dir, *name;
MonoImage *res;
MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
const char *fname;
guint32 fname_id;
error_init (error);
if (fileidx < 1 || fileidx > table_info_get_rows (t))
return NULL;
mono_image_lock (image);
if (image->files && image->files [fileidx - 1]) {
mono_image_unlock (image);
return image->files [fileidx - 1];
}
mono_image_unlock (image);
fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME);
fname = mono_metadata_string_heap (image, fname_id);
base_dir = g_path_get_dirname (image->name);
name = g_build_filename (base_dir, fname, (const char*)NULL);
res = mono_image_open (name, NULL);
if (!res)
goto done;
mono_image_lock (image);
if (image->files && image->files [fileidx - 1]) {
MonoImage *old = res;
res = image->files [fileidx - 1];
mono_image_unlock (image);
mono_image_close (old);
} else {
int i;
/* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
if (!assign_assembly_parent_for_netmodule (res, image, error)) {
mono_image_unlock (image);
mono_image_close (res);
return NULL;
}
for (i = 0; i < res->module_count; ++i) {
if (res->modules [i] && !res->modules [i]->assembly)
res->modules [i]->assembly = image->assembly;
}
if (!image->files) {
int n = table_info_get_rows (t);
image->files = g_new0 (MonoImage*, n);
image->file_count = n;
}
image->files [fileidx - 1] = res;
mono_image_unlock (image);
/* vtable fixup can't happen with the image lock held */
#ifdef HOST_WIN32
if (m_image_is_module_handle (res))
mono_image_fixup_vtable (res);
#endif
}
done:
g_free (name);
g_free (base_dir);
return res;
}
/**
* mono_image_load_file_for_image:
*/
MonoImage*
mono_image_load_file_for_image (MonoImage *image, int fileidx)
{
ERROR_DECL (error);
MonoImage *result = mono_image_load_file_for_image_checked (image, fileidx, error);
mono_error_assert_ok (error);
return result;
}
/**
* mono_image_get_strong_name:
* \param image a MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* If the image has a strong name, and \p size is not NULL, the value
* pointed to by size will have the size of the strong name.
*
* \returns NULL if the image does not have a strong name, or a
* pointer to the public key.
*/
const char*
mono_image_get_strong_name (MonoImage *image, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
const char* data;
if (!de->size || !de->rva)
return NULL;
data = mono_image_rva_map (image, de->rva);
if (!data)
return NULL;
if (size)
*size = de->size;
return data;
}
/**
* mono_image_strong_name_position:
* \param image a \c MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* If the image has a strong name, and \p size is not NULL, the value
* pointed to by size will have the size of the strong name.
*
* \returns the position within the image file where the strong name
* is stored.
*/
guint32
mono_image_strong_name_position (MonoImage *image, guint32 *size)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name;
guint32 pos;
if (size)
*size = de->size;
if (!de->size || !de->rva)
return 0;
pos = mono_cli_rva_image_map (image, de->rva);
return pos == INVALID_ADDRESS ? 0 : pos;
}
/**
* mono_image_get_public_key:
* \param image a \c MonoImage
* \param size a \c guint32 pointer, or NULL.
*
* This is used to obtain the public key in the \p image.
*
* If the image has a public key, and \p size is not NULL, the value
* pointed to by size will have the size of the public key.
*
* \returns NULL if the image does not have a public key, or a pointer
* to the public key.
*/
const char*
mono_image_get_public_key (MonoImage *image, guint32 *size)
{
const char *pubkey;
guint32 len, tok;
if (image_is_dynamic (image)) {
if (size)
*size = ((MonoDynamicImage*)image)->public_key_len;
return (char*)((MonoDynamicImage*)image)->public_key;
}
if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY]) != 1)
return NULL;
tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY);
if (!tok)
return NULL;
pubkey = mono_metadata_blob_heap (image, tok);
len = mono_metadata_decode_blob_size (pubkey, &pubkey);
if (size)
*size = len;
return pubkey;
}
/**
* mono_image_get_name:
* \param name a \c MonoImage
* \returns the name of the assembly.
*/
const char*
mono_image_get_name (MonoImage *image)
{
return image->assembly_name;
}
/**
* mono_image_get_filename:
* \param image a \c MonoImage
* Used to get the filename that hold the actual \c MonoImage
* \returns the filename.
*/
const char*
mono_image_get_filename (MonoImage *image)
{
return image->name;
}
/**
* mono_image_get_guid:
*/
const char*
mono_image_get_guid (MonoImage *image)
{
return image->guid;
}
/**
* mono_image_get_table_info:
*/
const MonoTableInfo*
mono_image_get_table_info (MonoImage *image, int table_id)
{
if (table_id < 0 || table_id >= MONO_TABLE_NUM)
return NULL;
return &image->tables [table_id];
}
/**
* mono_image_get_table_rows:
*/
int
mono_image_get_table_rows (MonoImage *image, int table_id)
{
if (table_id < 0 || table_id >= MONO_TABLE_NUM)
return 0;
return table_info_get_rows (&image->tables [table_id]);
}
/**
* mono_table_info_get_rows:
*/
int
mono_table_info_get_rows (const MonoTableInfo *table)
{
return table_info_get_rows (table);
}
/**
* mono_image_get_assembly:
* \param image the \c MonoImage .
* Use this routine to get the assembly that owns this image.
* \returns the assembly that holds this image.
*/
MonoAssembly*
mono_image_get_assembly (MonoImage *image)
{
return image->assembly;
}
/**
* mono_image_is_dynamic:
* \param image the \c MonoImage
*
* Determines if the given image was created dynamically through the
* \c System.Reflection.Emit API
* \returns TRUE if the image was created dynamically, FALSE if not.
*/
gboolean
mono_image_is_dynamic (MonoImage *image)
{
return image_is_dynamic (image);
}
/**
* mono_image_has_authenticode_entry:
* \param image the \c MonoImage
* Use this routine to determine if the image has a Authenticode
* Certificate Table.
* \returns TRUE if the image contains an authenticode entry in the PE
* directory.
*/
gboolean
mono_image_has_authenticode_entry (MonoImage *image)
{
MonoCLIImageInfo *iinfo = image->image_info;
MonoDotNetHeader *header = &iinfo->cli_header;
if (!header)
return FALSE;
MonoPEDirEntry *de = &header->datadir.pe_certificate_table;
// the Authenticode "pre" (non ASN.1) header is 8 bytes long
return ((de->rva != 0) && (de->size > 8));
}
gpointer
mono_image_alloc (MonoImage *image, guint size)
{
gpointer res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
#endif
mono_image_lock (image);
res = mono_mempool_alloc (image->mempool, size);
mono_image_unlock (image);
return res;
}
gpointer
mono_image_alloc0 (MonoImage *image, guint size)
{
gpointer res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
#endif
mono_image_lock (image);
res = mono_mempool_alloc0 (image->mempool, size);
mono_image_unlock (image);
return res;
}
char*
mono_image_strdup (MonoImage *image, const char *s)
{
char *res;
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (s));
#endif
mono_image_lock (image);
res = mono_mempool_strdup (image->mempool, s);
mono_image_unlock (image);
return res;
}
char*
mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args)
{
char *buf;
mono_image_lock (image);
buf = mono_mempool_strdup_vprintf (image->mempool, format, args);
mono_image_unlock (image);
#ifndef DISABLE_PERFCOUNTERS
mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (buf));
#endif
return buf;
}
char*
mono_image_strdup_printf (MonoImage *image, const char *format, ...)
{
char *buf;
va_list args;
va_start (args, format);
buf = mono_image_strdup_vprintf (image, format, args);
va_end (args);
return buf;
}
GList*
mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
{
GList *new_list;
new_list = (GList *)mono_image_alloc (image, sizeof (GList));
new_list->data = data;
new_list->prev = list ? list->prev : NULL;
new_list->next = list;
if (new_list->prev)
new_list->prev->next = new_list;
if (list)
list->prev = new_list;
return new_list;
}
GSList*
mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data)
{
GSList *new_list;
new_list = (GSList *)mono_image_alloc (image, sizeof (GSList));
new_list->data = data;
new_list->next = NULL;
return g_slist_concat (list, new_list);
}
void
mono_image_lock (MonoImage *image)
{
mono_locks_os_acquire (&image->lock, ImageDataLock);
}
void
mono_image_unlock (MonoImage *image)
{
mono_locks_os_release (&image->lock, ImageDataLock);
}
/**
* mono_image_property_lookup:
* Lookup a property on \p image . Used to store very rare fields of \c MonoClass and \c MonoMethod .
*
* LOCKING: Takes the image lock
*/
gpointer
mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property)
{
gpointer res;
mono_image_lock (image);
res = mono_property_hash_lookup (image->property_hash, subject, property);
mono_image_unlock (image);
return res;
}
/**
* mono_image_property_insert:
* Insert a new property \p property with value \p value on \p subject in \p
* image. Used to store very rare fields of \c MonoClass and \c MonoMethod.
*
* LOCKING: Takes the image lock
*/
void
mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
{
CHECKED_METADATA_STORE_LOCAL (image->mempool, value);
mono_image_lock (image);
mono_property_hash_insert (image->property_hash, subject, property, value);
mono_image_unlock (image);
}
/**
* mono_image_property_remove:
* Remove all properties associated with \p subject in \p image. Used to store very rare fields of \c MonoClass and \c MonoMethod .
*
* LOCKING: Takes the image lock
*/
void
mono_image_property_remove (MonoImage *image, gpointer subject)
{
mono_image_lock (image);
mono_property_hash_remove_object (image->property_hash, subject);
mono_image_unlock (image);
}
void
mono_image_append_class_to_reflection_info_set (MonoClass *klass)
{
MonoImage *image = m_class_get_image (klass);
g_assert (image_is_dynamic (image));
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, klass);
mono_image_unlock (image);
}
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/metadata-internals.h | /**
* \file
*/
#ifndef __MONO_METADATA_INTERNALS_H__
#define __MONO_METADATA_INTERNALS_H__
#include "mono/utils/mono-forward-internal.h"
#include "mono/metadata/image.h"
#include "mono/metadata/blob.h"
#include "mono/metadata/cil-coff.h"
#include "mono/metadata/mempool.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/mono-hash.h"
#include "mono/utils/mono-compiler.h"
#include "mono/utils/mono-dl.h"
#include "mono/utils/monobitset.h"
#include "mono/utils/mono-property-hash.h"
#include "mono/utils/mono-value-hash.h"
#include <mono/utils/mono-error.h>
#include "mono/utils/mono-conc-hashtable.h"
#include "mono/utils/refcount.h"
struct _MonoType {
union {
MonoClass *klass; /* for VALUETYPE and CLASS */
MonoType *type; /* for PTR */
MonoArrayType *array; /* for ARRAY */
MonoMethodSignature *method;
MonoGenericParam *generic_param; /* for VAR and MVAR */
MonoGenericClass *generic_class; /* for GENERICINST */
} data;
unsigned int attrs : 16; /* param attributes or field flags */
MonoTypeEnum type : 8;
unsigned int has_cmods : 1;
unsigned int byref__ : 1; /* don't access directly, use m_type_is_byref */
unsigned int pinned : 1; /* valid when included in a local var signature */
};
typedef struct {
unsigned int required : 1;
MonoType *type;
} MonoSingleCustomMod;
/* Aggregate custom modifiers can happen if a generic VAR or MVAR is inflated,
* and both the VAR and the type that will be used to inflated it have custom
* modifiers, but they come from different images. (e.g. inflating 'class G<T>
* {void Test (T modopt(IsConst) t);}' with 'int32 modopt(IsLong)' where G is
* in image1 and the int32 is in image2.)
*
* Moreover, we can't just store an image and a type token per modifier, because
* Roslyn and C++/CLI sometimes create modifiers that mention generic parameters that must be inflated, like:
* void .CL1`1.Test(!0 modopt(System.Nullable`1<!0>))
* So we have to store a resolved MonoType*.
*
* Because the types come from different images, we allocate the aggregate
* custom modifiers container object in the mempool of a MonoImageSet to ensure
* that it doesn't have dangling image pointers.
*/
typedef struct {
uint8_t count;
MonoSingleCustomMod modifiers[1]; /* Actual length is count */
} MonoAggregateModContainer;
/* ECMA says upto 64 custom modifiers. It's possible we could see more at
* runtime due to modifiers being appended together when we inflate type. In
* that case we should revisit the places where this define is used to make
* sure that we don't blow up the stack (or switch to heap allocation for
* temporaries).
*/
#define MONO_MAX_EXPECTED_CMODS 64
typedef struct {
MonoType unmodified;
gboolean is_aggregate;
union {
MonoCustomModContainer cmods;
/* the actual aggregate modifiers are in a MonoImageSet mempool
* that includes all the images of all the modifier types and
* also the type that this aggregate container is a part of.*/
MonoAggregateModContainer *amods;
} mods;
} MonoTypeWithModifiers;
gboolean
mono_type_is_aggregate_mods (const MonoType *t);
static inline void
mono_type_with_mods_init (MonoType *dest, uint8_t num_mods, gboolean is_aggregate)
{
if (num_mods == 0) {
dest->has_cmods = 0;
return;
}
dest->has_cmods = 1;
MonoTypeWithModifiers *dest_full = (MonoTypeWithModifiers *)dest;
dest_full->is_aggregate = !!is_aggregate;
if (is_aggregate)
dest_full->mods.amods = NULL;
else
dest_full->mods.cmods.count = num_mods;
}
MonoCustomModContainer *
mono_type_get_cmods (const MonoType *t);
MonoAggregateModContainer *
mono_type_get_amods (const MonoType *t);
void
mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods);
static inline uint8_t
mono_type_custom_modifier_count (const MonoType *t)
{
if (!t->has_cmods)
return 0;
MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t;
if (full->is_aggregate)
return full->mods.amods->count;
else
return full->mods.cmods.count;
}
MonoType *
mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error);
// Note: sizeof (MonoType) is dangerous. It can copy the num_mods
// field without copying the variably sized array. This leads to
// memory unsafety on the stack and/or heap, when we try to traverse
// this array.
//
// Use mono_sizeof_monotype
// to get the size of the memory to copy.
#define MONO_SIZEOF_TYPE sizeof (MonoType)
size_t
mono_sizeof_type_with_mods (uint8_t num_mods, gboolean aggregate);
size_t
mono_sizeof_type (const MonoType *ty);
size_t
mono_sizeof_aggregate_modifiers (uint8_t num_mods);
MonoAggregateModContainer *
mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate);
#define MONO_PUBLIC_KEY_TOKEN_LENGTH 17
#define MONO_PROCESSOR_ARCHITECTURE_NONE 0
#define MONO_PROCESSOR_ARCHITECTURE_MSIL 1
#define MONO_PROCESSOR_ARCHITECTURE_X86 2
#define MONO_PROCESSOR_ARCHITECTURE_IA64 3
#define MONO_PROCESSOR_ARCHITECTURE_AMD64 4
#define MONO_PROCESSOR_ARCHITECTURE_ARM 5
struct _MonoAssemblyName {
const char *name;
const char *culture;
const char *hash_value;
const mono_byte* public_key;
// string of 16 hex chars + 1 NULL
mono_byte public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH];
uint32_t hash_alg;
uint32_t hash_len;
uint32_t flags;
int32_t major, minor, build, revision, arch;
//Add members for correct work with mono_stringify_assembly_name
MonoBoolean without_version;
MonoBoolean without_culture;
MonoBoolean without_public_key_token;
};
struct MonoTypeNameParse {
char *name_space;
char *name;
MonoAssemblyName assembly;
GList *modifiers; /* 0 -> byref, -1 -> pointer, > 0 -> array rank */
GPtrArray *type_arguments;
GList *nested;
};
typedef struct _MonoAssemblyContext {
/* Don't fire managed load event for this assembly */
guint8 no_managed_load_event : 1;
} MonoAssemblyContext;
struct _MonoAssembly {
/*
* The number of appdomains which have this assembly loaded plus the number of
* assemblies referencing this assembly through an entry in their image->references
* arrays. The latter is needed because entries in the image->references array
* might point to assemblies which are only loaded in some appdomains, and without
* the additional reference, they can be freed at any time.
* The ref_count is initially 0.
*/
gint32 ref_count; /* use atomic operations only */
char *basedir;
MonoAssemblyName aname;
MonoImage *image;
GSList *friend_assembly_names; /* Computed by mono_assembly_load_friends () */
GSList *ignores_checks_assembly_names; /* Computed by mono_assembly_load_friends () */
guint8 friend_assembly_names_inited;
guint8 dynamic;
MonoAssemblyContext context;
guint8 wrap_non_exception_throws;
guint8 wrap_non_exception_throws_inited;
guint8 jit_optimizer_disabled;
guint8 jit_optimizer_disabled_inited;
guint8 runtime_marshalling_enabled;
guint8 runtime_marshalling_enabled_inited;
};
typedef struct {
const char* data;
guint32 size;
} MonoStreamHeader;
struct _MonoTableInfo {
const char *base;
guint rows_ : 24; /* don't access directly, use table_info_get_rows */
guint row_size : 8;
/*
* Tables contain up to 9 columns and the possible sizes of the
* fields in the documentation are 1, 2 and 4 bytes. So we
* can encode in 2 bits the size.
*
* A 32 bit value can encode the resulting size
*
* The top eight bits encode the number of columns in the table.
* we only need 4, but 8 is aligned no shift required.
*/
guint32 size_bitfield;
};
#define REFERENCE_MISSING ((gpointer) -1)
typedef struct {
gboolean (*match) (MonoImage*);
gboolean (*load_pe_data) (MonoImage*);
gboolean (*load_cli_data) (MonoImage*);
gboolean (*load_tables) (MonoImage*);
} MonoImageLoader;
/* Represents the physical bytes for an image (usually in the file system, but
* could be in memory).
*
* The MonoImageStorage owns the raw data for an image and is responsible for
* cleanup.
*
* May be shared by multiple MonoImage objects if they opened the same
* underlying file or byte blob in memory.
*
* There is an abstract string key (usually a file path, but could be formed in
* other ways) that is used to share MonoImageStorage objects among images.
*
*/
typedef struct {
MonoRefCount ref;
/* key used for lookups. owned by this image storage. */
char *key;
/* If the raw data was allocated from a source such as mmap, the allocator may store resource tracking information here. */
void *raw_data_handle;
char *raw_data;
guint32 raw_data_len;
/* data was allocated with mono_file_map and must be unmapped */
guint8 raw_buffer_used : 1;
/* data was allocated with malloc and must be freed */
guint8 raw_data_allocated : 1;
/* data was allocated with mono_file_map_fileio */
guint8 fileio_used : 1;
#ifdef HOST_WIN32
/* Module was loaded using LoadLibrary. */
guint8 is_module_handle : 1;
/* Module entry point is _CorDllMain. */
guint8 has_entry_point : 1;
#endif
} MonoImageStorage;
struct _MonoImage {
/*
* This count is incremented during these situations:
* - An assembly references this MonoImage through its 'image' field
* - This MonoImage is present in the 'files' field of an image
* - This MonoImage is present in the 'modules' field of an image
* - A thread is holding a temporary reference to this MonoImage between
* calls to mono_image_open and mono_image_close ()
*/
int ref_count;
MonoImageStorage *storage;
/* Aliases storage->raw_data when storage is non-NULL. Otherwise NULL. */
char *raw_data;
guint32 raw_data_len;
/* Whenever this is a dynamically emitted module */
guint8 dynamic : 1;
/* Whenever this image contains uncompressed metadata */
guint8 uncompressed_metadata : 1;
/* Whenever this image contains metadata only without PE data */
guint8 metadata_only : 1;
guint8 checked_module_cctor : 1;
guint8 has_module_cctor : 1;
guint8 idx_string_wide : 1;
guint8 idx_guid_wide : 1;
guint8 idx_blob_wide : 1;
/* NOT SUPPORTED: Whenever this image is considered as platform code for the CoreCLR security model */
guint8 core_clr_platform_code : 1;
/* Whether a #JTD stream was present. Indicates that this image was a minimal delta and its heaps only include the new heap entries */
guint8 minimal_delta : 1;
/* The path to the file for this image or an arbitrary name for images loaded from data. */
char *name;
/* The path to the file for this image or NULL */
char *filename;
/* The assembly name reported in the file for this image (expected to be NULL for a netmodule) */
const char *assembly_name;
/* The module name reported in the file for this image (could be NULL for a malformed file) */
const char *module_name;
guint32 time_date_stamp;
char *version;
gint16 md_version_major, md_version_minor;
char *guid;
MonoCLIImageInfo *image_info;
MonoMemPool *mempool; /*protected by the image lock*/
char *raw_metadata;
MonoStreamHeader heap_strings;
MonoStreamHeader heap_us;
MonoStreamHeader heap_blob;
MonoStreamHeader heap_guid;
MonoStreamHeader heap_tables;
MonoStreamHeader heap_pdb;
const char *tables_base;
/* For PPDB files */
guint64 referenced_tables;
int *referenced_table_rows;
/**/
MonoTableInfo tables [MONO_TABLE_NUM];
/*
* references is initialized only by using the mono_assembly_open
* function, and not by using the lowlevel mono_image_open.
*
* Protected by the image lock.
*
* It is NULL terminated.
*/
MonoAssembly **references;
int nreferences;
/* Code files in the assembly. The main assembly has a "file" table and also a "module"
* table, where the module table is a subset of the file table. We track both lists,
* and because we can lazy-load them at different times we reference-increment both.
*/
/* No netmodules in netcore, but for System.Reflection.Emit support we still use modules */
MonoImage **modules;
guint32 module_count;
gboolean *modules_loaded;
MonoImage **files;
guint32 file_count;
MonoAotModule *aot_module;
guint8 aotid[16];
/*
* The Assembly this image was loaded from.
*/
MonoAssembly *assembly;
/*
* The AssemblyLoadContext that this image was loaded into.
*/
MonoAssemblyLoadContext *alc;
/*
* Indexed by method tokens and typedef tokens.
*/
GHashTable *method_cache; /*protected by the image lock*/
MonoInternalHashTable class_cache;
/* Indexed by memberref + methodspec tokens */
GHashTable *methodref_cache; /*protected by the image lock*/
/*
* Indexed by fielddef and memberref tokens
*/
MonoConcurrentHashTable *field_cache; /*protected by the image lock*/
/* indexed by typespec tokens. */
MonoConcurrentHashTable *typespec_cache; /* protected by the image lock */
/* indexed by token */
GHashTable *memberref_signatures;
/* Indexed by blob heap indexes */
GHashTable *method_signatures;
/*
* Indexes namespaces to hash tables that map class name to typedef token.
*/
GHashTable *name_cache; /*protected by the image lock*/
/*
* Indexed by MonoClass
*/
GHashTable *array_cache;
GHashTable *ptr_cache;
GHashTable *szarray_cache;
/* This has a separate lock to improve scalability */
mono_mutex_t szarray_cache_lock;
/*
* indexed by SignaturePointerPair
*/
GHashTable *native_func_wrapper_cache;
/*
* indexed by MonoMethod pointers
*/
GHashTable *wrapper_param_names;
GHashTable *array_accessor_cache;
GHashTable *icall_wrapper_cache;
GHashTable *rgctx_template_hash; /* LOCKING: templates lock */
/* Contains rarely used fields of runtime structures belonging to this image */
MonoPropertyHash *property_hash;
void *reflection_info;
/*
* user_info is a public field and is not touched by the
* metadata engine
*/
void *user_info;
#ifndef DISABLE_DLLMAP
/* dll map entries */
MonoDllMap *dll_map;
#endif
/* interfaces IDs from this image */
/* protected by the classes lock */
MonoBitSet *interface_bitset;
/* when the image is being closed, this is abused as a list of
malloc'ed regions to be freed. */
GSList *reflection_info_unregister_classes;
/* List of dependent image sets containing this image */
/* Protected by image_sets_lock */
GSList *image_sets;
/* Caches for wrappers that DO NOT reference generic */
/* arguments */
MonoWrapperCaches wrapper_caches;
/* Pre-allocated anon generic params for the first N generic
* parameters, for a small N */
MonoGenericParam *var_gparam_cache_fast;
MonoGenericParam *mvar_gparam_cache_fast;
/* Anon generic parameters past N, if needed */
MonoConcurrentHashTable *var_gparam_cache;
MonoConcurrentHashTable *mvar_gparam_cache;
/* The loader used to load this image */
MonoImageLoader *loader;
// Containers for MonoGenericParams associated with this image but not with any specific class or method. Created on demand.
// This could happen, for example, for MonoTypes associated with TypeSpec table entries.
MonoGenericContainer *anonymous_generic_class_container;
MonoGenericContainer *anonymous_generic_method_container;
gboolean weak_fields_inited;
/* Contains 1 based indexes */
GHashTable *weak_field_indexes;
/* baseline images only: whether any metadata updates have been applied to this image */
gboolean has_updates;
/*
* No other runtime locks must be taken while holding this lock.
* It's meant to be used only to mutate and query structures part of this image.
*/
mono_mutex_t lock;
};
enum {
MONO_SECTION_TEXT,
MONO_SECTION_RSRC,
MONO_SECTION_RELOC,
MONO_SECTION_MAX
};
typedef struct {
GHashTable *hash;
char *data;
guint32 alloc_size; /* malloced bytes */
guint32 index;
guint32 offset; /* from start of metadata */
} MonoDynamicStream;
typedef struct {
guint32 alloc_rows;
guint32 rows;
guint8 row_size; /* calculated later with column_sizes */
guint8 columns;
guint32 next_idx;
guint32 *values; /* rows * columns */
} MonoDynamicTable;
/* "Dynamic" assemblies and images arise from System.Reflection.Emit */
struct _MonoDynamicAssembly {
MonoAssembly assembly;
char *strong_name;
guint32 strong_name_size;
};
struct _MonoDynamicImage {
MonoImage image;
guint32 meta_size;
guint32 text_rva;
guint32 metadata_rva;
guint32 image_base;
guint32 cli_header_offset;
guint32 iat_offset;
guint32 idt_offset;
guint32 ilt_offset;
guint32 imp_names_offset;
struct {
guint32 rva;
guint32 size;
guint32 offset;
guint32 attrs;
} sections [MONO_SECTION_MAX];
GHashTable *typespec;
GHashTable *typeref;
GHashTable *handleref;
MonoGHashTable *tokens;
GHashTable *blob_cache;
GHashTable *standalonesig_cache;
GList *array_methods;
GHashTable *method_aux_hash;
GHashTable *vararg_aux_hash;
MonoGHashTable *generic_def_objects;
gboolean initial_image;
guint32 pe_kind, machine;
char *strong_name;
guint32 strong_name_size;
char *win32_res;
guint32 win32_res_size;
guint8 *public_key;
int public_key_len;
MonoDynamicStream sheap;
MonoDynamicStream code; /* used to store method headers and bytecode */
MonoDynamicStream resources; /* managed embedded resources */
MonoDynamicStream us;
MonoDynamicStream blob;
MonoDynamicStream tstream;
MonoDynamicStream guid;
MonoDynamicTable tables [MONO_TABLE_NUM];
MonoClass *wrappers_type; /*wrappers are bound to this type instead of <Module>*/
};
/* Contains information about assembly binding */
typedef struct _MonoAssemblyBindingInfo {
char *name;
char *culture;
guchar public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH];
int major;
int minor;
AssemblyVersionSet old_version_bottom;
AssemblyVersionSet old_version_top;
AssemblyVersionSet new_version;
guint has_old_version_bottom : 1;
guint has_old_version_top : 1;
guint has_new_version : 1;
guint is_valid : 1;
gint32 domain_id; /*Needed to unload per-domain binding*/
} MonoAssemblyBindingInfo;
struct _MonoMethodHeader {
const unsigned char *code;
#ifdef MONO_SMALL_CONFIG
guint16 code_size;
#else
guint32 code_size;
#endif
guint16 max_stack : 15;
unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */
unsigned int num_clauses : 15;
/* if num_locals != 0, then the following apply: */
unsigned int init_locals : 1;
guint16 num_locals;
MonoExceptionClause *clauses;
MonoBitSet *volatile_args;
MonoBitSet *volatile_locals;
MonoType *locals [MONO_ZERO_LEN_ARRAY];
};
typedef struct {
const unsigned char *code;
guint32 code_size;
guint16 max_stack;
gboolean has_clauses;
gboolean has_locals;
} MonoMethodHeaderSummary;
// FIXME? offsetof (MonoMethodHeader, locals)?
#define MONO_SIZEOF_METHOD_HEADER (sizeof (struct _MonoMethodHeader) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
struct _MonoMethodSignature {
MonoType *ret;
#ifdef MONO_SMALL_CONFIG
guint8 param_count;
gint8 sentinelpos;
unsigned int generic_param_count : 5;
#else
guint16 param_count;
gint16 sentinelpos;
unsigned int generic_param_count : 16;
#endif
unsigned int call_convention : 6;
unsigned int hasthis : 1;
unsigned int explicit_this : 1;
unsigned int pinvoke : 1;
unsigned int is_inflated : 1;
unsigned int has_type_parameters : 1;
unsigned int suppress_gc_transition : 1;
unsigned int marshalling_disabled : 1;
MonoType *params [MONO_ZERO_LEN_ARRAY];
};
/*
* AOT cache configuration loaded from config files.
* Doesn't really belong here.
*/
typedef struct {
/*
* Enable aot caching for applications whose main assemblies are in
* this list.
*/
GSList *apps;
GSList *assemblies;
char *aot_options;
} MonoAotCacheConfig;
#define MONO_SIZEOF_METHOD_SIGNATURE (sizeof (struct _MonoMethodSignature) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
static inline gboolean
image_is_dynamic (MonoImage *image)
{
#ifdef DISABLE_REFLECTION_EMIT
return FALSE;
#else
return image->dynamic;
#endif
}
static inline gboolean
assembly_is_dynamic (MonoAssembly *assembly)
{
#ifdef DISABLE_REFLECTION_EMIT
return FALSE;
#else
return assembly->dynamic;
#endif
}
static inline int
table_info_get_rows (const MonoTableInfo *table)
{
return table->rows_;
}
/* for use with allocated memory blocks (assumes alignment is to 8 bytes) */
MONO_COMPONENT_API guint mono_aligned_addr_hash (gconstpointer ptr);
void
mono_image_check_for_module_cctor (MonoImage *image);
gpointer
mono_image_alloc (MonoImage *image, guint size);
gpointer
mono_image_alloc0 (MonoImage *image, guint size);
#define mono_image_new0(image,type,size) ((type *) mono_image_alloc0 (image, sizeof (type)* (size)))
char*
mono_image_strdup (MonoImage *image, const char *s);
char*
mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args);
char*
mono_image_strdup_printf (MonoImage *image, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
GList*
mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data);
GSList*
mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data);
MONO_COMPONENT_API
void
mono_image_lock (MonoImage *image);
MONO_COMPONENT_API
void
mono_image_unlock (MonoImage *image);
gpointer
mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property);
void
mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value);
void
mono_image_property_remove (MonoImage *image, gpointer subject);
MONO_COMPONENT_API
gboolean
mono_image_close_except_pools (MonoImage *image);
MONO_COMPONENT_API
void
mono_image_close_finish (MonoImage *image);
typedef void (*MonoImageUnloadFunc) (MonoImage *image, gpointer user_data);
void
mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data);
void
mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data);
void
mono_install_image_loader (const MonoImageLoader *loader);
void
mono_image_append_class_to_reflection_info_set (MonoClass *klass);
typedef struct _MonoMetadataUpdateData MonoMetadataUpdateData;
struct _MonoMetadataUpdateData {
int has_updates;
};
extern MonoMetadataUpdateData mono_metadata_update_data_private;
/* returns TRUE if there's at least one update */
static inline gboolean
mono_metadata_has_updates (void)
{
return mono_metadata_update_data_private.has_updates != 0;
}
/* components can't call the inline function directly since the private data isn't exported */
MONO_COMPONENT_API
gboolean
mono_metadata_has_updates_api (void);
void
mono_image_effective_table_slow (const MonoTableInfo **t, int idx);
gboolean
mono_metadata_update_has_modified_rows (const MonoTableInfo *t);
static inline void
mono_image_effective_table (const MonoTableInfo **t, int idx)
{
if (G_UNLIKELY (mono_metadata_has_updates ())) {
if (G_UNLIKELY (idx >= table_info_get_rows ((*t)) || mono_metadata_update_has_modified_rows (*t))) {
mono_image_effective_table_slow (t, idx);
}
}
}
enum MonoEnCDeltaOrigin {
MONO_ENC_DELTA_API = 0,
MONO_ENC_DELTA_DBG = 1,
};
MONO_COMPONENT_API void
mono_image_load_enc_delta (int delta_origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb, uint32_t dpdb_len, MonoError *error);
gboolean
mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo);
gboolean
mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo);
const char*
mono_metadata_string_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error);
const char *
mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index);
const char*
mono_metadata_blob_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error);
gboolean
mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, uint32_t *res, int res_size, MonoError *error);
MONO_COMPONENT_API
void
mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, uint32_t *res, int res_size);
gboolean
mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error);
MonoType*
mono_metadata_get_shared_type (MonoType *type);
void
mono_metadata_clean_generic_classes_for_image (MonoImage *image);
gboolean
mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index);
int
mono_metadata_table_num_rows_slow (MonoImage *image, int table_index);
static inline int
mono_metadata_table_num_rows (MonoImage *image, int table_index)
{
if (G_LIKELY (!image->has_updates))
return table_info_get_rows (&image->tables [table_index]);
else
return mono_metadata_table_num_rows_slow (image, table_index);
}
/* token_index is 1-based */
static inline gboolean
mono_metadata_table_bounds_check (MonoImage *image, int table_index, int token_index)
{
/* returns true if given index is not in bounds with provided table/index pair */
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_table_bounds_check_slow (image, table_index, token_index);
}
MONO_COMPONENT_API
const char * mono_meta_table_name (int table);
void mono_metadata_compute_table_bases (MonoImage *meta);
gboolean
mono_metadata_interfaces_from_typedef_full (MonoImage *image,
guint32 table_index,
MonoClass ***interfaces,
guint *count,
gboolean heap_alloc_result,
MonoGenericContext *context,
MonoError *error);
MONO_API MonoMethodSignature *
mono_metadata_parse_method_signature_full (MonoImage *image,
MonoGenericContainer *generic_container,
int def,
const char *ptr,
const char **rptr,
MonoError *error);
MONO_API MonoMethodHeader *
mono_metadata_parse_mh_full (MonoImage *image,
MonoGenericContainer *container,
const char *ptr,
MonoError *error);
MonoMethodSignature *mono_metadata_parse_signature_checked (MonoImage *image,
uint32_t token,
MonoError *error);
gboolean
mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary);
int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count);
gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def);
guint
mono_metadata_generic_context_hash (const MonoGenericContext *context);
gboolean
mono_metadata_generic_context_equal (const MonoGenericContext *g1,
const MonoGenericContext *g2);
MonoGenericInst *
mono_metadata_parse_generic_inst (MonoImage *image,
MonoGenericContainer *container,
int count,
const char *ptr,
const char **rptr,
MonoError *error);
MONO_COMPONENT_API MonoGenericInst *
mono_metadata_get_generic_inst (int type_argc,
MonoType **type_argv);
MonoGenericInst *
mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate);
MonoGenericClass *
mono_metadata_lookup_generic_class (MonoClass *gclass,
MonoGenericInst *inst,
gboolean is_dynamic);
MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error);
guint
mono_metadata_generic_param_hash (MonoGenericParam *p);
gboolean
mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2);
void mono_dynamic_stream_reset (MonoDynamicStream* stream);
void mono_assembly_load_friends (MonoAssembly* ass);
MONO_API gint32
mono_assembly_addref (MonoAssembly *assembly);
gint32
mono_assembly_decref (MonoAssembly *assembly);
void mono_assembly_release_gc_roots (MonoAssembly *assembly);
gboolean mono_assembly_close_except_image_pools (MonoAssembly *assembly);
void mono_assembly_close_finish (MonoAssembly *assembly);
gboolean mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *pubt2);
void mono_config_parse_publisher_policy (const char *filename, MonoAssemblyBindingInfo *binding_info);
gboolean
mono_assembly_name_parse_full (const char *name,
MonoAssemblyName *aname,
gboolean save_public_key,
gboolean *is_version_defined,
gboolean *is_token_defined);
gboolean
mono_assembly_fill_assembly_name_full (MonoImage *image, MonoAssemblyName *aname, gboolean copyBlobs);
MONO_API guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner);
MonoGenericParam*
mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar);
void mono_unload_interface_ids (MonoBitSet *bitset);
MonoType *mono_metadata_type_dup (MonoImage *image, const MonoType *original);
MonoType *mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *original, const MonoType *cmods_source);
MonoMethodSignature *mono_metadata_signature_dup_full (MonoImage *image,MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass);
MonoGenericInst *
mono_get_shared_generic_inst (MonoGenericContainer *container);
int
mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open);
MONO_API void mono_type_get_desc (GString *res, MonoType *type, mono_bool include_namespace);
gboolean
mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only);
MonoMarshalSpec *
mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr);
guint mono_metadata_generic_inst_hash (gconstpointer data);
gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb);
gboolean
mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2);
MONO_API void
mono_metadata_field_info_with_mempool (
MonoImage *meta,
guint32 table_index,
guint32 *offset,
guint32 *rva,
MonoMarshalSpec **marshal_spec);
MonoClassField*
mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field);
MonoEvent*
mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event);
MonoProperty*
mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property);
guint32
mono_metadata_signature_size (MonoMethodSignature *sig);
guint mono_metadata_str_hash (gconstpointer v1);
gboolean mono_image_load_pe_data (MonoImage *image);
gboolean mono_image_load_cli_data (MonoImage *image);
void mono_image_load_names (MonoImage *image);
MonoImage *mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
MonoImage *mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
MONO_COMPONENT_API
MonoImage *mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename);
MonoException *mono_get_exception_field_access_msg (const char *msg);
MonoException *mono_get_exception_method_access_msg (const char *msg);
MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error);
MonoMethod *mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error);
MonoMethod *mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error);
void mono_type_set_alignment (MonoTypeEnum type, int align);
MonoType *
mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error);
MonoMethodSignature*
mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error);
MONO_COMPONENT_API MonoMethod *
mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error);
guint32
mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index);
void
mono_wrapper_caches_free (MonoWrapperCaches *cache);
MonoWrapperCaches*
mono_method_get_wrapper_cache (MonoMethod *method);
MonoWrapperCaches*
mono_method_get_wrapper_cache (MonoMethod *method);
MonoType*
mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error);
MonoGenericContainer *
mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar);
void
mono_loader_register_module (const char *name, MonoDl *module);
void
mono_ginst_get_desc (GString *str, MonoGenericInst *ginst);
void
mono_loader_set_strict_assembly_name_check (gboolean enabled);
gboolean
mono_loader_get_strict_assembly_name_check (void);
MONO_COMPONENT_API gboolean
mono_type_in_image (MonoType *type, MonoImage *image);
gboolean
mono_type_is_valid_generic_argument (MonoType *type);
void
mono_metadata_get_class_guid (MonoClass* klass, uint8_t* guid, MonoError *error);
#define MONO_CLASS_IS_INTERFACE_INTERNAL(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (m_class_get_byval_arg (c)))
static inline gboolean
m_image_is_raw_data_allocated (MonoImage *image)
{
return image->storage ? image->storage->raw_data_allocated : FALSE;
}
static inline gboolean
m_image_is_fileio_used (MonoImage *image)
{
return image->storage ? image->storage->fileio_used : FALSE;
}
#ifdef HOST_WIN32
static inline gboolean
m_image_is_module_handle (MonoImage *image)
{
return image->storage ? image->storage->is_module_handle : FALSE;
}
static inline gboolean
m_image_has_entry_point (MonoImage *image)
{
return image->storage ? image->storage->has_entry_point : FALSE;
}
#endif
static inline const char *
m_image_get_name (MonoImage *image)
{
return image->name;
}
static inline const char *
m_image_get_filename (MonoImage *image)
{
return image->filename;
}
static inline const char *
m_image_get_assembly_name (MonoImage *image)
{
return image->assembly_name;
}
static inline
MonoAssemblyLoadContext *
mono_image_get_alc (MonoImage *image)
{
return image->alc;
}
static inline
MonoAssemblyLoadContext *
mono_assembly_get_alc (MonoAssembly *assm)
{
return mono_image_get_alc (assm->image);
}
static inline MonoType*
mono_signature_get_return_type_internal (MonoMethodSignature *sig)
{
return sig->ret;
}
/**
* mono_type_get_type_internal:
* \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.
*/
static inline int
mono_type_get_type_internal (MonoType *type)
{
return type->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.
*/
static inline MonoMethodSignature*
mono_type_get_signature_internal (MonoType *type)
{
g_assert (type->type == MONO_TYPE_FNPTR);
return type->data.method;
}
/**
* m_type_is_byref:
* \param type the \c MonoType operated on
* \returns TRUE if \p type represents a type passed by reference,
* FALSE otherwise.
*/
static inline gboolean
m_type_is_byref (const MonoType *type)
{
return type->byref__;
}
/**
* mono_type_get_class_internal:
* \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.
*/
static inline MonoClass*
mono_type_get_class_internal (MonoType *type)
{
/* FIXME: review the runtime users before adding the assert here */
return type->data.klass;
}
/**
* mono_type_get_array_type_internal:
* \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.
*/
static inline MonoArrayType*
mono_type_get_array_type_internal (MonoType *type)
{
return type->data.array;
}
static inline int
mono_metadata_table_to_ptr_table (int table_num)
{
switch (table_num) {
case MONO_TABLE_FIELD: return MONO_TABLE_FIELD_POINTER;
case MONO_TABLE_METHOD: return MONO_TABLE_METHOD_POINTER;
case MONO_TABLE_PARAM: return MONO_TABLE_PARAM_POINTER;
case MONO_TABLE_PROPERTY: return MONO_TABLE_PROPERTY_POINTER;
case MONO_TABLE_EVENT: return MONO_TABLE_EVENT_POINTER;
default:
g_assert_not_reached ();
}
}
#endif /* __MONO_METADATA_INTERNALS_H__ */
| /**
* \file
*/
#ifndef __MONO_METADATA_INTERNALS_H__
#define __MONO_METADATA_INTERNALS_H__
#include "mono/utils/mono-forward-internal.h"
#include "mono/metadata/image.h"
#include "mono/metadata/blob.h"
#include "mono/metadata/cil-coff.h"
#include "mono/metadata/mempool.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/mono-hash.h"
#include "mono/utils/mono-compiler.h"
#include "mono/utils/mono-dl.h"
#include "mono/utils/monobitset.h"
#include "mono/utils/mono-property-hash.h"
#include "mono/utils/mono-value-hash.h"
#include <mono/utils/mono-error.h>
#include "mono/utils/mono-conc-hashtable.h"
#include "mono/utils/refcount.h"
struct _MonoType {
union {
MonoClass *klass; /* for VALUETYPE and CLASS */
MonoType *type; /* for PTR */
MonoArrayType *array; /* for ARRAY */
MonoMethodSignature *method;
MonoGenericParam *generic_param; /* for VAR and MVAR */
MonoGenericClass *generic_class; /* for GENERICINST */
} data;
unsigned int attrs : 16; /* param attributes or field flags */
MonoTypeEnum type : 8;
unsigned int has_cmods : 1;
unsigned int byref__ : 1; /* don't access directly, use m_type_is_byref */
unsigned int pinned : 1; /* valid when included in a local var signature */
};
typedef struct {
unsigned int required : 1;
MonoType *type;
} MonoSingleCustomMod;
/* Aggregate custom modifiers can happen if a generic VAR or MVAR is inflated,
* and both the VAR and the type that will be used to inflated it have custom
* modifiers, but they come from different images. (e.g. inflating 'class G<T>
* {void Test (T modopt(IsConst) t);}' with 'int32 modopt(IsLong)' where G is
* in image1 and the int32 is in image2.)
*
* Moreover, we can't just store an image and a type token per modifier, because
* Roslyn and C++/CLI sometimes create modifiers that mention generic parameters that must be inflated, like:
* void .CL1`1.Test(!0 modopt(System.Nullable`1<!0>))
* So we have to store a resolved MonoType*.
*
* Because the types come from different images, we allocate the aggregate
* custom modifiers container object in the mempool of a MonoImageSet to ensure
* that it doesn't have dangling image pointers.
*/
typedef struct {
uint8_t count;
MonoSingleCustomMod modifiers[1]; /* Actual length is count */
} MonoAggregateModContainer;
/* ECMA says upto 64 custom modifiers. It's possible we could see more at
* runtime due to modifiers being appended together when we inflate type. In
* that case we should revisit the places where this define is used to make
* sure that we don't blow up the stack (or switch to heap allocation for
* temporaries).
*/
#define MONO_MAX_EXPECTED_CMODS 64
typedef struct {
MonoType unmodified;
gboolean is_aggregate;
union {
MonoCustomModContainer cmods;
/* the actual aggregate modifiers are in a MonoImageSet mempool
* that includes all the images of all the modifier types and
* also the type that this aggregate container is a part of.*/
MonoAggregateModContainer *amods;
} mods;
} MonoTypeWithModifiers;
gboolean
mono_type_is_aggregate_mods (const MonoType *t);
static inline void
mono_type_with_mods_init (MonoType *dest, uint8_t num_mods, gboolean is_aggregate)
{
if (num_mods == 0) {
dest->has_cmods = 0;
return;
}
dest->has_cmods = 1;
MonoTypeWithModifiers *dest_full = (MonoTypeWithModifiers *)dest;
dest_full->is_aggregate = !!is_aggregate;
if (is_aggregate)
dest_full->mods.amods = NULL;
else
dest_full->mods.cmods.count = num_mods;
}
MonoCustomModContainer *
mono_type_get_cmods (const MonoType *t);
MonoAggregateModContainer *
mono_type_get_amods (const MonoType *t);
void
mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods);
static inline uint8_t
mono_type_custom_modifier_count (const MonoType *t)
{
if (!t->has_cmods)
return 0;
MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t;
if (full->is_aggregate)
return full->mods.amods->count;
else
return full->mods.cmods.count;
}
MonoType *
mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error);
// Note: sizeof (MonoType) is dangerous. It can copy the num_mods
// field without copying the variably sized array. This leads to
// memory unsafety on the stack and/or heap, when we try to traverse
// this array.
//
// Use mono_sizeof_monotype
// to get the size of the memory to copy.
#define MONO_SIZEOF_TYPE sizeof (MonoType)
size_t
mono_sizeof_type_with_mods (uint8_t num_mods, gboolean aggregate);
size_t
mono_sizeof_type (const MonoType *ty);
size_t
mono_sizeof_aggregate_modifiers (uint8_t num_mods);
MonoAggregateModContainer *
mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate);
#define MONO_PUBLIC_KEY_TOKEN_LENGTH 17
#define MONO_PROCESSOR_ARCHITECTURE_NONE 0
#define MONO_PROCESSOR_ARCHITECTURE_MSIL 1
#define MONO_PROCESSOR_ARCHITECTURE_X86 2
#define MONO_PROCESSOR_ARCHITECTURE_IA64 3
#define MONO_PROCESSOR_ARCHITECTURE_AMD64 4
#define MONO_PROCESSOR_ARCHITECTURE_ARM 5
struct _MonoAssemblyName {
const char *name;
const char *culture;
const char *hash_value;
const mono_byte* public_key;
// string of 16 hex chars + 1 NULL
mono_byte public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH];
uint32_t hash_alg;
uint32_t hash_len;
uint32_t flags;
int32_t major, minor, build, revision, arch;
//Add members for correct work with mono_stringify_assembly_name
MonoBoolean without_version;
MonoBoolean without_culture;
MonoBoolean without_public_key_token;
};
struct MonoTypeNameParse {
char *name_space;
char *name;
MonoAssemblyName assembly;
GList *modifiers; /* 0 -> byref, -1 -> pointer, > 0 -> array rank */
GPtrArray *type_arguments;
GList *nested;
};
typedef struct _MonoAssemblyContext {
/* Don't fire managed load event for this assembly */
guint8 no_managed_load_event : 1;
} MonoAssemblyContext;
struct _MonoAssembly {
/*
* The number of appdomains which have this assembly loaded plus the number of
* assemblies referencing this assembly through an entry in their image->references
* arrays. The latter is needed because entries in the image->references array
* might point to assemblies which are only loaded in some appdomains, and without
* the additional reference, they can be freed at any time.
* The ref_count is initially 0.
*/
gint32 ref_count; /* use atomic operations only */
char *basedir;
MonoAssemblyName aname;
MonoImage *image;
GSList *friend_assembly_names; /* Computed by mono_assembly_load_friends () */
GSList *ignores_checks_assembly_names; /* Computed by mono_assembly_load_friends () */
guint8 friend_assembly_names_inited;
guint8 dynamic;
MonoAssemblyContext context;
guint8 wrap_non_exception_throws;
guint8 wrap_non_exception_throws_inited;
guint8 jit_optimizer_disabled;
guint8 jit_optimizer_disabled_inited;
guint8 runtime_marshalling_enabled;
guint8 runtime_marshalling_enabled_inited;
};
typedef struct {
const char* data;
guint32 size;
} MonoStreamHeader;
struct _MonoTableInfo {
const char *base;
guint rows_ : 24; /* don't access directly, use table_info_get_rows */
guint row_size : 8;
/*
* Tables contain up to 9 columns and the possible sizes of the
* fields in the documentation are 1, 2 and 4 bytes. So we
* can encode in 2 bits the size.
*
* A 32 bit value can encode the resulting size
*
* The top eight bits encode the number of columns in the table.
* we only need 4, but 8 is aligned no shift required.
*/
guint32 size_bitfield;
};
#define REFERENCE_MISSING ((gpointer) -1)
typedef struct {
gboolean (*match) (MonoImage*);
gboolean (*load_pe_data) (MonoImage*);
gboolean (*load_cli_data) (MonoImage*);
gboolean (*load_tables) (MonoImage*);
} MonoImageLoader;
/* Represents the physical bytes for an image (usually in the file system, but
* could be in memory).
*
* The MonoImageStorage owns the raw data for an image and is responsible for
* cleanup.
*
* May be shared by multiple MonoImage objects if they opened the same
* underlying file or byte blob in memory.
*
* There is an abstract string key (usually a file path, but could be formed in
* other ways) that is used to share MonoImageStorage objects among images.
*
*/
typedef struct {
MonoRefCount ref;
/* key used for lookups. owned by this image storage. */
char *key;
/* If the raw data was allocated from a source such as mmap, the allocator may store resource tracking information here. */
void *raw_data_handle;
char *raw_data;
guint32 raw_data_len;
/* data was allocated with mono_file_map and must be unmapped */
guint8 raw_buffer_used : 1;
/* data was allocated with malloc and must be freed */
guint8 raw_data_allocated : 1;
/* data was allocated with mono_file_map_fileio */
guint8 fileio_used : 1;
#ifdef HOST_WIN32
/* Module was loaded using LoadLibrary. */
guint8 is_module_handle : 1;
/* Module entry point is _CorDllMain. */
guint8 has_entry_point : 1;
#endif
} MonoImageStorage;
struct _MonoImage {
/*
* This count is incremented during these situations:
* - An assembly references this MonoImage through its 'image' field
* - This MonoImage is present in the 'files' field of an image
* - This MonoImage is present in the 'modules' field of an image
* - A thread is holding a temporary reference to this MonoImage between
* calls to mono_image_open and mono_image_close ()
*/
int ref_count;
MonoImageStorage *storage;
/* Aliases storage->raw_data when storage is non-NULL. Otherwise NULL. */
char *raw_data;
guint32 raw_data_len;
/* Whenever this is a dynamically emitted module */
guint8 dynamic : 1;
/* Whenever this image contains uncompressed metadata */
guint8 uncompressed_metadata : 1;
/* Whenever this image contains metadata only without PE data */
guint8 metadata_only : 1;
guint8 checked_module_cctor : 1;
guint8 has_module_cctor : 1;
guint8 idx_string_wide : 1;
guint8 idx_guid_wide : 1;
guint8 idx_blob_wide : 1;
/* NOT SUPPORTED: Whenever this image is considered as platform code for the CoreCLR security model */
guint8 core_clr_platform_code : 1;
/* Whether a #JTD stream was present. Indicates that this image was a minimal delta and its heaps only include the new heap entries */
guint8 minimal_delta : 1;
/* The path to the file for this image or an arbitrary name for images loaded from data. */
char *name;
/* The path to the file for this image or NULL */
char *filename;
/* The assembly name reported in the file for this image (expected to be NULL for a netmodule) */
const char *assembly_name;
/* The module name reported in the file for this image (could be NULL for a malformed file) */
const char *module_name;
guint32 time_date_stamp;
char *version;
gint16 md_version_major, md_version_minor;
char *guid;
MonoCLIImageInfo *image_info;
MonoMemPool *mempool; /*protected by the image lock*/
char *raw_metadata;
MonoStreamHeader heap_strings;
MonoStreamHeader heap_us;
MonoStreamHeader heap_blob;
MonoStreamHeader heap_guid;
MonoStreamHeader heap_tables;
MonoStreamHeader heap_pdb;
const char *tables_base;
/* For PPDB files */
guint64 referenced_tables;
int *referenced_table_rows;
/**/
MonoTableInfo tables [MONO_TABLE_NUM];
/*
* references is initialized only by using the mono_assembly_open
* function, and not by using the lowlevel mono_image_open.
*
* Protected by the image lock.
*
* It is NULL terminated.
*/
MonoAssembly **references;
int nreferences;
/* Code files in the assembly. The main assembly has a "file" table and also a "module"
* table, where the module table is a subset of the file table. We track both lists,
* and because we can lazy-load them at different times we reference-increment both.
*/
/* No netmodules in netcore, but for System.Reflection.Emit support we still use modules */
MonoImage **modules;
guint32 module_count;
gboolean *modules_loaded;
MonoImage **files;
guint32 file_count;
MonoAotModule *aot_module;
guint8 aotid[16];
/*
* The Assembly this image was loaded from.
*/
MonoAssembly *assembly;
/*
* The AssemblyLoadContext that this image was loaded into.
*/
MonoAssemblyLoadContext *alc;
/*
* Indexed by method tokens and typedef tokens.
*/
GHashTable *method_cache; /*protected by the image lock*/
MonoInternalHashTable class_cache;
/* Indexed by memberref + methodspec tokens */
GHashTable *methodref_cache; /*protected by the image lock*/
/*
* Indexed by fielddef and memberref tokens
*/
MonoConcurrentHashTable *field_cache; /*protected by the image lock*/
/* indexed by typespec tokens. */
MonoConcurrentHashTable *typespec_cache; /* protected by the image lock */
/* indexed by token */
GHashTable *memberref_signatures;
/* Indexed by blob heap indexes */
GHashTable *method_signatures;
/*
* Indexes namespaces to hash tables that map class name to typedef token.
*/
GHashTable *name_cache; /*protected by the image lock*/
/*
* Indexed by MonoClass
*/
GHashTable *array_cache;
GHashTable *ptr_cache;
GHashTable *szarray_cache;
/* This has a separate lock to improve scalability */
mono_mutex_t szarray_cache_lock;
/*
* indexed by SignaturePointerPair
*/
GHashTable *native_func_wrapper_cache;
/*
* indexed by MonoMethod pointers
*/
GHashTable *wrapper_param_names;
GHashTable *array_accessor_cache;
GHashTable *icall_wrapper_cache;
GHashTable *rgctx_template_hash; /* LOCKING: templates lock */
/* Contains rarely used fields of runtime structures belonging to this image */
MonoPropertyHash *property_hash;
void *reflection_info;
/*
* user_info is a public field and is not touched by the
* metadata engine
*/
void *user_info;
#ifndef DISABLE_DLLMAP
/* dll map entries */
MonoDllMap *dll_map;
#endif
/* interfaces IDs from this image */
/* protected by the classes lock */
MonoBitSet *interface_bitset;
/* when the image is being closed, this is abused as a list of
malloc'ed regions to be freed. */
GSList *reflection_info_unregister_classes;
/* List of dependent image sets containing this image */
/* Protected by image_sets_lock */
GSList *image_sets;
/* Caches for wrappers that DO NOT reference generic */
/* arguments */
MonoWrapperCaches wrapper_caches;
/* Pre-allocated anon generic params for the first N generic
* parameters, for a small N */
MonoGenericParam *var_gparam_cache_fast;
MonoGenericParam *mvar_gparam_cache_fast;
/* Anon generic parameters past N, if needed */
MonoConcurrentHashTable *var_gparam_cache;
MonoConcurrentHashTable *mvar_gparam_cache;
/* The loader used to load this image */
MonoImageLoader *loader;
// Containers for MonoGenericParams associated with this image but not with any specific class or method. Created on demand.
// This could happen, for example, for MonoTypes associated with TypeSpec table entries.
MonoGenericContainer *anonymous_generic_class_container;
MonoGenericContainer *anonymous_generic_method_container;
#ifdef ENABLE_WEAK_ATTR
gboolean weak_fields_inited;
/* Contains 1 based indexes */
GHashTable *weak_field_indexes;
#endif
/* baseline images only: whether any metadata updates have been applied to this image */
gboolean has_updates;
/*
* No other runtime locks must be taken while holding this lock.
* It's meant to be used only to mutate and query structures part of this image.
*/
mono_mutex_t lock;
};
enum {
MONO_SECTION_TEXT,
MONO_SECTION_RSRC,
MONO_SECTION_RELOC,
MONO_SECTION_MAX
};
typedef struct {
GHashTable *hash;
char *data;
guint32 alloc_size; /* malloced bytes */
guint32 index;
guint32 offset; /* from start of metadata */
} MonoDynamicStream;
typedef struct {
guint32 alloc_rows;
guint32 rows;
guint8 row_size; /* calculated later with column_sizes */
guint8 columns;
guint32 next_idx;
guint32 *values; /* rows * columns */
} MonoDynamicTable;
/* "Dynamic" assemblies and images arise from System.Reflection.Emit */
struct _MonoDynamicAssembly {
MonoAssembly assembly;
char *strong_name;
guint32 strong_name_size;
};
struct _MonoDynamicImage {
MonoImage image;
guint32 meta_size;
guint32 text_rva;
guint32 metadata_rva;
guint32 image_base;
guint32 cli_header_offset;
guint32 iat_offset;
guint32 idt_offset;
guint32 ilt_offset;
guint32 imp_names_offset;
struct {
guint32 rva;
guint32 size;
guint32 offset;
guint32 attrs;
} sections [MONO_SECTION_MAX];
GHashTable *typespec;
GHashTable *typeref;
GHashTable *handleref;
MonoGHashTable *tokens;
GHashTable *blob_cache;
GHashTable *standalonesig_cache;
GList *array_methods;
GHashTable *method_aux_hash;
GHashTable *vararg_aux_hash;
MonoGHashTable *generic_def_objects;
gboolean initial_image;
guint32 pe_kind, machine;
char *strong_name;
guint32 strong_name_size;
char *win32_res;
guint32 win32_res_size;
guint8 *public_key;
int public_key_len;
MonoDynamicStream sheap;
MonoDynamicStream code; /* used to store method headers and bytecode */
MonoDynamicStream resources; /* managed embedded resources */
MonoDynamicStream us;
MonoDynamicStream blob;
MonoDynamicStream tstream;
MonoDynamicStream guid;
MonoDynamicTable tables [MONO_TABLE_NUM];
MonoClass *wrappers_type; /*wrappers are bound to this type instead of <Module>*/
};
/* Contains information about assembly binding */
typedef struct _MonoAssemblyBindingInfo {
char *name;
char *culture;
guchar public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH];
int major;
int minor;
AssemblyVersionSet old_version_bottom;
AssemblyVersionSet old_version_top;
AssemblyVersionSet new_version;
guint has_old_version_bottom : 1;
guint has_old_version_top : 1;
guint has_new_version : 1;
guint is_valid : 1;
gint32 domain_id; /*Needed to unload per-domain binding*/
} MonoAssemblyBindingInfo;
struct _MonoMethodHeader {
const unsigned char *code;
#ifdef MONO_SMALL_CONFIG
guint16 code_size;
#else
guint32 code_size;
#endif
guint16 max_stack : 15;
unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */
unsigned int num_clauses : 15;
/* if num_locals != 0, then the following apply: */
unsigned int init_locals : 1;
guint16 num_locals;
MonoExceptionClause *clauses;
MonoBitSet *volatile_args;
MonoBitSet *volatile_locals;
MonoType *locals [MONO_ZERO_LEN_ARRAY];
};
typedef struct {
const unsigned char *code;
guint32 code_size;
guint16 max_stack;
gboolean has_clauses;
gboolean has_locals;
} MonoMethodHeaderSummary;
// FIXME? offsetof (MonoMethodHeader, locals)?
#define MONO_SIZEOF_METHOD_HEADER (sizeof (struct _MonoMethodHeader) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
struct _MonoMethodSignature {
MonoType *ret;
#ifdef MONO_SMALL_CONFIG
guint8 param_count;
gint8 sentinelpos;
unsigned int generic_param_count : 5;
#else
guint16 param_count;
gint16 sentinelpos;
unsigned int generic_param_count : 16;
#endif
unsigned int call_convention : 6;
unsigned int hasthis : 1;
unsigned int explicit_this : 1;
unsigned int pinvoke : 1;
unsigned int is_inflated : 1;
unsigned int has_type_parameters : 1;
unsigned int suppress_gc_transition : 1;
unsigned int marshalling_disabled : 1;
MonoType *params [MONO_ZERO_LEN_ARRAY];
};
/*
* AOT cache configuration loaded from config files.
* Doesn't really belong here.
*/
typedef struct {
/*
* Enable aot caching for applications whose main assemblies are in
* this list.
*/
GSList *apps;
GSList *assemblies;
char *aot_options;
} MonoAotCacheConfig;
#define MONO_SIZEOF_METHOD_SIGNATURE (sizeof (struct _MonoMethodSignature) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
static inline gboolean
image_is_dynamic (MonoImage *image)
{
#ifdef DISABLE_REFLECTION_EMIT
return FALSE;
#else
return image->dynamic;
#endif
}
static inline gboolean
assembly_is_dynamic (MonoAssembly *assembly)
{
#ifdef DISABLE_REFLECTION_EMIT
return FALSE;
#else
return assembly->dynamic;
#endif
}
static inline int
table_info_get_rows (const MonoTableInfo *table)
{
return table->rows_;
}
/* for use with allocated memory blocks (assumes alignment is to 8 bytes) */
MONO_COMPONENT_API guint mono_aligned_addr_hash (gconstpointer ptr);
void
mono_image_check_for_module_cctor (MonoImage *image);
gpointer
mono_image_alloc (MonoImage *image, guint size);
gpointer
mono_image_alloc0 (MonoImage *image, guint size);
#define mono_image_new0(image,type,size) ((type *) mono_image_alloc0 (image, sizeof (type)* (size)))
char*
mono_image_strdup (MonoImage *image, const char *s);
char*
mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args);
char*
mono_image_strdup_printf (MonoImage *image, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
GList*
mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data);
GSList*
mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data);
MONO_COMPONENT_API
void
mono_image_lock (MonoImage *image);
MONO_COMPONENT_API
void
mono_image_unlock (MonoImage *image);
gpointer
mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property);
void
mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value);
void
mono_image_property_remove (MonoImage *image, gpointer subject);
MONO_COMPONENT_API
gboolean
mono_image_close_except_pools (MonoImage *image);
MONO_COMPONENT_API
void
mono_image_close_finish (MonoImage *image);
typedef void (*MonoImageUnloadFunc) (MonoImage *image, gpointer user_data);
void
mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data);
void
mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data);
void
mono_install_image_loader (const MonoImageLoader *loader);
void
mono_image_append_class_to_reflection_info_set (MonoClass *klass);
typedef struct _MonoMetadataUpdateData MonoMetadataUpdateData;
struct _MonoMetadataUpdateData {
int has_updates;
};
extern MonoMetadataUpdateData mono_metadata_update_data_private;
/* returns TRUE if there's at least one update */
static inline gboolean
mono_metadata_has_updates (void)
{
return mono_metadata_update_data_private.has_updates != 0;
}
/* components can't call the inline function directly since the private data isn't exported */
MONO_COMPONENT_API
gboolean
mono_metadata_has_updates_api (void);
void
mono_image_effective_table_slow (const MonoTableInfo **t, int idx);
gboolean
mono_metadata_update_has_modified_rows (const MonoTableInfo *t);
static inline void
mono_image_effective_table (const MonoTableInfo **t, int idx)
{
if (G_UNLIKELY (mono_metadata_has_updates ())) {
if (G_UNLIKELY (idx >= table_info_get_rows ((*t)) || mono_metadata_update_has_modified_rows (*t))) {
mono_image_effective_table_slow (t, idx);
}
}
}
enum MonoEnCDeltaOrigin {
MONO_ENC_DELTA_API = 0,
MONO_ENC_DELTA_DBG = 1,
};
MONO_COMPONENT_API void
mono_image_load_enc_delta (int delta_origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb, uint32_t dpdb_len, MonoError *error);
gboolean
mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo);
gboolean
mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo);
const char*
mono_metadata_string_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error);
const char *
mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index);
const char*
mono_metadata_blob_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error);
gboolean
mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, uint32_t *res, int res_size, MonoError *error);
MONO_COMPONENT_API
void
mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, uint32_t *res, int res_size);
gboolean
mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error);
MonoType*
mono_metadata_get_shared_type (MonoType *type);
void
mono_metadata_clean_generic_classes_for_image (MonoImage *image);
gboolean
mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index);
int
mono_metadata_table_num_rows_slow (MonoImage *image, int table_index);
static inline int
mono_metadata_table_num_rows (MonoImage *image, int table_index)
{
if (G_LIKELY (!image->has_updates))
return table_info_get_rows (&image->tables [table_index]);
else
return mono_metadata_table_num_rows_slow (image, table_index);
}
/* token_index is 1-based */
static inline gboolean
mono_metadata_table_bounds_check (MonoImage *image, int table_index, int token_index)
{
/* returns true if given index is not in bounds with provided table/index pair */
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_table_bounds_check_slow (image, table_index, token_index);
}
MONO_COMPONENT_API
const char * mono_meta_table_name (int table);
void mono_metadata_compute_table_bases (MonoImage *meta);
gboolean
mono_metadata_interfaces_from_typedef_full (MonoImage *image,
guint32 table_index,
MonoClass ***interfaces,
guint *count,
gboolean heap_alloc_result,
MonoGenericContext *context,
MonoError *error);
MONO_API MonoMethodSignature *
mono_metadata_parse_method_signature_full (MonoImage *image,
MonoGenericContainer *generic_container,
int def,
const char *ptr,
const char **rptr,
MonoError *error);
MONO_API MonoMethodHeader *
mono_metadata_parse_mh_full (MonoImage *image,
MonoGenericContainer *container,
const char *ptr,
MonoError *error);
MonoMethodSignature *mono_metadata_parse_signature_checked (MonoImage *image,
uint32_t token,
MonoError *error);
gboolean
mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary);
int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count);
gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def);
guint
mono_metadata_generic_context_hash (const MonoGenericContext *context);
gboolean
mono_metadata_generic_context_equal (const MonoGenericContext *g1,
const MonoGenericContext *g2);
MonoGenericInst *
mono_metadata_parse_generic_inst (MonoImage *image,
MonoGenericContainer *container,
int count,
const char *ptr,
const char **rptr,
MonoError *error);
MONO_COMPONENT_API MonoGenericInst *
mono_metadata_get_generic_inst (int type_argc,
MonoType **type_argv);
MonoGenericInst *
mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate);
MonoGenericClass *
mono_metadata_lookup_generic_class (MonoClass *gclass,
MonoGenericInst *inst,
gboolean is_dynamic);
MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error);
guint
mono_metadata_generic_param_hash (MonoGenericParam *p);
gboolean
mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2);
void mono_dynamic_stream_reset (MonoDynamicStream* stream);
void mono_assembly_load_friends (MonoAssembly* ass);
MONO_API gint32
mono_assembly_addref (MonoAssembly *assembly);
gint32
mono_assembly_decref (MonoAssembly *assembly);
void mono_assembly_release_gc_roots (MonoAssembly *assembly);
gboolean mono_assembly_close_except_image_pools (MonoAssembly *assembly);
void mono_assembly_close_finish (MonoAssembly *assembly);
gboolean mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *pubt2);
void mono_config_parse_publisher_policy (const char *filename, MonoAssemblyBindingInfo *binding_info);
gboolean
mono_assembly_name_parse_full (const char *name,
MonoAssemblyName *aname,
gboolean save_public_key,
gboolean *is_version_defined,
gboolean *is_token_defined);
gboolean
mono_assembly_fill_assembly_name_full (MonoImage *image, MonoAssemblyName *aname, gboolean copyBlobs);
MONO_API guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner);
MonoGenericParam*
mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar);
void mono_unload_interface_ids (MonoBitSet *bitset);
MonoType *mono_metadata_type_dup (MonoImage *image, const MonoType *original);
MonoType *mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *original, const MonoType *cmods_source);
MonoMethodSignature *mono_metadata_signature_dup_full (MonoImage *image,MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig);
MonoMethodSignature *mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass);
MonoGenericInst *
mono_get_shared_generic_inst (MonoGenericContainer *container);
int
mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open);
MONO_API void mono_type_get_desc (GString *res, MonoType *type, mono_bool include_namespace);
gboolean
mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only);
MonoMarshalSpec *
mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr);
guint mono_metadata_generic_inst_hash (gconstpointer data);
gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb);
gboolean
mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2);
MONO_API void
mono_metadata_field_info_with_mempool (
MonoImage *meta,
guint32 table_index,
guint32 *offset,
guint32 *rva,
MonoMarshalSpec **marshal_spec);
MonoClassField*
mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field);
MonoEvent*
mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event);
MonoProperty*
mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property);
guint32
mono_metadata_signature_size (MonoMethodSignature *sig);
guint mono_metadata_str_hash (gconstpointer v1);
gboolean mono_image_load_pe_data (MonoImage *image);
gboolean mono_image_load_cli_data (MonoImage *image);
void mono_image_load_names (MonoImage *image);
MonoImage *mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
MonoImage *mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status);
MONO_COMPONENT_API
MonoImage *mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename);
MonoException *mono_get_exception_field_access_msg (const char *msg);
MonoException *mono_get_exception_method_access_msg (const char *msg);
MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error);
MonoMethod *mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error);
MonoMethod *mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error);
void mono_type_set_alignment (MonoTypeEnum type, int align);
MonoType *
mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error);
MonoMethodSignature*
mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error);
MONO_COMPONENT_API MonoMethod *
mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error);
guint32
mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index);
void
mono_wrapper_caches_free (MonoWrapperCaches *cache);
MonoWrapperCaches*
mono_method_get_wrapper_cache (MonoMethod *method);
MonoWrapperCaches*
mono_method_get_wrapper_cache (MonoMethod *method);
MonoType*
mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error);
MonoGenericContainer *
mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar);
void
mono_loader_register_module (const char *name, MonoDl *module);
void
mono_ginst_get_desc (GString *str, MonoGenericInst *ginst);
void
mono_loader_set_strict_assembly_name_check (gboolean enabled);
gboolean
mono_loader_get_strict_assembly_name_check (void);
MONO_COMPONENT_API gboolean
mono_type_in_image (MonoType *type, MonoImage *image);
gboolean
mono_type_is_valid_generic_argument (MonoType *type);
void
mono_metadata_get_class_guid (MonoClass* klass, uint8_t* guid, MonoError *error);
#define MONO_CLASS_IS_INTERFACE_INTERNAL(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (m_class_get_byval_arg (c)))
static inline gboolean
m_image_is_raw_data_allocated (MonoImage *image)
{
return image->storage ? image->storage->raw_data_allocated : FALSE;
}
static inline gboolean
m_image_is_fileio_used (MonoImage *image)
{
return image->storage ? image->storage->fileio_used : FALSE;
}
#ifdef HOST_WIN32
static inline gboolean
m_image_is_module_handle (MonoImage *image)
{
return image->storage ? image->storage->is_module_handle : FALSE;
}
static inline gboolean
m_image_has_entry_point (MonoImage *image)
{
return image->storage ? image->storage->has_entry_point : FALSE;
}
#endif
static inline const char *
m_image_get_name (MonoImage *image)
{
return image->name;
}
static inline const char *
m_image_get_filename (MonoImage *image)
{
return image->filename;
}
static inline const char *
m_image_get_assembly_name (MonoImage *image)
{
return image->assembly_name;
}
static inline
MonoAssemblyLoadContext *
mono_image_get_alc (MonoImage *image)
{
return image->alc;
}
static inline
MonoAssemblyLoadContext *
mono_assembly_get_alc (MonoAssembly *assm)
{
return mono_image_get_alc (assm->image);
}
static inline MonoType*
mono_signature_get_return_type_internal (MonoMethodSignature *sig)
{
return sig->ret;
}
/**
* mono_type_get_type_internal:
* \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.
*/
static inline int
mono_type_get_type_internal (MonoType *type)
{
return type->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.
*/
static inline MonoMethodSignature*
mono_type_get_signature_internal (MonoType *type)
{
g_assert (type->type == MONO_TYPE_FNPTR);
return type->data.method;
}
/**
* m_type_is_byref:
* \param type the \c MonoType operated on
* \returns TRUE if \p type represents a type passed by reference,
* FALSE otherwise.
*/
static inline gboolean
m_type_is_byref (const MonoType *type)
{
return type->byref__;
}
/**
* mono_type_get_class_internal:
* \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.
*/
static inline MonoClass*
mono_type_get_class_internal (MonoType *type)
{
/* FIXME: review the runtime users before adding the assert here */
return type->data.klass;
}
/**
* mono_type_get_array_type_internal:
* \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.
*/
static inline MonoArrayType*
mono_type_get_array_type_internal (MonoType *type)
{
return type->data.array;
}
static inline int
mono_metadata_table_to_ptr_table (int table_num)
{
switch (table_num) {
case MONO_TABLE_FIELD: return MONO_TABLE_FIELD_POINTER;
case MONO_TABLE_METHOD: return MONO_TABLE_METHOD_POINTER;
case MONO_TABLE_PARAM: return MONO_TABLE_PARAM_POINTER;
case MONO_TABLE_PROPERTY: return MONO_TABLE_PROPERTY_POINTER;
case MONO_TABLE_EVENT: return MONO_TABLE_EVENT_POINTER;
default:
g_assert_not_reached ();
}
}
#endif /* __MONO_METADATA_INTERNALS_H__ */
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/object.c | /**
* \file
* Object creation for the Mono runtime
*
* Author:
* Miguel de Icaza ([email protected])
* Paolo Molaro ([email protected])
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2011 Novell, Inc (http://www.novell.com)
* Copyright 2001 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>
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/object.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/domain-internals.h>
#include "mono/metadata/metadata-internals.h"
#include "mono/metadata/class-internals.h"
#include "mono/metadata/class-init.h"
#include <mono/metadata/assembly.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/mono-hash-internals.h>
#include "mono/metadata/debug-helpers.h"
#include <mono/metadata/threads.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/environment.h>
#include "mono/metadata/profiler-private.h"
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/w32event.h>
#include <mono/metadata/w32process.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/runtime.h>
#include <mono/metadata/metadata-update.h>
#include <mono/utils/strenc.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/mono-logger-internals.h>
#include "cominterop.h"
#include <mono/utils/w32api.h>
#include <mono/utils/unlocked.h>
#include "external-only.h"
#include "monitor.h"
#include "icall-decl.h"
#include "icall-signatures.h"
#if _MSC_VER
#pragma warning(disable:4312) // FIXME pointer cast to different size
#endif
// If no symbols in an object file in a static library are referenced, its exports will not be exported.
// There are a few workarounds:
// 1. Link to .o/.obj files directly on the link command line,
// instead of putting them in static libraries.
// 2. Use a Windows .def file, or exports on command line, or Unix equivalent.
// 3. Have a reference to at least one symbol in the .o/.obj.
// That is effectively what this include does.
#include "external-only.c"
static void
get_default_field_value (MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error);
static void
mono_ldstr_metadata_sig (const char* sig, MonoStringHandleOut string_handle, MonoError *error);
static void
free_main_args (void);
static char *
mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s, MonoError *error);
static char *
mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s, MonoError *error);
/* Class lazy loading functions */
static GENERATE_GET_CLASS_WITH_CACHE (pointer, "System.Reflection", "Pointer")
static GENERATE_GET_CLASS_WITH_CACHE (unhandled_exception_event_args, "System", "UnhandledExceptionEventArgs")
static GENERATE_GET_CLASS_WITH_CACHE (first_chance_exception_event_args, "System.Runtime.ExceptionServices", "FirstChanceExceptionEventArgs")
static GENERATE_GET_CLASS_WITH_CACHE (sta_thread_attribute, "System", "STAThreadAttribute")
static GENERATE_GET_CLASS_WITH_CACHE (activation_services, "System.Runtime.Remoting.Activation", "ActivationServices")
static GENERATE_TRY_GET_CLASS_WITH_CACHE (execution_context, "System.Threading", "ExecutionContext")
#define ldstr_lock() mono_coop_mutex_lock (&ldstr_section)
#define ldstr_unlock() mono_coop_mutex_unlock (&ldstr_section)
static MonoCoopMutex ldstr_section;
/* Used by remoting proxies */
static MonoMethod *create_proxy_for_type_method;
static MonoGHashTable *ldstr_table;
static GString *
quote_escape_and_append_string (char *src_str, GString *target_str);
static GString *
format_cmd_line (int argc, char **argv, gboolean add_host);
/**
* mono_runtime_object_init:
* \param this_obj the object to initialize
* This function calls the zero-argument constructor (which must
* exist) for the given object.
*/
void
mono_runtime_object_init (MonoObject *this_obj)
{
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
mono_runtime_object_init_checked (this_obj, error);
mono_error_assert_ok (error);
MONO_EXIT_GC_UNSAFE;
}
/**
* mono_runtime_object_init_handle:
* \param this_obj the object to initialize
* \param error set on error.
* This function calls the zero-argument constructor (which must
* exist) for the given object and returns TRUE on success, or FALSE
* on error and sets \p error.
*/
gboolean
mono_runtime_object_init_handle (MonoObjectHandle this_obj, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
error_init (error);
MonoClass * const klass = MONO_HANDLE_GETVAL (this_obj, vtable)->klass;
MonoMethod * const method = mono_class_get_method_from_name_checked (klass, ".ctor", 0, 0, error);
mono_error_assert_msg_ok (error, "Could not lookup zero argument constructor");
g_assertf (method, "Could not lookup zero argument constructor for class %s", mono_type_get_full_name (klass));
if (m_class_is_valuetype (method->klass)) {
MonoGCHandle gchandle = NULL;
gpointer raw = mono_object_handle_pin_unbox (this_obj, &gchandle);
mono_runtime_invoke_checked (method, raw, NULL, error);
mono_gchandle_free_internal (gchandle);
} else {
mono_runtime_invoke_handle_void (method, this_obj, NULL, error);
}
HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
}
/**
* mono_runtime_object_init_checked:
* \param this_obj the object to initialize
* \param error set on error.
* This function calls the zero-argument constructor (which must
* exist) for the given object and returns TRUE on success, or FALSE
* on error and sets \p error.
*/
gboolean
mono_runtime_object_init_checked (MonoObject *this_obj_raw, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, this_obj);
gboolean const result = mono_runtime_object_init_handle (this_obj, error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/* The pseudo algorithm for type initialization from the spec
Note it doesn't say anything about domains - only threads.
2. If the type is initialized you are done.
2.1. If the type is not yet initialized, try to take an
initialization lock.
2.2. If successful, record this thread as responsible for
initializing the type and proceed to step 2.3.
2.2.1. If not, see whether this thread or any thread
waiting for this thread to complete already holds the lock.
2.2.2. If so, return since blocking would create a deadlock. This thread
will now see an incompletely initialized state for the type,
but no deadlock will arise.
2.2.3 If not, block until the type is initialized then return.
2.3 Initialize the parent type and then all interfaces implemented
by this type.
2.4 Execute the type initialization code for this type.
2.5 Mark the type as initialized, release the initialization lock,
awaken any threads waiting for this type to be initialized,
and return.
*/
typedef struct
{
MonoNativeThreadId initializing_tid;
guint32 waiting_count;
gboolean done;
MonoCoopMutex mutex;
/* condvar used to wait for 'done' becoming TRUE */
MonoCoopCond cond;
} TypeInitializationLock;
/* for locking access to type_initialization_hash and blocked_thread_hash */
static MonoCoopMutex type_initialization_section;
static void
mono_type_initialization_lock (void)
{
/* The critical sections protected by this lock in mono_runtime_class_init_full () can block */
mono_coop_mutex_lock (&type_initialization_section);
}
static void
mono_type_initialization_unlock (void)
{
mono_coop_mutex_unlock (&type_initialization_section);
}
static void
mono_type_init_lock (TypeInitializationLock *lock)
{
MONO_REQ_GC_NEUTRAL_MODE;
mono_coop_mutex_lock (&lock->mutex);
}
static void
mono_type_init_unlock (TypeInitializationLock *lock)
{
mono_coop_mutex_unlock (&lock->mutex);
}
/* from vtable to lock */
static GHashTable *type_initialization_hash;
/* from thread id to thread id being waited on */
static GHashTable *blocked_thread_hash;
/* Main thread */
static MonoThread *main_thread;
/* Functions supplied by the runtime */
static MonoRuntimeCallbacks callbacks;
/**
* mono_thread_set_main:
* \param thread thread to set as the main thread
* This function can be used to instruct the runtime to treat \p thread
* as the main thread, ie, the thread that would normally execute the \c Main
* method. This basically means that at the end of \p thread, the runtime will
* wait for the existing foreground threads to quit and other such details.
*/
void
mono_thread_set_main (MonoThread *thread)
{
MONO_REQ_GC_UNSAFE_MODE;
static gboolean registered = FALSE;
if (!registered) {
void *key = thread->internal_thread ? (gpointer)(gsize) MONO_UINT_TO_NATIVE_THREAD_ID (thread->internal_thread->tid) : NULL;
MONO_GC_REGISTER_ROOT_SINGLE (main_thread, MONO_ROOT_SOURCE_THREADING, key, "Thread Main Object");
registered = TRUE;
}
main_thread = thread;
}
/**
* mono_thread_get_main:
*/
MonoThread*
mono_thread_get_main (void)
{
MONO_REQ_GC_UNSAFE_MODE;
return main_thread;
}
void
mono_type_initialization_init (void)
{
mono_coop_mutex_init_recursive (&type_initialization_section);
type_initialization_hash = g_hash_table_new (NULL, NULL);
blocked_thread_hash = g_hash_table_new (NULL, NULL);
mono_coop_mutex_init (&ldstr_section);
mono_register_jit_icall (ves_icall_string_alloc, mono_icall_sig_object_int, FALSE);
}
static MonoException*
mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException* inner_raw, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoException, inner);
HANDLE_FUNCTION_RETURN_OBJ (mono_get_exception_type_initialization_handle (type_name, inner, error));
}
/**
* get_type_init_exception_for_vtable:
*
* Return the stored type initialization exception for VTABLE.
*/
static MonoException*
get_type_init_exception_for_vtable (MonoVTable *vtable)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoClass *klass = vtable->klass;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
MonoException *ex;
gchar *full_name;
if (!vtable->init_failed)
g_error ("Trying to get the init exception for a non-failed vtable of class %s", mono_type_get_full_name (klass));
/*
* If the initializing thread was rudely aborted, the exception is not stored
* in the hash.
*/
ex = NULL;
mono_mem_manager_lock (mem_manager);
ex = (MonoException *)mono_g_hash_table_lookup (mem_manager->type_init_exception_hash, klass);
mono_mem_manager_unlock (mem_manager);
if (!ex) {
const char *klass_name_space = m_class_get_name_space (klass);
const char *klass_name = m_class_get_name (klass);
if (klass_name_space && *klass_name_space)
full_name = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
else
full_name = g_strdup (klass_name);
ex = mono_get_exception_type_initialization_checked (full_name, NULL, error);
g_free (full_name);
return_val_if_nok (error, NULL);
}
return ex;
}
/**
* mono_runtime_class_init:
* \param vtable vtable that needs to be initialized
* This routine calls the class constructor for \p vtable.
*/
void
mono_runtime_class_init (MonoVTable *vtable)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
mono_runtime_class_init_full (vtable, error);
mono_error_assert_ok (error);
}
/*
* Returns TRUE if the lock was freed.
* LOCKING: Caller should hold type_initialization_lock.
*/
static gboolean
unref_type_lock (TypeInitializationLock *lock)
{
--lock->waiting_count;
if (lock->waiting_count == 0) {
mono_coop_mutex_destroy (&lock->mutex);
mono_coop_cond_destroy (&lock->cond);
g_free (lock);
return TRUE;
} else {
return FALSE;
}
}
/**
* mono_runtime_run_module_cctor:
* \param image the image whose module ctor to run
* \param error set on error
* This routine runs the module ctor for \p image, if it hasn't already run
*/
gboolean
mono_runtime_run_module_cctor (MonoImage *image, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!image->checked_module_cctor) {
mono_image_check_for_module_cctor (image);
if (image->has_module_cctor) {
MonoClass *module_klass;
MonoVTable *module_vtable;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE, "Running module .cctor for '%s'", image->name);
module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
if (!module_klass) {
return FALSE;
}
module_vtable = mono_class_vtable_checked (module_klass, error);
if (!module_vtable)
return FALSE;
if (!mono_runtime_class_init_full (module_vtable, error))
return FALSE;
}
}
return TRUE;
}
/**
* mono_runtime_class_init_full:
* \param vtable that neeeds to be initialized
* \param error set on error
* \returns TRUE if class constructor \c .cctor has been initialized successfully, or FALSE otherwise and sets \p error.
*/
gboolean
mono_runtime_class_init_full (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (vtable->initialized)
return TRUE;
MonoClass *klass = vtable->klass;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
MonoImage *klass_image = m_class_get_image (klass);
if (!mono_runtime_run_module_cctor (klass_image, error)) {
return FALSE;
}
MonoMethod *method = mono_class_get_cctor (klass);
if (!method) {
vtable->initialized = 1;
return TRUE;
}
MonoNativeThreadId tid = mono_native_thread_id_get ();
/*
* Due some preprocessing inside a global lock. If we are the first thread
* trying to initialize this class, create a separate lock+cond var, and
* acquire it before leaving the global lock. The other threads will wait
* on this cond var.
*/
mono_type_initialization_lock ();
/* double check... */
if (vtable->initialized) {
mono_type_initialization_unlock ();
return TRUE;
}
gboolean do_initialization = FALSE;
TypeInitializationLock *lock = NULL;
gboolean pending_tae = FALSE;
gboolean ret = FALSE;
HANDLE_FUNCTION_ENTER ();
if (vtable->init_failed) {
/* The type initialization already failed once, rethrow the same exception */
MonoException *exp = get_type_init_exception_for_vtable (vtable);
MONO_HANDLE_NEW (MonoException, exp);
/* Reset the stack_trace and trace_ips because the exception is reused */
exp->stack_trace = NULL;
exp->trace_ips = NULL;
mono_type_initialization_unlock ();
mono_error_set_exception_instance (error, exp);
goto return_false;
}
lock = (TypeInitializationLock *)g_hash_table_lookup (type_initialization_hash, vtable);
if (lock == NULL) {
lock = (TypeInitializationLock *)g_malloc0 (sizeof (TypeInitializationLock));
mono_coop_mutex_init_recursive (&lock->mutex);
mono_coop_cond_init (&lock->cond);
lock->initializing_tid = tid;
lock->waiting_count = 1;
lock->done = FALSE;
g_hash_table_insert (type_initialization_hash, vtable, lock);
do_initialization = TRUE;
} else {
gpointer blocked;
TypeInitializationLock *pending_lock;
if (mono_native_thread_id_equals (lock->initializing_tid, tid)) {
mono_type_initialization_unlock ();
goto return_true;
}
/* see if the thread doing the initialization is already blocked on this thread */
gboolean is_blocked = TRUE;
blocked = GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (lock->initializing_tid));
while ((pending_lock = (TypeInitializationLock*) g_hash_table_lookup (blocked_thread_hash, blocked))) {
if (mono_native_thread_id_equals (pending_lock->initializing_tid, tid)) {
if (!pending_lock->done) {
mono_type_initialization_unlock ();
goto return_true;
} else {
/* the thread doing the initialization is blocked on this thread,
but on a lock that has already been freed. It just hasn't got
time to awake */
is_blocked = FALSE;
break;
}
}
blocked = GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (pending_lock->initializing_tid));
}
++lock->waiting_count;
/* record the fact that we are waiting on the initializing thread */
if (is_blocked)
g_hash_table_insert (blocked_thread_hash, GUINT_TO_POINTER (tid), lock);
}
mono_type_initialization_unlock ();
if (do_initialization) {
MonoException *exc = NULL;
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE)) {
char* type_name = mono_type_full_name (m_class_get_byval_arg (klass));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE, "Running class .cctor for %s from '%s'", type_name, m_class_get_image (klass)->name);
g_free (type_name);
}
/* We are holding the per-vtable lock, do the actual initialization */
mono_threads_begin_abort_protected_block ();
mono_runtime_try_invoke (method, NULL, NULL, (MonoObject**) &exc, error);
MonoExceptionHandle exch = MONO_HANDLE_NEW (MonoException, exc);
mono_threads_end_abort_protected_block ();
//exception extracted, error will be set to the right value later
if (exc == NULL && !is_ok (error)) { // invoking failed but exc was not set
exc = mono_error_convert_to_exception (error);
MONO_HANDLE_ASSIGN_RAW (exch, exc);
} else
mono_error_cleanup (error);
error_init_reuse (error);
const char *klass_name_space = m_class_get_name_space (klass);
const char *klass_name = m_class_get_name (klass);
/* If the initialization failed, mark the class as unusable. */
/* Avoid infinite loops */
if (!(!exc ||
(klass_image == mono_defaults.corlib &&
!strcmp (klass_name_space, "System") &&
!strcmp (klass_name, "TypeInitializationException")))) {
vtable->init_failed = 1;
char *full_name;
if (klass_name_space && *klass_name_space)
full_name = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
else
full_name = g_strdup (klass_name);
MonoException *exc_to_throw = mono_get_exception_type_initialization_checked (full_name, exc, error);
MONO_HANDLE_NEW (MonoException, exc_to_throw);
g_free (full_name);
mono_error_assert_ok (error); //We can't recover from this, no way to fail a type we can't alloc a failure.
/*
* Store the exception object so it could be thrown on subsequent
* accesses.
*/
mono_mem_manager_lock (mem_manager);
mono_g_hash_table_insert_internal (mem_manager->type_init_exception_hash, klass, exc_to_throw);
mono_mem_manager_unlock (mem_manager);
}
/* Signal to the other threads that we are done */
mono_type_init_lock (lock);
lock->done = TRUE;
mono_coop_cond_broadcast (&lock->cond);
mono_type_init_unlock (lock);
/*
* This can happen if the cctor self-aborts. We need to reactivate tae
* (next interruption checkpoint will throw it) and make sure we won't
* throw tie for the type.
*/
if (exc && mono_object_class (exc) == mono_defaults.threadabortexception_class) {
pending_tae = TRUE;
mono_thread_resume_interruption (FALSE);
}
} else {
/* this just blocks until the initializing thread is done */
mono_type_init_lock (lock);
while (!lock->done)
mono_coop_cond_wait (&lock->cond, &lock->mutex);
mono_type_init_unlock (lock);
}
/* Do cleanup and setting vtable->initialized inside the global lock again */
mono_type_initialization_lock ();
if (!do_initialization)
g_hash_table_remove (blocked_thread_hash, GUINT_TO_POINTER (tid));
{
gboolean deleted = unref_type_lock (lock);
if (deleted)
g_hash_table_remove (type_initialization_hash, vtable);
}
/* Have to set this here since we check it inside the global lock */
if (do_initialization && !vtable->init_failed)
vtable->initialized = 1;
mono_type_initialization_unlock ();
/* If vtable init fails because of TAE, we don't throw TIE, only the TAE */
if (vtable->init_failed && !pending_tae) {
/* Either we were the initializing thread or we waited for the initialization */
mono_error_set_exception_instance (error, get_type_init_exception_for_vtable (vtable));
goto return_false;
}
return_true:
ret = TRUE;
goto exit;
return_false:
ret = FALSE;
exit:
HANDLE_FUNCTION_RETURN_VAL (ret);
}
MonoDomain *
mono_vtable_domain_internal (MonoVTable *vtable)
{
return mono_get_root_domain ();
}
MonoDomain*
mono_vtable_domain (MonoVTable *vtable)
{
MONO_EXTERNAL_ONLY (MonoDomain*, mono_get_root_domain ());
}
MonoClass *
mono_vtable_class_internal (MonoVTable *vtable)
{
return vtable->klass;
}
MonoClass*
mono_vtable_class (MonoVTable *vtable)
{
MONO_EXTERNAL_ONLY (MonoClass*, mono_vtable_class_internal (vtable));
}
static
gboolean release_type_locks (gpointer key, gpointer value, gpointer user)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoVTable *vtable = (MonoVTable*)key;
TypeInitializationLock *lock = (TypeInitializationLock*) value;
if (mono_native_thread_id_equals (lock->initializing_tid, MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (user))) && !lock->done) {
lock->done = TRUE;
/*
* Have to set this since it cannot be set by the normal code in
* mono_runtime_class_init (). In this case, the exception object is not stored,
* and get_type_init_exception_for_class () needs to be aware of this.
*/
mono_type_init_lock (lock);
vtable->init_failed = 1;
mono_coop_cond_broadcast (&lock->cond);
mono_type_init_unlock (lock);
gboolean deleted = unref_type_lock (lock);
if (deleted)
return TRUE;
}
return FALSE;
}
void
mono_release_type_locks (MonoInternalThread *thread)
{
MONO_REQ_GC_UNSAFE_MODE;
mono_type_initialization_lock ();
g_hash_table_foreach_remove (type_initialization_hash, release_type_locks, GUINT_TO_POINTER (thread->tid));
mono_type_initialization_unlock ();
}
static MonoImtTrampolineBuilder imt_trampoline_builder;
static gboolean always_build_imt_trampolines;
#if (MONO_IMT_SIZE > 32)
#error "MONO_IMT_SIZE cannot be larger than 32"
#endif
void
mono_install_callbacks (MonoRuntimeCallbacks *cbs)
{
memcpy (&callbacks, cbs, sizeof (*cbs));
}
MonoRuntimeCallbacks*
mono_get_runtime_callbacks (void)
{
return &callbacks;
}
void
mono_install_imt_trampoline_builder (MonoImtTrampolineBuilder func)
{
imt_trampoline_builder = func;
}
void
mono_set_always_build_imt_trampolines (gboolean value)
{
always_build_imt_trampolines = value;
}
/**
* mono_compile_method:
* \param method The method to compile.
* This JIT-compiles the method, and returns the pointer to the native code
* produced.
*/
gpointer
mono_compile_method (MonoMethod *method)
{
gpointer result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_compile_method_checked (method, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_compile_method_checked:
* \param method The method to compile.
* \param error set on error.
* This JIT-compiles the method, and returns the pointer to the native code
* produced. On failure returns NULL and sets \p error.
*/
gpointer
mono_compile_method_checked (MonoMethod *method, MonoError *error)
{
gpointer res;
MONO_REQ_GC_NEUTRAL_MODE
error_init (error);
g_assert (callbacks.compile_method);
res = callbacks.compile_method (method, error);
return res;
}
gpointer
mono_runtime_create_delegate_trampoline (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE
g_assert (callbacks.create_delegate_trampoline);
return callbacks.create_delegate_trampoline (klass);
}
/**
* mono_runtime_free_method:
* \param method method to release
* This routine is invoked to free the resources associated with
* a method that has been JIT compiled. This is used to discard
* methods that were used only temporarily (for example, used in marshalling)
*/
void
mono_runtime_free_method (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE
if (callbacks.free_method)
callbacks.free_method (method);
mono_method_clear_object (method);
mono_free_method (method);
}
/*
* The vtables in the root appdomain are assumed to be reachable by other
* roots, and we don't use typed allocation in the other domains.
*/
/* The sync block is no longer a GC pointer */
#define GC_HEADER_BITMAP (0)
#define BITMAP_EL_SIZE (sizeof (gsize) * 8)
#define MONO_OBJECT_HEADER_BITS (MONO_ABI_SIZEOF (MonoObject) / MONO_ABI_SIZEOF (gpointer))
static gsize*
compute_class_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int *max_set, gboolean static_fields)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoClassField *field;
MonoClass *p;
guint32 pos;
int max_size, wordsize;
wordsize = TARGET_SIZEOF_VOID_P;
if (static_fields)
max_size = mono_class_data_size (klass) / wordsize;
else
max_size = m_class_get_instance_size (klass) / wordsize;
if (max_size > size) {
g_assert (offset <= 0);
bitmap = (gsize *)g_malloc0 ((max_size + BITMAP_EL_SIZE - 1) / BITMAP_EL_SIZE * sizeof (gsize));
size = max_size;
}
/* An Ephemeron cannot be marked by sgen */
if (mono_gc_is_moving () && !static_fields && m_class_get_image (klass) == mono_defaults.corlib && !strcmp ("Ephemeron", m_class_get_name (klass))) {
*max_set = 0;
memset (bitmap, 0, size / 8);
return bitmap;
}
for (p = klass; p != NULL; p = m_class_get_parent (p)) {
gpointer iter = NULL;
while ((field = mono_class_get_fields_internal (p, &iter))) {
MonoType *type;
if (static_fields) {
if (!(field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
continue;
} else {
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
}
/* FIXME: should not happen, flag as type load error */
if (m_type_is_byref (field->type))
break;
if (static_fields && field->offset == -1)
/* special static */
continue;
pos = field->offset / TARGET_SIZEOF_VOID_P;
pos += offset;
type = mono_type_get_underlying_type (field->type);
switch (type->type) {
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
break;
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
g_assert ((field->offset % wordsize) == 0);
g_assert (pos < size || pos <= max_size);
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
*max_set = MAX (*max_set, pos);
break;
case MONO_TYPE_GENERICINST:
if (!mono_type_generic_inst_is_valuetype (type)) {
g_assert ((field->offset % wordsize) == 0);
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
*max_set = MAX (*max_set, pos);
break;
} else {
/* fall through */
}
case MONO_TYPE_TYPEDBYREF:
case MONO_TYPE_VALUETYPE: {
MonoClass *fclass = mono_class_from_mono_type_internal (field->type);
if (m_class_has_references (fclass)) {
/* remove the object header */
compute_class_bitmap (fclass, bitmap, size, pos - MONO_OBJECT_HEADER_BITS, max_set, FALSE);
}
break;
}
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_BOOLEAN:
case MONO_TYPE_CHAR:
break;
default:
g_error ("compute_class_bitmap: Invalid type %x for field %s:%s\n", type->type, mono_type_get_full_name (m_field_get_parent (field)), field->name);
break;
}
}
if (static_fields)
break;
}
return bitmap;
}
/**
* mono_class_compute_bitmap:
*
* Mono internal function to compute a bitmap of reference fields in a class.
*/
gsize*
mono_class_compute_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int *max_set, gboolean static_fields)
{
MONO_REQ_GC_NEUTRAL_MODE;
return compute_class_bitmap (klass, bitmap, size, offset, max_set, static_fields);
}
#if 0
/*
* similar to the above, but sets the bits in the bitmap for any non-ref field
* and ignores static fields
*/
static gsize*
compute_class_non_ref_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset)
{
MonoClassField *field;
MonoClass *p;
guint32 pos, pos2;
int max_size, wordsize;
wordsize = TARGET_SIZEOF_VOID_P;
max_size = class->instance_size / wordsize;
if (max_size >= size)
bitmap = g_malloc0 (sizeof (gsize) * ((max_size) + 1));
for (p = class; p != NULL; p = p->parent) {
gpointer iter = NULL;
while ((field = mono_class_get_fields_internal (p, &iter))) {
MonoType *type;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
/* FIXME: should not happen, flag as type load error */
if (m_type_is_byref (field->type))
break;
pos = field->offset / wordsize;
pos += offset;
type = mono_type_get_underlying_type (field->type);
switch (type->type) {
#if SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
#endif
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R8:
if ((((field->offset + 7) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 7) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
#if SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
#endif
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_R4:
if ((((field->offset + 3) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 3) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
case MONO_TYPE_CHAR:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
if ((((field->offset + 1) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 1) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
break;
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
break;
case MONO_TYPE_GENERICINST:
if (!mono_type_generic_inst_is_valuetype (type)) {
break;
} else {
/* fall through */
}
case MONO_TYPE_VALUETYPE: {
MonoClass *fclass = mono_class_from_mono_type_internal (field->type);
/* remove the object header */
compute_class_non_ref_bitmap (fclass, bitmap, size, pos - MONO_OBJECT_HEADER_BITS);
break;
}
default:
g_assert_not_reached ();
break;
}
}
}
return bitmap;
}
/**
* mono_class_insecure_overlapping:
* check if a class with explicit layout has references and non-references
* fields overlapping.
*
* Returns: TRUE if it is insecure to load the type.
*/
gboolean
mono_class_insecure_overlapping (MonoClass *klass)
{
int max_set = 0;
gsize *bitmap;
gsize default_bitmap [4] = {0};
gsize *nrbitmap;
gsize default_nrbitmap [4] = {0};
int i, insecure = FALSE;
return FALSE;
bitmap = compute_class_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, FALSE);
nrbitmap = compute_class_non_ref_bitmap (klass, default_nrbitmap, sizeof (default_nrbitmap) * 8, 0);
for (i = 0; i <= max_set; i += sizeof (bitmap [0]) * 8) {
int idx = i % (sizeof (bitmap [0]) * 8);
if (bitmap [idx] & nrbitmap [idx]) {
insecure = TRUE;
break;
}
}
if (bitmap != default_bitmap)
g_free (bitmap);
if (nrbitmap != default_nrbitmap)
g_free (nrbitmap);
if (insecure) {
g_print ("class %s.%s in assembly %s has overlapping references\n", klass->name_space, klass->name, klass->image->name);
return FALSE;
}
return insecure;
}
#endif
MonoStringHandle
ves_icall_string_alloc_impl (int length, MonoError *error)
{
MonoString *s = mono_string_new_size_checked (length, error);
return_val_if_nok (error, NULL_HANDLE_STRING);
return MONO_HANDLE_NEW (MonoString, s);
}
#define BITMAP_EL_SIZE (sizeof (gsize) * 8)
/* LOCKING: Acquires the loader lock */
/*
* Sets the following fields in KLASS:
* - gc_desc
* - gc_descr_inited
*/
void
mono_class_compute_gc_descriptor (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE;
int max_set = 0;
gsize *bitmap;
gsize default_bitmap [4] = {0};
MonoGCDescriptor gc_descr;
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
if (m_class_is_gc_descr_inited (klass))
return;
bitmap = default_bitmap;
if (klass == mono_defaults.string_class) {
gc_descr = mono_gc_make_descr_for_string (bitmap, 2);
} else if (m_class_get_rank (klass)) {
MonoClass *klass_element_class = m_class_get_element_class (klass);
mono_class_compute_gc_descriptor (klass_element_class);
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (klass_element_class))) {
gsize abm = 1;
gc_descr = mono_gc_make_descr_for_array (m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY, &abm, 1, sizeof (gpointer));
/*printf ("new array descriptor: 0x%x for %s.%s\n", class->gc_descr,
class->name_space, class->name);*/
} else {
/* remove the object header */
bitmap = mono_class_compute_bitmap (klass_element_class, default_bitmap, sizeof (default_bitmap) * 8, - (int)(MONO_OBJECT_HEADER_BITS), &max_set, FALSE);
gc_descr = mono_gc_make_descr_for_array (m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY, bitmap, mono_array_element_size (klass) / sizeof (gpointer), mono_array_element_size (klass));
/*printf ("new vt array descriptor: 0x%x for %s.%s\n", class->gc_descr,
class->name_space, class->name);*/
}
} else {
/*static int count = 0;
if (count++ > 58)
return;*/
bitmap = mono_class_compute_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, FALSE);
/*
if (class->gc_descr == MONO_GC_DESCRIPTOR_NULL)
g_print ("disabling typed alloc (%d) for %s.%s\n", max_set, class->name_space, class->name);
*/
/*printf ("new descriptor: %p 0x%x for %s.%s\n", class->gc_descr, bitmap [0], class->name_space, class->name);*/
if (m_class_has_weak_fields (klass)) {
gsize *weak_bitmap = NULL;
int weak_bitmap_nbits = 0;
weak_bitmap = (gsize *)mono_class_alloc0 (klass, m_class_get_instance_size (klass) / sizeof (gsize));
if (mono_class_has_static_metadata (klass)) {
for (MonoClass *p = klass; p != NULL; p = m_class_get_parent (p)) {
gpointer iter = NULL;
guint32 first_field_idx = mono_class_get_first_field_idx (p);
MonoClassField *field;
MonoClassField *p_fields = m_class_get_fields (p);
MonoImage *p_image = m_class_get_image (p);
while ((field = mono_class_get_fields_internal (p, &iter))) {
guint32 field_idx = first_field_idx + (field - p_fields);
if (MONO_TYPE_IS_REFERENCE (field->type) && mono_assembly_is_weak_field (p_image, field_idx + 1)) {
int pos = field->offset / sizeof (gpointer);
if (pos + 1 > weak_bitmap_nbits)
weak_bitmap_nbits = pos + 1;
weak_bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
}
}
}
}
for (int pos = 0; pos < weak_bitmap_nbits; ++pos) {
if (weak_bitmap [pos / BITMAP_EL_SIZE] & ((gsize)1) << (pos % BITMAP_EL_SIZE)) {
/* Clear the normal bitmap so these refs don't keep an object alive */
bitmap [pos / BITMAP_EL_SIZE] &= ~(((gsize)1) << (pos % BITMAP_EL_SIZE));
}
}
mono_loader_lock ();
mono_class_set_weak_bitmap (klass, weak_bitmap_nbits, weak_bitmap);
mono_loader_unlock ();
}
gc_descr = mono_gc_make_descr_for_object (bitmap, max_set + 1, m_class_get_instance_size (klass));
}
if (bitmap != default_bitmap)
g_free (bitmap);
/* Publish the data */
mono_class_publish_gc_descriptor (klass, gc_descr);
}
/**
* field_is_special_static:
* @fklass: The MonoClass to look up.
* @field: The MonoClassField describing the field.
*
* Returns: SPECIAL_STATIC_THREAD if the field is thread static, SPECIAL_STATIC_NONE otherwise.
*/
static gint32
field_is_special_static (MonoClass *fklass, MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE;
ERROR_DECL (error);
MonoCustomAttrInfo *ainfo;
int i;
ainfo = mono_custom_attrs_from_field_checked (fklass, field, error);
mono_error_cleanup (error); /* FIXME don't swallow the error? */
if (!ainfo)
return FALSE;
for (i = 0; i < ainfo->num_attrs; ++i) {
MonoClass *klass = ainfo->attrs [i].ctor->klass;
if (m_class_get_image (klass) == mono_defaults.corlib) {
const char *klass_name = m_class_get_name (klass);
if (strcmp (klass_name, "ThreadStaticAttribute") == 0) {
mono_custom_attrs_free (ainfo);
return SPECIAL_STATIC_THREAD;
}
}
}
mono_custom_attrs_free (ainfo);
return SPECIAL_STATIC_NONE;
}
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) { \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define mono_final(a,b,c) { \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
/*
* mono_method_get_imt_slot:
*
* The IMT slot is embedded into AOTed code, so this must return the same value
* for the same method across all executions. This means:
* - pointers shouldn't be used as hash values.
* - mono_metadata_str_hash () should be used for hashing strings.
*/
guint32
mono_method_get_imt_slot (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethodSignature *sig;
int hashes_count;
guint32 *hashes_start, *hashes;
guint32 a, b, c;
int i;
/* This can be used to stress tests the collision code */
//return 0;
/*
* We do this to simplify generic sharing. It will hurt
* performance in cases where a class implements two different
* instantiations of the same generic interface.
* The code in build_imt_slots () depends on this.
*/
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
sig = mono_method_signature_internal (method);
hashes_count = sig->param_count + 4;
hashes_start = (guint32 *)g_malloc (hashes_count * sizeof (guint32));
hashes = hashes_start;
if (! MONO_CLASS_IS_INTERFACE_INTERNAL (method->klass)) {
g_error ("mono_method_get_imt_slot: %s.%s.%s is not an interface MonoMethod",
m_class_get_name_space (method->klass), m_class_get_name (method->klass), method->name);
}
/* Initialize hashes */
hashes [0] = mono_metadata_str_hash (m_class_get_name (method->klass));
hashes [1] = mono_metadata_str_hash (m_class_get_name_space (method->klass));
hashes [2] = mono_metadata_str_hash (method->name);
hashes [3] = mono_metadata_type_hash (sig->ret);
for (i = 0; i < sig->param_count; i++) {
hashes [4 + i] = mono_metadata_type_hash (sig->params [i]);
}
/* Setup internal state */
a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
/* Handle most of the hashes */
while (hashes_count > 3) {
a += hashes [0];
b += hashes [1];
c += hashes [2];
mix (a,b,c);
hashes_count -= 3;
hashes += 3;
}
/* Handle the last 3 hashes (all the case statements fall through) */
switch (hashes_count) {
case 3 : c += hashes [2];
case 2 : b += hashes [1];
case 1 : a += hashes [0];
mono_final (a,b,c);
case 0: /* nothing left to add */
break;
}
g_free (hashes_start);
/* Report the result */
return c % MONO_IMT_SIZE;
}
#undef rot
#undef mix
#undef mono_final
#define DEBUG_IMT 0
static void
add_imt_builder_entry (MonoImtBuilderEntry **imt_builder, MonoMethod *method, guint32 *imt_collisions_bitmap, int vtable_slot, int slot_num) {
MONO_REQ_GC_NEUTRAL_MODE;
guint32 imt_slot = mono_method_get_imt_slot (method);
MonoImtBuilderEntry *entry;
if (slot_num >= 0 && imt_slot != slot_num) {
/* we build just a single imt slot and this is not it */
return;
}
entry = (MonoImtBuilderEntry *)g_malloc0 (sizeof (MonoImtBuilderEntry));
entry->key = method;
entry->value.vtable_slot = vtable_slot;
entry->next = imt_builder [imt_slot];
if (imt_builder [imt_slot] != NULL) {
entry->children = imt_builder [imt_slot]->children + 1;
if (entry->children == 1) {
UnlockedIncrement (&mono_stats.imt_slots_with_collisions);
*imt_collisions_bitmap |= (1 << imt_slot);
}
} else {
entry->children = 0;
UnlockedIncrement (&mono_stats.imt_used_slots);
}
imt_builder [imt_slot] = entry;
#if DEBUG_IMT
{
char *method_name = mono_method_full_name (method, TRUE);
printf ("Added IMT slot for method (%p) %s: imt_slot = %d, vtable_slot = %d, colliding with other %d entries\n",
method, method_name, imt_slot, vtable_slot, entry->children);
g_free (method_name);
}
#endif
}
#if DEBUG_IMT
static void
print_imt_entry (const char* message, MonoImtBuilderEntry *e, int num) {
if (e != NULL) {
MonoMethod *method = e->key;
printf (" * %s [%d]: (%p) '%s.%s.%s'\n",
message,
num,
method,
method->klass->name_space,
method->klass->name,
method->name);
} else {
printf (" * %s: NULL\n", message);
}
}
#endif
static int
compare_imt_builder_entries (const void *p1, const void *p2) {
MonoImtBuilderEntry *e1 = *(MonoImtBuilderEntry**) p1;
MonoImtBuilderEntry *e2 = *(MonoImtBuilderEntry**) p2;
return (e1->key < e2->key) ? -1 : ((e1->key > e2->key) ? 1 : 0);
}
static int
imt_emit_ir (MonoImtBuilderEntry **sorted_array, int start, int end, GPtrArray *out_array)
{
MONO_REQ_GC_NEUTRAL_MODE;
int count = end - start;
int chunk_start = out_array->len;
if (count < 4) {
int i;
for (i = start; i < end; ++i) {
MonoIMTCheckItem *item = g_new0 (MonoIMTCheckItem, 1);
item->key = sorted_array [i]->key;
item->value = sorted_array [i]->value;
item->has_target_code = sorted_array [i]->has_target_code;
item->is_equals = TRUE;
if (i < end - 1)
item->check_target_idx = out_array->len + 1;
else
item->check_target_idx = 0;
g_ptr_array_add (out_array, item);
}
} else {
int middle = start + count / 2;
MonoIMTCheckItem *item = g_new0 (MonoIMTCheckItem, 1);
item->key = sorted_array [middle]->key;
item->is_equals = FALSE;
g_ptr_array_add (out_array, item);
imt_emit_ir (sorted_array, start, middle, out_array);
item->check_target_idx = imt_emit_ir (sorted_array, middle, end, out_array);
}
return chunk_start;
}
static GPtrArray*
imt_sort_slot_entries (MonoImtBuilderEntry *entries) {
MONO_REQ_GC_NEUTRAL_MODE;
int number_of_entries = entries->children + 1;
MonoImtBuilderEntry **sorted_array = (MonoImtBuilderEntry **)g_malloc (sizeof (MonoImtBuilderEntry*) * number_of_entries);
GPtrArray *result = g_ptr_array_new ();
MonoImtBuilderEntry *current_entry;
int i;
for (current_entry = entries, i = 0; current_entry != NULL; current_entry = current_entry->next, i++) {
sorted_array [i] = current_entry;
}
mono_qsort (sorted_array, number_of_entries, sizeof (MonoImtBuilderEntry*), compare_imt_builder_entries);
/*for (i = 0; i < number_of_entries; i++) {
print_imt_entry (" sorted array:", sorted_array [i], i);
}*/
imt_emit_ir (sorted_array, 0, number_of_entries, result);
g_free (sorted_array);
return result;
}
static gpointer
initialize_imt_slot (MonoVTable *vtable, MonoImtBuilderEntry *imt_builder_entry, gpointer fail_tramp)
{
MONO_REQ_GC_NEUTRAL_MODE;
if (imt_builder_entry != NULL) {
if (imt_builder_entry->children == 0 && !fail_tramp && !always_build_imt_trampolines) {
/* No collision, return the vtable slot contents */
return vtable->vtable [imt_builder_entry->value.vtable_slot];
} else {
/* Collision, build the trampoline */
GPtrArray *imt_ir = imt_sort_slot_entries (imt_builder_entry);
gpointer result;
int i;
result = imt_trampoline_builder (vtable,
(MonoIMTCheckItem**)imt_ir->pdata, imt_ir->len, fail_tramp);
for (i = 0; i < imt_ir->len; ++i)
g_free (g_ptr_array_index (imt_ir, i));
g_ptr_array_free (imt_ir, TRUE);
return result;
}
} else {
if (fail_tramp)
return fail_tramp;
else
/* Empty slot */
return NULL;
}
}
static MonoImtBuilderEntry*
get_generic_virtual_entries (MonoMemoryManager *mem_manager, gpointer *vtable_slot);
/*
* LOCKING: assume the loader lock is held
*
*/
static void
build_imt_slots (MonoClass *klass, MonoVTable *vt, gpointer* imt, GSList *extra_interfaces, int slot_num)
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
GSList *list_item;
guint32 imt_collisions_bitmap = 0;
MonoImtBuilderEntry **imt_builder = (MonoImtBuilderEntry **)g_calloc (MONO_IMT_SIZE, sizeof (MonoImtBuilderEntry*));
int method_count = 0;
gboolean record_method_count_for_max_collisions = FALSE;
gboolean has_generic_virtual = FALSE, has_variant_iface = FALSE;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (klass);
#if DEBUG_IMT
printf ("Building IMT for class %s.%s slot %d\n", m_class_get_name_space (klass), m_class_get_name (klass), slot_num);
#endif
int klass_interface_offsets_count = m_class_get_interface_offsets_count (klass);
MonoClass **klass_interfaces_packed = m_class_get_interfaces_packed (klass);
guint16 *klass_interface_offsets_packed = m_class_get_interface_offsets_packed (klass);
for (i = 0; i < klass_interface_offsets_count; ++i) {
MonoClass *iface = klass_interfaces_packed [i];
int interface_offset = klass_interface_offsets_packed [i];
int method_slot_in_interface, vt_slot;
if (mono_class_has_variant_generic_params (iface))
has_variant_iface = TRUE;
mono_class_setup_methods (iface);
vt_slot = interface_offset;
int mcount = mono_class_get_method_count (iface);
for (method_slot_in_interface = 0; method_slot_in_interface < mcount; method_slot_in_interface++) {
MonoMethod *method;
if (slot_num >= 0 && mono_class_is_ginst (iface)) {
/*
* The imt slot of the method is the same as for its declaring method,
* see the comment in mono_method_get_imt_slot (), so we can
* avoid inflating methods which will be discarded by
* add_imt_builder_entry anyway.
*/
method = mono_class_get_method_by_index (mono_class_get_generic_class (iface)->container_class, method_slot_in_interface);
if (m_method_is_static (method))
continue;
if (mono_method_get_imt_slot (method) != slot_num) {
vt_slot ++;
continue;
}
}
method = mono_class_get_method_by_index (iface, method_slot_in_interface);
if (method->is_generic) {
has_generic_virtual = TRUE;
vt_slot ++;
continue;
}
if (m_method_is_static (method))
continue;
if (method->flags & METHOD_ATTRIBUTE_VIRTUAL) {
add_imt_builder_entry (imt_builder, method, &imt_collisions_bitmap, vt_slot, slot_num);
vt_slot ++;
}
}
}
if (extra_interfaces) {
int interface_offset = m_class_get_vtable_size (klass);
for (list_item = extra_interfaces; list_item != NULL; list_item=list_item->next) {
MonoClass* iface = (MonoClass *)list_item->data;
int method_slot_in_interface;
int mcount = mono_class_get_method_count (iface);
for (method_slot_in_interface = 0; method_slot_in_interface < mcount; method_slot_in_interface++) {
MonoMethod *method = mono_class_get_method_by_index (iface, method_slot_in_interface);
if (method->is_generic)
has_generic_virtual = TRUE;
add_imt_builder_entry (imt_builder, method, &imt_collisions_bitmap, interface_offset + method_slot_in_interface, slot_num);
}
interface_offset += mcount;
}
}
for (i = 0; i < MONO_IMT_SIZE; ++i) {
/* overwrite the imt slot only if we're building all the entries or if
* we're building this specific one
*/
if (slot_num < 0 || i == slot_num) {
MonoImtBuilderEntry *entries = get_generic_virtual_entries (mem_manager, &imt [i]);
if (entries) {
if (imt_builder [i]) {
MonoImtBuilderEntry *entry;
/* Link entries with imt_builder [i] */
for (entry = entries; entry->next; entry = entry->next) {
#if DEBUG_IMT
MonoMethod *method = (MonoMethod*)entry->key;
char *method_name = mono_method_full_name (method, TRUE);
printf ("Added extra entry for method (%p) %s: imt_slot = %d\n", method, method_name, i);
g_free (method_name);
#endif
}
entry->next = imt_builder [i];
entries->children += imt_builder [i]->children + 1;
}
imt_builder [i] = entries;
}
if (has_generic_virtual || has_variant_iface) {
/*
* There might be collisions later when the the trampoline is expanded.
*/
imt_collisions_bitmap |= (1 << i);
/*
* The IMT trampoline might be called with an instance of one of the
* generic virtual methods, so has to fallback to the IMT trampoline.
*/
imt [i] = initialize_imt_slot (vt, imt_builder [i], callbacks.get_imt_trampoline (vt, i));
} else {
imt [i] = initialize_imt_slot (vt, imt_builder [i], NULL);
}
#if DEBUG_IMT
printf ("initialize_imt_slot[%d]: %p methods %d\n", i, imt [i], imt_builder [i]->children + 1);
#endif
}
if (imt_builder [i] != NULL) {
int methods_in_slot = imt_builder [i]->children + 1;
if (methods_in_slot > UnlockedRead (&mono_stats.imt_max_collisions_in_slot)) {
UnlockedWrite (&mono_stats.imt_max_collisions_in_slot, methods_in_slot);
record_method_count_for_max_collisions = TRUE;
}
method_count += methods_in_slot;
}
}
UnlockedAdd (&mono_stats.imt_number_of_methods, method_count);
if (record_method_count_for_max_collisions) {
UnlockedWrite (&mono_stats.imt_method_count_when_max_collisions, method_count);
}
for (i = 0; i < MONO_IMT_SIZE; i++) {
MonoImtBuilderEntry* entry = imt_builder [i];
while (entry != NULL) {
MonoImtBuilderEntry* next = entry->next;
g_free (entry);
entry = next;
}
}
g_free (imt_builder);
/* we OR the bitmap since we may build just a single imt slot at a time */
vt->imt_collisions_bitmap |= imt_collisions_bitmap;
}
/**
* mono_vtable_build_imt_slot:
* \param vtable virtual object table struct
* \param imt_slot slot in the IMT table
* Fill the given \p imt_slot in the IMT table of \p vtable with
* a trampoline or a trampoline for the case of collisions.
* This is part of the internal mono API.
* LOCKING: Take the loader lock.
*/
void
mono_vtable_build_imt_slot (MonoVTable* vtable, int imt_slot)
{
MONO_REQ_GC_NEUTRAL_MODE;
gpointer *imt = (gpointer*)vtable;
imt -= MONO_IMT_SIZE;
g_assert (imt_slot >= 0 && imt_slot < MONO_IMT_SIZE);
/* no support for extra interfaces: the proxy objects will need
* to build the complete IMT
* Update and heck needs to ahppen inside the proper domain lock, as all
* the changes made to a MonoVTable.
*/
mono_loader_lock ();
/* we change the slot only if it wasn't changed from the generic imt trampoline already */
if (!callbacks.imt_entry_inited (vtable, imt_slot))
build_imt_slots (vtable->klass, vtable, imt, NULL, imt_slot);
mono_loader_unlock ();
}
#define THUNK_THRESHOLD 10
typedef struct _GenericVirtualCase {
MonoMethod *method;
gpointer code;
int count;
struct _GenericVirtualCase *next;
} GenericVirtualCase;
/*
* get_generic_virtual_entries:
*
* Return IMT entries for the generic virtual method instances and
* variant interface methods for vtable slot
* VTABLE_SLOT.
*/
static MonoImtBuilderEntry*
get_generic_virtual_entries (MonoMemoryManager *mem_manager, gpointer *vtable_slot)
{
MONO_REQ_GC_NEUTRAL_MODE;
GenericVirtualCase *list;
MonoImtBuilderEntry *entries;
mono_mem_manager_lock (mem_manager);
if (!mem_manager->generic_virtual_cases)
mem_manager->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
list = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
entries = NULL;
for (; list; list = list->next) {
MonoImtBuilderEntry *entry;
if (list->count < THUNK_THRESHOLD)
continue;
entry = g_new0 (MonoImtBuilderEntry, 1);
entry->key = list->method;
entry->value.target_code = mono_get_addr_from_ftnptr (list->code);
entry->has_target_code = 1;
if (entries)
entry->children = entries->children + 1;
entry->next = entries;
entries = entry;
}
mono_mem_manager_unlock (mem_manager);
/* FIXME: Leaking memory ? */
return entries;
}
/**
* \param domain a domain
* \param vtable_slot pointer to the vtable slot
* \param method the inflated generic virtual method
* \param code the method's code
*
* Registers a call via unmanaged code to a generic virtual method
* instantiation or variant interface method. If the number of calls reaches a threshold
* (THUNK_THRESHOLD), the method is added to the vtable slot's generic
* virtual method trampoline.
*/
void
mono_method_add_generic_virtual_invocation (MonoVTable *vtable,
gpointer *vtable_slot,
MonoMethod *method, gpointer code)
{
MONO_REQ_GC_NEUTRAL_MODE;
static gboolean inited = FALSE;
static int num_added = 0;
static int num_freed = 0;
GenericVirtualCase *gvc, *list;
MonoImtBuilderEntry *entries;
GPtrArray *sorted;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
mono_loader_lock ();
mono_mem_manager_lock (mem_manager);
if (!mem_manager->generic_virtual_cases)
mem_manager->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
if (!inited) {
mono_counters_register ("Generic virtual cases", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_added);
mono_counters_register ("Freed IMT trampolines", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_freed);
inited = TRUE;
}
/* Check whether the case was already added */
list = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
gvc = list;
while (gvc) {
if (gvc->method == method)
break;
gvc = gvc->next;
}
/* If not found, make a new one */
if (!gvc) {
gvc = (GenericVirtualCase *)m_class_alloc (vtable->klass, sizeof (GenericVirtualCase));
gvc->method = method;
gvc->code = code;
gvc->count = 0;
gvc->next = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
g_hash_table_insert (mem_manager->generic_virtual_cases, vtable_slot, gvc);
num_added++;
}
mono_mem_manager_unlock (mem_manager);
if (++gvc->count == THUNK_THRESHOLD) {
gpointer *old_thunk = (void **)*vtable_slot;
gpointer vtable_trampoline = NULL;
gpointer imt_trampoline = NULL;
if ((gpointer)vtable_slot < (gpointer)vtable) {
int displacement = (gpointer*)vtable_slot - (gpointer*)vtable;
int imt_slot = MONO_IMT_SIZE + displacement;
/* Force the rebuild of the trampoline at the next call */
imt_trampoline = callbacks.get_imt_trampoline (vtable, imt_slot);
*vtable_slot = imt_trampoline;
} else {
vtable_trampoline = callbacks.get_vtable_trampoline ? callbacks.get_vtable_trampoline (vtable, (gpointer*)vtable_slot - (gpointer*)vtable->vtable) : NULL;
entries = get_generic_virtual_entries (mem_manager, vtable_slot);
sorted = imt_sort_slot_entries (entries);
*vtable_slot = imt_trampoline_builder (vtable, (MonoIMTCheckItem**)sorted->pdata, sorted->len,
vtable_trampoline);
while (entries) {
MonoImtBuilderEntry *next = entries->next;
g_free (entries);
entries = next;
}
for (int i = 0; i < sorted->len; ++i)
g_free (g_ptr_array_index (sorted, i));
g_ptr_array_free (sorted, TRUE);
if (old_thunk != vtable_trampoline && old_thunk != imt_trampoline)
num_freed ++;
}
}
mono_loader_unlock ();
}
static MonoVTable *mono_class_create_runtime_vtable (MonoClass *klass, MonoError *error);
/**
* mono_class_vtable:
* \param domain the application domain
* \param class the class to initialize
* VTables are domain specific because we create domain specific code, and
* they contain the domain specific static class data.
* On failure, NULL is returned, and \c class->exception_type is set.
*/
MonoVTable *
mono_class_vtable (MonoDomain *domain, MonoClass *klass)
{
MonoVTable* vtable;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
vtable = mono_class_vtable_checked (klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return vtable;
}
/**
* mono_class_vtable_checked:
* \param class the class to initialize
* \param error set on failure.
* VTables are domain specific because we create domain specific code, and
* they contain the domain specific static class data.
*/
MonoVTable *
mono_class_vtable_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
error_init (error);
g_assert (klass);
if (mono_class_has_failure (klass)) {
mono_error_set_for_class_failure (error, klass);
return NULL;
}
vtable = m_class_get_runtime_vtable (klass);
if (vtable)
return vtable;
return mono_class_create_runtime_vtable (klass, error);
}
/**
* mono_class_try_get_vtable:
* \param class the class to initialize
* This function tries to get the associated vtable from \p class if
* it was already created.
*/
MonoVTable *
mono_class_try_get_vtable (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoVTable *vtable;
g_assert (klass);
vtable = m_class_get_runtime_vtable (klass);
if (vtable)
return vtable;
return NULL;
}
static gpointer*
alloc_vtable (MonoClass *klass, size_t vtable_size, size_t imt_table_bytes)
{
MONO_REQ_GC_NEUTRAL_MODE;
size_t alloc_offset;
/*
* We want the pointer to the MonoVTable aligned to 8 bytes because SGen uses three
* address bits. The IMT has an odd number of entries, however, so on 32 bits the
* alignment will be off. In that case we allocate 4 more bytes and skip over them.
*/
if (sizeof (gpointer) == 4 && (imt_table_bytes & 7)) {
g_assert ((imt_table_bytes & 7) == 4);
vtable_size += 4;
alloc_offset = 4;
} else {
alloc_offset = 0;
}
return (gpointer*) ((char*)m_class_alloc0 (klass, vtable_size) + alloc_offset);
}
static MonoVTable *
mono_class_create_runtime_vtable (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoVTable *vt;
MonoClassField *field;
MonoMemoryManager *mem_manager;
char *t;
int i, vtable_slots;
size_t imt_table_bytes;
int gc_bits;
guint32 vtable_size, class_size;
gpointer iter;
gpointer *interface_offsets;
gboolean is_primitive_type_array = FALSE;
gboolean use_interpreter = callbacks.is_interpreter_enabled ();
MonoDomain *domain = mono_get_root_domain ();
mono_loader_lock ();
vt = m_class_get_runtime_vtable (klass);
if (vt) {
mono_loader_unlock ();
goto exit;
}
if (!m_class_is_inited (klass) || mono_class_has_failure (klass)) {
if (!mono_class_init_internal (klass) || mono_class_has_failure (klass)) {
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
}
/* Array types require that their element type be valid*/
if (m_class_get_byval_arg (klass)->type == MONO_TYPE_ARRAY || m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY) {
MonoClass *element_class = m_class_get_element_class (klass);
is_primitive_type_array = m_class_is_primitive (element_class);
if (!m_class_is_inited (element_class))
mono_class_init_internal (element_class);
/*mono_class_init_internal can leave the vtable layout to be lazily done and we can't afford this here*/
if (!mono_class_has_failure (element_class) && !m_class_get_vtable_size (element_class))
mono_class_setup_vtable (element_class);
if (mono_class_has_failure (element_class)) {
/*Can happen if element_class only got bad after mono_class_setup_vtable*/
if (!mono_class_has_failure (klass))
mono_class_set_type_load_failure (klass, "");
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
}
/*
* For some classes, mono_class_init_internal () already computed klass->vtable_size, and
* that is all that is needed because of the vtable trampolines.
*/
if (!m_class_get_vtable_size (klass))
mono_class_setup_vtable (klass);
if (mono_class_is_ginst (klass) && !m_class_get_vtable (klass))
mono_class_check_vtable_constraints (klass, NULL);
/* Initialize klass->has_finalize */
mono_class_has_finalizer (klass);
if (mono_class_has_failure (klass)) {
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
vtable_slots = m_class_get_vtable_size (klass);
/* we add an additional vtable slot to store the pointer to static field data only when needed */
class_size = mono_class_data_size (klass);
if (class_size)
vtable_slots++;
if (m_class_get_interface_offsets_count (klass)) {
imt_table_bytes = sizeof (gpointer) * (MONO_IMT_SIZE);
/* Interface table for the interpreter */
if (use_interpreter)
imt_table_bytes *= 2;
UnlockedIncrement (&mono_stats.imt_number_of_tables);
UnlockedAdd (&mono_stats.imt_tables_size, imt_table_bytes);
} else {
imt_table_bytes = 0;
}
vtable_size = imt_table_bytes + MONO_SIZEOF_VTABLE + vtable_slots * sizeof (gpointer);
UnlockedIncrement (&mono_stats.used_class_count);
UnlockedAdd (&mono_stats.class_vtable_size, vtable_size);
interface_offsets = alloc_vtable (klass, vtable_size, imt_table_bytes);
vt = (MonoVTable*) ((char*)interface_offsets + imt_table_bytes);
/* If on interp, skip the interp interface table */
if (use_interpreter)
interface_offsets = (gpointer*)((char*)interface_offsets + imt_table_bytes / 2);
g_assert (!((gsize)vt & 7));
vt->klass = klass;
vt->rank = m_class_get_rank (klass);
vt->domain = domain;
if ((vt->rank > 0) || klass == mono_get_string_class ())
vt->flags |= MONO_VT_FLAG_ARRAY_OR_STRING;
if (m_class_has_references (klass))
vt->flags |= MONO_VT_FLAG_HAS_REFERENCES;
if (is_primitive_type_array)
vt->flags |= MONO_VT_FLAG_ARRAY_IS_PRIMITIVE;
MONO_PROFILER_RAISE (vtable_loading, (vt));
mono_class_compute_gc_descriptor (klass);
vt->gc_descr = m_class_get_gc_descr (klass);
gc_bits = mono_gc_get_vtable_bits (klass);
g_assert (!(gc_bits & ~((1 << MONO_VTABLE_AVAILABLE_GC_BITS) - 1)));
vt->gc_bits = gc_bits;
if (class_size) {
/* we store the static field pointer at the end of the vtable: vt->vtable [class->vtable_size] */
if (m_class_has_static_refs (klass)) {
MonoGCDescriptor statics_gc_descr;
int max_set = 0;
gsize default_bitmap [4] = {0};
gsize *bitmap;
bitmap = compute_class_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, TRUE);
/*g_print ("bitmap 0x%x for %s.%s (size: %d)\n", bitmap [0], klass->name_space, klass->name, class_size);*/
statics_gc_descr = mono_gc_make_descr_from_bitmap (bitmap, max_set + 1);
vt->vtable [m_class_get_vtable_size (klass)] = mono_gc_alloc_fixed (class_size, statics_gc_descr, MONO_ROOT_SOURCE_STATIC, vt, "Static Fields");
if (bitmap != default_bitmap)
g_free (bitmap);
} else {
vt->vtable [m_class_get_vtable_size (klass)] = m_class_alloc0 (klass, class_size);
}
vt->has_static_fields = TRUE;
UnlockedAdd (&mono_stats.class_static_data_size, class_size);
}
mem_manager = m_class_get_mem_manager (klass);
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (mono_field_is_deleted (field))
continue;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) {
gint32 special_static = m_class_has_no_special_static_fields (klass) ? SPECIAL_STATIC_NONE : field_is_special_static (klass, field);
if (special_static != SPECIAL_STATIC_NONE) {
guint32 size, offset;
gint32 align;
gsize default_bitmap [4] = {0};
gsize *bitmap;
int max_set = 0;
int numbits;
MonoClass *fclass;
if (mono_type_is_reference (field->type)) {
default_bitmap [0] = 1;
numbits = 1;
bitmap = default_bitmap;
} else if (mono_type_is_struct (field->type)) {
fclass = mono_class_from_mono_type_internal (field->type);
bitmap = compute_class_bitmap (fclass, default_bitmap, sizeof (default_bitmap) * 8, - (int)(MONO_OBJECT_HEADER_BITS), &max_set, FALSE);
numbits = max_set + 1;
} else {
default_bitmap [0] = 0;
numbits = 0;
bitmap = default_bitmap;
}
size = mono_type_size (field->type, &align);
offset = mono_alloc_special_static_data (special_static, size, align, (uintptr_t*)bitmap, numbits);
mono_mem_manager_lock (mem_manager);
if (!mem_manager->special_static_fields)
mem_manager->special_static_fields = g_hash_table_new (NULL, NULL);
g_hash_table_insert (mem_manager->special_static_fields, field, GUINT_TO_POINTER (offset));
mono_mem_manager_unlock (mem_manager);
if (bitmap != default_bitmap)
g_free (bitmap);
/*
* This marks the field as special static to speed up the
* checks in mono_field_static_get/set_value ().
*/
field->offset = -1;
continue;
}
}
if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
MonoClass *fklass = mono_class_from_mono_type_internal (field->type);
const char *data = mono_field_get_data (field);
g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT));
t = (char*)mono_static_field_get_addr (vt, field);
/* some fields don't really have rva, they are just zeroed (bss? bug #343083) */
if (!data)
continue;
if (m_class_is_valuetype (fklass)) {
memcpy (t, data, mono_class_value_size (fklass, NULL));
} else {
/* it's a pointer type: add check */
g_assert ((m_class_get_byval_arg (fklass)->type == MONO_TYPE_PTR) || (m_class_get_byval_arg (fklass)->type == MONO_TYPE_FNPTR));
*t = *(char *)data;
}
continue;
}
}
vt->max_interface_id = m_class_get_max_interface_id (klass);
vt->interface_bitmap = m_class_get_interface_bitmap (klass);
//printf ("Initializing VT for class %s (interface_offsets_count = %d)\n",
// class->name, klass->interface_offsets_count);
/* Initialize vtable */
if (callbacks.get_vtable_trampoline) {
// This also covers the AOT case
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
vt->vtable [i] = callbacks.get_vtable_trampoline (vt, i);
}
} else {
mono_class_setup_vtable (klass);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm;
cm = m_class_get_vtable (klass) [i];
if (cm) {
vt->vtable [i] = callbacks.create_jit_trampoline (cm, error);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
}
}
}
if (imt_table_bytes) {
/* Now that the vtable is full, we can actually fill up the IMT */
for (i = 0; i < MONO_IMT_SIZE; ++i)
interface_offsets [i] = callbacks.get_imt_trampoline (vt, i);
}
/*
* FIXME: Is it ok to allocate while holding the domain/loader locks ? If not, we can release them, allocate, then
* re-acquire them and check if another thread has created the vtable in the meantime.
*/
/* Special case System.MonoType to avoid infinite recursion */
if (!mono_runtime_get_no_exec () && klass != mono_defaults.runtimetype_class) {
MonoReflectionTypeHandle vt_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error);
vt->type = MONO_HANDLE_RAW (vt_type);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
if (mono_handle_class (vt_type) != mono_defaults.runtimetype_class)
/* This is unregistered in
unregister_vtable_reflection_type() in
domain.c. */
MONO_GC_REGISTER_ROOT_IF_MOVING (vt->type, MONO_ROOT_SOURCE_REFLECTION, vt, "Reflection Type Object");
}
/* class_vtable_array keeps an array of created vtables
*/
mono_mem_manager_lock (mem_manager);
g_ptr_array_add (mem_manager->class_vtable_array, vt);
mono_mem_manager_unlock (mem_manager);
/*
* Store the vtable in klass_vtable.
* klass->runtime_vtable is accessed without locking, so this do this last after the vtable has been constructed.
*/
mono_memory_barrier ();
mono_class_set_runtime_vtable (klass, vt);
if (!mono_runtime_get_no_exec () && klass == mono_defaults.runtimetype_class) {
MonoReflectionTypeHandle vt_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error);
vt->type = MONO_HANDLE_RAW (vt_type);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
if (mono_handle_class (vt_type) != mono_defaults.runtimetype_class)
/* This is unregistered in
unregister_vtable_reflection_type() in
domain.c. */
MONO_GC_REGISTER_ROOT_IF_MOVING(vt->type, MONO_ROOT_SOURCE_REFLECTION, vt, "Reflection Type Object");
}
mono_loader_unlock ();
/* make sure the parent is initialized */
/*FIXME shouldn't this fail the current type?*/
if (m_class_get_parent (klass))
mono_class_vtable_checked (m_class_get_parent (klass), error);
MONO_PROFILER_RAISE (vtable_loaded, (vt));
goto exit;
return_null:
vt = NULL;
exit:
HANDLE_FUNCTION_RETURN_VAL (vt);
}
/**
* mono_class_field_is_special_static:
* \returns whether \p field is a thread/context static field.
*/
gboolean
mono_class_field_is_special_static (MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return FALSE;
if (mono_field_is_deleted (field))
return FALSE;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) {
if (field_is_special_static (m_field_get_parent (field), field) != SPECIAL_STATIC_NONE)
return TRUE;
}
return FALSE;
}
/**
* mono_class_field_get_special_static_type:
* \param field The \c MonoClassField describing the field.
* \returns \c SPECIAL_STATIC_THREAD if the field is thread static, \c SPECIAL_STATIC_CONTEXT if it is context static,
* \c SPECIAL_STATIC_NONE otherwise.
*/
guint32
mono_class_field_get_special_static_type (MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return SPECIAL_STATIC_NONE;
if (mono_field_is_deleted (field))
return SPECIAL_STATIC_NONE;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
return field_is_special_static (m_field_get_parent (field), field);
return SPECIAL_STATIC_NONE;
}
/**
* mono_class_has_special_static_fields:
* \returns whether \p klass has any thread/context static fields.
*/
gboolean
mono_class_has_special_static_fields (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE
MonoClassField *field;
gpointer iter;
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
g_assert (m_field_get_parent (field) == klass);
if (mono_class_field_is_special_static (field))
return TRUE;
}
return FALSE;
}
MonoMethod*
mono_object_get_virtual_method_internal (MonoObject *obj_raw, MonoMethod *method)
{
HANDLE_FUNCTION_ENTER ();
MonoMethod *result;
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
result = mono_object_handle_get_virtual_method (obj, method, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/**
* mono_object_get_virtual_method:
* \param obj object to operate on.
* \param method method
* Retrieves the \c MonoMethod that would be called on \p obj if \p obj is passed as
* the instance of a callvirt of \p method.
*/
MonoMethod*
mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoMethod*, mono_object_get_virtual_method_internal (obj, method));
}
/**
* mono_object_handle_get_virtual_method:
* \param obj object to operate on.
* \param method method
* Retrieves the \c MonoMethod that would be called on \p obj if \p obj is passed as
* the instance of a callvirt of \p method.
*/
MonoMethod*
mono_object_handle_get_virtual_method (MonoObjectHandle obj, MonoMethod *method, MonoError *error)
{
error_init (error);
MonoClass *klass = mono_handle_class (obj);
return mono_class_get_virtual_method (klass, method, error);
}
MonoMethod*
mono_class_get_virtual_method (MonoClass *klass, MonoMethod *method, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
error_init (error);
if (((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)))
return method;
mono_class_setup_vtable (klass);
MonoMethod **vtable = m_class_get_vtable (klass);
if (method->slot == -1) {
/* method->slot might not be set for instances of generic methods */
if (method->is_inflated) {
g_assert (((MonoMethodInflated*)method)->declaring->slot != -1);
method->slot = ((MonoMethodInflated*)method)->declaring->slot;
} else {
g_assert_not_reached ();
}
}
MonoMethod *res = NULL;
/* check method->slot is a valid index: perform isinstance? */
if (method->slot != -1) {
if (mono_class_is_interface (method->klass)) {
gboolean variance_used = FALSE;
int iface_offset = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
g_assert (iface_offset > 0);
res = vtable [iface_offset + method->slot];
} else {
res = vtable [method->slot];
}
}
{
if (method->is_inflated) {
/* Have to inflate the result */
res = mono_class_inflate_generic_method_checked (res, &((MonoMethodInflated*)method)->context, error);
}
}
return res;
}
static MonoObject*
do_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *result = NULL;
g_assert (callbacks.runtime_invoke);
error_init (error);
MONO_PROFILER_RAISE (method_begin_invoke, (method));
result = callbacks.runtime_invoke (method, obj, params, exc, error);
MONO_PROFILER_RAISE (method_end_invoke, (method));
if (!is_ok (error))
return NULL;
return result;
}
/**
* mono_runtime_invoke:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* Invokes the method represented by \p method on the object \p obj.
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* \c mono_runtime_invoke variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
{
MonoObject *res;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
if (exc) {
res = mono_runtime_try_invoke (method, obj, params, exc, error);
if (*exc == NULL && !is_ok(error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else
mono_error_cleanup (error);
} else {
res = mono_runtime_invoke_checked (method, obj, params, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return res;
}
/**
* mono_runtime_try_invoke:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* \param error set on error
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* For this function, you must not pass NULL as the \p exc argument if
* you don't want to catch exceptions, use
* mono_runtime_invoke_checked(). If an exception is thrown, you
* can't use the \c MonoObject* result from the function.
*
* If this method cannot be invoked, \p error will be set and \p exc and
* the return value must not be used.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_try_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError* error)
{
MONO_REQ_GC_UNSAFE_MODE;
g_assert (exc != NULL);
if (mono_runtime_get_no_exec ())
g_warning ("Invoking method '%s' when running in no-exec mode.\n", mono_method_full_name (method, TRUE));
return do_runtime_invoke (method, obj, params, exc, error);
}
MonoObjectHandle
mono_runtime_try_invoke_handle (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
// FIXME? typing of params
MonoException *exc = NULL;
MonoObject *obj_raw = mono_runtime_try_invoke (method, MONO_HANDLE_RAW (obj), params, (MonoObject**)&exc, error);
if (exc && is_ok (error))
mono_error_set_exception_instance (error, exc);
return MONO_HANDLE_NEW (MonoObject, obj_raw);
}
/**
* mono_runtime_invoke_checked:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param error set on error
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* If an exception is thrown, you can't use the \c MonoObject* result
* from the function.
*
* If this method cannot be invoked, \p error will be set. If the
* method throws an exception (and we're in coop mode) the exception
* will be set in \p error.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_checked (MonoMethod *method, void *obj, void **params, MonoError* error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (mono_runtime_get_no_exec ())
g_error ("Invoking method '%s' when running in no-exec mode.\n", mono_method_full_name (method, TRUE));
return do_runtime_invoke (method, obj, params, NULL, error);
}
MonoObjectHandle
mono_runtime_invoke_handle (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
return MONO_HANDLE_NEW (MonoObject, mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (obj), params, error));
}
void
mono_runtime_invoke_handle_void (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (obj), params, error);
}
/**
* mono_method_get_unmanaged_thunk:
* \param method method to generate a thunk for.
*
* Returns an \c unmanaged->managed thunk that can be used to call
* a managed method directly from C.
*
* The thunk's C signature closely matches the managed signature:
*
* C#: <code>public bool Equals (object obj);</code>
*
* C: <code>typedef MonoBoolean (*Equals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* The 1st (<code>this</code>) parameter must not be used with static methods:
*
* C#: <code>public static bool ReferenceEquals (object a, object b);</code>
*
* C: <code>typedef MonoBoolean (*ReferenceEquals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* The last argument must be a non-null \c MonoException* pointer.
* It has "out" semantics. After invoking the thunk, \c *ex will be NULL if no
* exception has been thrown in managed code. Otherwise it will point
* to the \c MonoException* caught by the thunk. In this case, the result of
* the thunk is undefined:
*
* <pre>
* MonoMethod *method = ... // MonoMethod* of System.Object.Equals
*
* MonoException *ex = NULL;
*
* Equals func = mono_method_get_unmanaged_thunk (method);
*
* MonoBoolean res = func (thisObj, objToCompare, &ex);
*
* if (ex) {
*
* // handle exception
*
* }
* </pre>
*
* The calling convention of the thunk matches the platform's default
* convention. This means that under Windows, C declarations must
* contain the \c __stdcall attribute:
*
* C: <code>typedef MonoBoolean (__stdcall *Equals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* LIMITATIONS
*
* Value type arguments and return values are treated as they were objects:
*
* C#: <code>public static Rectangle Intersect (Rectangle a, Rectangle b);</code>
* C: <code>typedef MonoObject* (*Intersect)(MonoObject*, MonoObject*, MonoException**);</code>
*
* Arguments must be properly boxed upon trunk's invocation, while return
* values must be unboxed.
*/
gpointer
mono_method_get_unmanaged_thunk (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE;
MONO_REQ_API_ENTRYPOINT;
ERROR_DECL (error);
gpointer res;
MONO_ENTER_GC_UNSAFE;
method = mono_marshal_get_thunk_invoke_wrapper (method);
res = mono_compile_method_checked (method, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return res;
}
void
mono_copy_value (MonoType *type, void *dest, void *value, int deref_pointer)
{
MONO_REQ_GC_UNSAFE_MODE;
int t;
if (m_type_is_byref (type)) {
/* object fields cannot be byref, so we don't need a
wbarrier here */
gpointer *p = (gpointer*)dest;
*p = value;
return;
}
t = type->type;
handle_enum:
switch (t) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1: {
guint8 *p = (guint8*)dest;
*p = value ? *(guint8*)value : 0;
return;
}
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR: {
guint16 *p = (guint16*)dest;
*p = value ? *(guint16*)value : 0;
return;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gint32 *p = (gint32*)dest;
*p = value ? *(gint32*)value : 0;
return;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
case MONO_TYPE_I8:
case MONO_TYPE_U8: {
gint64 *p = (gint64*)dest;
*p = value ? *(gint64*)value : 0;
return;
}
case MONO_TYPE_R4: {
float *p = (float*)dest;
*p = value ? *(float*)value : 0;
return;
}
case MONO_TYPE_R8: {
double *p = (double*)dest;
*p = value ? *(double*)value : 0;
return;
}
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
mono_gc_wbarrier_generic_store_internal (dest, deref_pointer ? *(MonoObject **)value : (MonoObject *)value);
return;
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR: {
gpointer *p = (gpointer*)dest;
*p = deref_pointer? *(gpointer*)value: value;
return;
}
case MONO_TYPE_VALUETYPE:
/* note that 't' and 'type->type' can be different */
if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass)) {
t = mono_class_enum_basetype_internal (type->data.klass)->type;
goto handle_enum;
} else {
MonoClass *klass = mono_class_from_mono_type_internal (type);
int size = mono_class_value_size (klass, NULL);
if (value == NULL)
mono_gc_bzero_atomic (dest, size);
else
mono_gc_wbarrier_value_copy_internal (dest, value, 1, klass);
}
return;
case MONO_TYPE_GENERICINST:
t = m_class_get_byval_arg (type->data.generic_class->container_class)->type;
goto handle_enum;
default:
g_error ("got type %x", type->type);
}
}
void
mono_field_set_value_internal (MonoObject *obj, MonoClassField *field, void *value)
{
void *dest;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return;
dest = (char*)obj + field->offset;
mono_copy_value (field->type, dest, value, value && field->type->type == MONO_TYPE_PTR);
}
/**
* mono_field_set_value:
* \param obj Instance object
* \param field \c MonoClassField describing the field to set
* \param value The value to be set
*
* Sets the value of the field described by \p field in the object instance \p obj
* to the value passed in \p value. This method should only be used for instance
* fields. For static fields, use \c mono_field_static_set_value.
*
* The value must be in the native format of the field type.
*/
void
mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_set_value_internal (obj, field, value));
}
void
mono_field_static_set_value_internal (MonoVTable *vt, MonoClassField *field, void *value)
{
void *dest;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC) == 0)
return;
/* you cant set a constant! */
if ((field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
return;
dest = mono_static_field_get_addr (vt, field);
mono_copy_value (field->type, dest, value, value && field->type->type == MONO_TYPE_PTR);
}
gpointer
mono_special_static_field_get_offset (MonoClassField *field, MonoError *error)
{
MonoMemoryManager *mem_manager = m_class_get_mem_manager (m_field_get_parent (field));
gpointer addr = NULL;
mono_mem_manager_lock (mem_manager);
if (mem_manager->special_static_fields)
addr = g_hash_table_lookup (mem_manager->special_static_fields, field);
mono_mem_manager_unlock (mem_manager);
return addr;
}
/**
* mono_field_static_set_value:
* \param field \c MonoClassField describing the field to set
* \param value The value to be set
* Sets the value of the static field described by \p field
* to the value passed in \p value.
* The value must be in the native format of the field type.
*/
void
mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_static_set_value_internal (vt, field, value));
}
/**
* mono_vtable_get_static_field_data:
*
* Internal use function: return a pointer to the memory holding the static fields
* for a class or NULL if there are no static fields.
* This is exported only for use by the debugger.
*/
void *
mono_vtable_get_static_field_data (MonoVTable *vt)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!vt->has_static_fields)
return NULL;
return vt->vtable [m_class_get_vtable_size (vt->klass)];
}
static guint8*
mono_field_get_addr (MonoObject *obj, MonoVTable *vt, MonoClassField *field)
{
MONO_REQ_GC_UNSAFE_MODE;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
return mono_static_field_get_addr (vt, field);
else
return (guint8*)obj + field->offset;
}
guint8*
mono_static_field_get_addr (MonoVTable *vt, MonoClassField *field)
{
MONO_REQ_GC_UNSAFE_MODE;
guint8 *src;
g_assert (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
if (field->offset == -1) {
if (G_UNLIKELY (m_field_is_from_update (field))) {
return mono_metadata_update_get_static_field_addr (field);
}
/* Special static */
ERROR_DECL (error);
gpointer addr = mono_special_static_field_get_offset (field, error);
mono_error_assert_ok (error);
src = (guint8 *)mono_get_special_static_data (GPOINTER_TO_UINT (addr));
} else {
src = (guint8*)mono_vtable_get_static_field_data (vt) + field->offset;
}
return src;
}
/**
* mono_field_get_value:
* \param obj Object instance
* \param field \c MonoClassField describing the field to fetch information from
* \param value pointer to the location where the value will be stored
* Use this routine to get the value of the field \p field in the object
* passed.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
*
* <pre>
* int i;
*
* mono_field_get_value (obj, int_field, &i);
* </pre>
*/
void
mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_get_value_internal (obj, field, value));
}
void
mono_field_get_value_internal (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_REQ_GC_UNSAFE_MODE;
void *src;
g_assert (obj);
g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
src = (char*)obj + field->offset;
mono_copy_value (field->type, value, src, TRUE);
}
/**
* mono_field_get_value_object:
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed.
*/
MonoObject *
mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObject *obj)
{
MonoObject* result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_field_get_value_object_checked (field, obj, error);
mono_error_assert_ok (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_static_field_get_value_handle:
* \param domain domain where the object will be created (if boxing)
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed.
*/
MonoObjectHandle
mono_static_field_get_value_handle (MonoClassField *field, MonoError *error)
// FIXMEcoop invert
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_REF (MonoObject, MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (field, NULL, error)));
}
/**
* mono_field_get_value_object_checked:
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \param error Set on error.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed. On error returns NULL and sets \p error.
*/
MonoObject *
mono_field_get_value_object_checked (MonoClassField *field, MonoObject *obj, MonoError *error)
{
// FIXMEcoop
HANDLE_FUNCTION_ENTER ();
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoObject *o = NULL;
MonoClass *klass;
MonoVTable *vtable = NULL;
gpointer v;
gboolean is_static = FALSE;
gboolean is_ref = FALSE;
gboolean is_literal = FALSE;
gboolean is_ptr = FALSE;
MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL);
MonoType *type = mono_field_get_type_checked (field, error);
goto_if_nok (error, return_null);
switch (type->type) {
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
is_ref = TRUE;
break;
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_VALUETYPE:
is_ref = m_type_is_byref (type);
break;
case MONO_TYPE_GENERICINST:
is_ref = !mono_type_generic_inst_is_valuetype (type);
break;
case MONO_TYPE_PTR:
is_ptr = TRUE;
break;
default:
g_error ("type 0x%x not handled in "
"mono_field_get_value_object", type->type);
goto return_null;
}
if (type->attrs & FIELD_ATTRIBUTE_LITERAL)
is_literal = TRUE;
if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
is_static = TRUE;
if (!is_literal) {
vtable = mono_class_vtable_checked (m_field_get_parent (field), error);
goto_if_nok (error, return_null);
if (!vtable->initialized) {
mono_runtime_class_init_full (vtable, error);
goto_if_nok (error, return_null);
}
}
} else {
g_assert (obj);
}
if (is_ref) {
if (is_literal) {
get_default_field_value (field, &o, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, &o, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, &o);
}
goto exit;
}
if (is_ptr) {
gpointer args [2];
gpointer *ptr;
MONO_STATIC_POINTER_INIT (MonoMethod, m)
MonoClass *ptr_klass = mono_class_get_pointer_class ();
m = mono_class_get_method_from_name_checked (ptr_klass, "Box", 2, METHOD_ATTRIBUTE_STATIC, error);
goto_if_nok (error, return_null);
g_assert (m);
MONO_STATIC_POINTER_INIT_END (MonoMethod, m)
v = &ptr;
if (is_literal) {
get_default_field_value (field, v, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, v, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, v);
}
args [0] = ptr;
args [1] = mono_type_get_object_checked (type, error);
goto_if_nok (error, return_null);
o = mono_runtime_invoke_checked (m, NULL, args, error);
goto_if_nok (error, return_null);
goto exit;
}
/* boxed value type */
klass = mono_class_from_mono_type_internal (type);
if (mono_class_is_nullable (klass)) {
o = mono_nullable_box (mono_field_get_addr (obj, vtable, field), klass, error);
goto exit;
}
o = mono_object_new_checked (klass, error);
goto_if_nok (error, return_null);
v = mono_object_get_data (o);
if (is_literal) {
get_default_field_value (field, v, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, v, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, v);
}
goto exit;
return_null:
o = NULL;
exit:
HANDLE_FUNCTION_RETURN_VAL (o);
}
/*
* Important detail, if type is MONO_TYPE_STRING we return a blob encoded string (ie, utf16 + leb128 prefixed size)
*/
gboolean
mono_metadata_read_constant_value (const char *blob, MonoTypeEnum type, void *value, MonoError *error)
{
error_init (error);
gboolean retval = TRUE;
const char *p = blob;
mono_metadata_decode_blob_size (p, &p);
switch (type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*(guint8 *) value = *p;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
*(guint16*) value = read16 (p);
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
*(guint32*) value = read32 (p);
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
*(guint64*) value = read64 (p);
break;
case MONO_TYPE_R4:
readr4 (p, (float*) value);
break;
case MONO_TYPE_R8:
readr8 (p, (double*) value);
break;
case MONO_TYPE_STRING:
*(const char**) value = blob;
break;
case MONO_TYPE_CLASS:
*(gpointer*) value = NULL;
break;
default:
retval = FALSE;
mono_error_set_execution_engine (error, "Type 0x%02x should not be in constant table", type);
}
return retval;
}
gboolean
mono_get_constant_value_from_blob (MonoTypeEnum type, const char *blob, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXMEcoop excess frame, but mono_ldstr_metadata_sig does allocate a handle.
HANDLE_FUNCTION_ENTER ();
gboolean result = FALSE;
if (!mono_metadata_read_constant_value (blob, type, value, error))
goto exit;
if (type == MONO_TYPE_STRING) {
mono_ldstr_metadata_sig (*(const char**)value, string_handle, error);
*(gpointer*)value = MONO_HANDLE_RAW (string_handle);
}
result = TRUE;
exit:
HANDLE_FUNCTION_RETURN_VAL (result);
}
static void
get_default_field_value (MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoTypeEnum def_type;
const char* data;
error_init (error);
data = mono_class_get_field_default_value (field, &def_type);
(void)mono_get_constant_value_from_blob (def_type, data, value, string_handle, error);
}
void
mono_field_static_get_value_for_thread (MonoInternalThread *thread, MonoVTable *vt, MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
void *src;
error_init (error);
g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL) {
get_default_field_value (field, value, string_handle, error);
return;
}
src = mono_static_field_get_addr (vt, field);
mono_copy_value (field->type, value, src, TRUE);
}
/**
* mono_field_static_get_value:
* \param vt vtable to the object
* \param field \c MonoClassField describing the field to fetch information from
* \param value where the value is returned
* Use this routine to get the value of the static field \p field value.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
*
* <pre>
* int i;
*
* mono_field_static_get_value (vt, int_field, &i);
* </pre>
*/
void
mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
{
MONO_REQ_GC_NEUTRAL_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
mono_field_static_get_value_checked (vt, field, value, MONO_HANDLE_NEW (MonoString, NULL), error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN ();
}
/**
* mono_field_static_get_value_checked:
* \param vt vtable to the object
* \param field \c MonoClassField describing the field to fetch information from
* \param value where the value is returned
* \param error set on error
* Use this routine to get the value of the static field \p field value.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
* int i;
* mono_field_static_get_value_checked (vt, int_field, &i, error);
* if (!is_ok (error)) { ... }
*
* On failure sets \p error.
*/
void
mono_field_static_get_value_checked (MonoVTable *vt, MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
mono_field_static_get_value_for_thread (mono_thread_internal_current (), vt, field, value, string_handle, error);
}
/**
* mono_property_set_value:
* \param prop MonoProperty to set
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param exc optional exception
* Invokes the property's set method with the given arguments on the
* object instance obj (or NULL for static properties).
*
* You can pass NULL as the exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
void
mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
{
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
do_runtime_invoke (prop->set, obj, params, exc, error);
if (exc && *exc == NULL && !is_ok (error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else {
mono_error_cleanup (error);
}
MONO_EXIT_GC_UNSAFE;
}
/**
* mono_property_set_value_handle:
* \param prop \c MonoProperty to set
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param error set on error
* Invokes the property's set method with the given arguments on the
* object instance \p obj (or NULL for static properties).
* \returns TRUE on success. On failure returns FALSE and sets \p error.
* If an exception is thrown, it will be caught and returned via \p error.
*/
gboolean
mono_property_set_value_handle (MonoProperty *prop, MonoObjectHandle obj, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *exc;
error_init (error);
do_runtime_invoke (prop->set, MONO_HANDLE_RAW (obj), params, &exc, error);
if (exc != NULL && is_ok (error))
mono_error_set_exception_instance (error, (MonoException*)exc);
return is_ok (error);
}
/**
* mono_property_get_value:
* \param prop \c MonoProperty to fetch
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param exc optional exception
* Invokes the property's \c get method with the given arguments on the
* object instance \p obj (or NULL for static properties).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* \returns the value from invoking the \c get method on the property.
*/
MonoObject*
mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
{
MonoObject *val;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
val = do_runtime_invoke (prop->get, obj, params, exc, error);
if (exc && *exc == NULL && !is_ok (error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else {
mono_error_cleanup (error); /* FIXME don't raise here */
}
MONO_EXIT_GC_UNSAFE;
return val;
}
/**
* mono_property_get_value_checked:
* \param prop \c MonoProperty to fetch
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param error set on error
* Invokes the property's \c get method with the given arguments on the
* object instance obj (or NULL for static properties).
*
* If an exception is thrown, you can't use the
* \c MonoObject* result from the function. The exception will be propagated via \p error.
*
* \returns the value from invoking the get method on the property. On
* failure returns NULL and sets \p error.
*/
MonoObject*
mono_property_get_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *exc;
MonoObject *val = do_runtime_invoke (prop->get, obj, params, &exc, error);
if (exc != NULL && !is_ok (error))
mono_error_set_exception_instance (error, (MonoException*) exc);
if (!is_ok (error))
val = NULL;
return val;
}
static MonoClassField*
nullable_class_get_value_field (MonoClass *klass)
{
mono_class_setup_fields (klass);
g_assert (m_class_is_fields_inited (klass));
MonoClassField *klass_fields = m_class_get_fields (klass);
return &klass_fields [1];
}
static MonoClassField*
nullable_class_get_has_value_field (MonoClass *klass)
{
mono_class_setup_fields (klass);
g_assert (m_class_is_fields_inited (klass));
MonoClassField *klass_fields = m_class_get_fields (klass);
return &klass_fields [0];
}
static gpointer
nullable_get_has_value_field_addr (guint8 *nullable, MonoClass *klass)
{
MonoClassField *has_value_field = nullable_class_get_has_value_field (klass);
return mono_vtype_get_field_addr (nullable, has_value_field);
}
static gpointer
nullable_get_value_field_addr (guint8 *nullable, MonoClass *klass)
{
MonoClassField *has_value_field = nullable_class_get_value_field (klass);
return mono_vtype_get_field_addr (nullable, has_value_field);
}
/*
* mono_nullable_init:
* @buf: The nullable structure to initialize.
* @value: the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*/
void
mono_nullable_init (guint8 *buf, MonoObject *value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
*(guint8*)(has_value_field_addr) = value ? 1 : 0;
if (value) {
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (value_field_addr, mono_object_unbox_internal (value), 1, param_class);
else
mono_gc_memmove_atomic (value_field_addr, mono_object_unbox_internal (value), mono_class_value_size (param_class, NULL));
} else {
mono_gc_bzero_atomic (value_field_addr, mono_class_value_size (param_class, NULL));
}
}
/*
* mono_nullable_init_from_handle:
* @buf: The nullable structure to initialize.
* @value: the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*/
void
mono_nullable_init_from_handle (guint8 *buf, MonoObjectHandle value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!MONO_HANDLE_IS_NULL (value)) {
MonoGCHandle value_gchandle = NULL;
gpointer src = mono_object_handle_pin_unbox (value, &value_gchandle);
mono_nullable_init_unboxed (buf, src, klass);
mono_gchandle_free_internal (value_gchandle);
} else {
mono_nullable_init_unboxed (buf, NULL, klass);
}
}
/*
* mono_nullable_init_unboxed
*
* @buf: The nullable structure to initialize.
* @value: the unboxed address of the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*
* This function expects all objects to be pinned or for
* MONO_ENTER_NO_SAFEPOINTS to be used in a caller.
*/
void
mono_nullable_init_unboxed (guint8 *buf, gpointer value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
*(guint8*)(has_value_field_addr) = (value == NULL) ? 0 : 1;
if (value) {
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (value_field_addr, value, 1, param_class);
else
mono_gc_memmove_atomic (value_field_addr, value, mono_class_value_size (param_class, NULL));
} else {
mono_gc_bzero_atomic (value_field_addr, mono_class_value_size (param_class, NULL));
}
}
/**
* mono_nullable_box:
* \param buf The buffer representing the data to be boxed
* \param klass the type to box it as.
* \param error set on error
*
* Creates a boxed vtype or NULL from the \c Nullable structure pointed to by
* \p buf. On failure returns NULL and sets \p error.
*/
MonoObject*
mono_nullable_box (gpointer vbuf, MonoClass *klass, MonoError *error)
{
guint8 *buf = (guint8*)vbuf;
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
g_assertf (!m_class_is_byreflike (param_class), "Unexpected Nullable<%s> - generic type instantiated with IsByRefLike type", mono_type_get_full_name (param_class));
if (*(guint8*)(has_value_field_addr)) {
MonoObject *o = mono_object_new_checked (param_class, error);
return_val_if_nok (error, NULL);
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (mono_object_unbox_internal (o), value_field_addr, 1, param_class);
else
mono_gc_memmove_atomic (mono_object_unbox_internal (o), value_field_addr, mono_class_value_size (param_class, NULL));
return o;
}
else
return NULL;
}
MonoObjectHandle
mono_nullable_box_handle (gpointer buf, MonoClass *klass, MonoError *error)
{
// FIXMEcoop gpointer buf needs more attention
return MONO_HANDLE_NEW (MonoObject, mono_nullable_box (buf, klass, error));
}
MonoMethod *
mono_get_delegate_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c Invoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_invoke_internal (klass));
}
/**
* mono_get_delegate_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c Invoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "Invoke", -1, 0, error);
return im;
}
MonoMethod *
mono_get_delegate_begin_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_begin_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_begin_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c BeginInvoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_begin_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_begin_invoke_internal (klass));
}
/**
* mono_get_delegate_begin_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c BeginInvoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_begin_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "BeginInvoke", -1, 0, error);
return im;
}
MonoMethod *
mono_get_delegate_end_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_end_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_end_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c EndInvoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_end_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_end_invoke_internal (klass));
}
/**
* mono_get_delegate_end_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c EndInvoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_end_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "EndInvoke", -1, 0, error);
return im;
}
/**
* mono_runtime_delegate_invoke:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param exc Pointer to the exception result.
*
* Invokes the delegate method \p delegate with the parameters provided.
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
MonoObject*
mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
{
ERROR_DECL (error);
MonoObject* result = NULL;
MONO_ENTER_GC_UNSAFE;
if (exc) {
result = mono_runtime_delegate_try_invoke (delegate, params, exc, error);
if (*exc) {
mono_error_cleanup (error);
result = NULL;
} else {
if (!is_ok (error))
*exc = (MonoObject*)mono_error_convert_to_exception (error);
}
} else {
result = mono_runtime_delegate_invoke_checked (delegate, params, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_runtime_delegate_try_invoke:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param exc Pointer to the exception result.
* \param error set on error
* Invokes the delegate method \p delegate with the parameters provided.
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. On failure to execute, \p error will be set.
* if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
MonoObject*
mono_runtime_delegate_try_invoke (MonoObject *delegate, void **params, MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoMethod *im;
MonoClass *klass = delegate->vtable->klass;
MonoObject *o;
im = mono_get_delegate_invoke_internal (klass);
g_assertf (im, "Could not lookup delegate invoke method for delegate %s", mono_type_get_full_name (klass));
if (exc) {
o = mono_runtime_try_invoke (im, delegate, params, exc, error);
} else {
o = mono_runtime_invoke_checked (im, delegate, params, error);
}
return o;
}
static MonoObjectHandle
mono_runtime_delegate_try_invoke_handle (MonoObjectHandle delegate, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = MONO_HANDLE_GETVAL (delegate, vtable)->klass;
MonoMethod* const im = mono_get_delegate_invoke_internal (klass);
g_assertf (im, "Could not lookup delegate invoke method for delegate %s", mono_type_get_full_name (klass));
return mono_runtime_try_invoke_handle (im, delegate, params, error);
}
/**
* mono_runtime_delegate_invoke_checked:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param error set on error
* Invokes the delegate method \p delegate with the parameters provided.
* On failure \p error will be set and you can't use the \c MonoObject*
* result from the function.
*/
MonoObject*
mono_runtime_delegate_invoke_checked (MonoObject *delegate, void **params, MonoError *error)
{
error_init (error);
return mono_runtime_delegate_try_invoke (delegate, params, NULL, error);
}
static char **main_args = NULL;
static int num_main_args = 0;
/**
* mono_runtime_get_main_args:
* \returns A \c MonoArray with the arguments passed to the main program
*/
MonoArray*
mono_runtime_get_main_args (void)
{
HANDLE_FUNCTION_ENTER ();
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
error_init (error);
MonoArrayHandle arg_array = mono_runtime_get_main_args_handle (error);
goto_if_nok (error, leave);
MONO_HANDLE_ASSIGN (result, arg_array);
leave:
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static gboolean
handle_main_arg_array_set (int idx, MonoArrayHandle dest, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
error_init (error);
MonoStringHandle value = mono_string_new_handle (main_args [idx], error);
goto_if_nok (error, leave);
MONO_HANDLE_ARRAY_SETREF (dest, idx, value);
leave:
HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
}
/**
* mono_runtime_get_main_args_handle:
* \param error set on error
* \returns a \c MonoArray with the arguments passed to the main
* program. On failure returns NULL and sets \p error.
*/
MonoArrayHandle
mono_runtime_get_main_args_handle (MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle array;
int i;
error_init (error);
array = mono_array_new_handle (mono_defaults.string_class, num_main_args, error);
if (!is_ok (error)) {
array = MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
goto leave;
}
for (i = 0; i < num_main_args; ++i) {
if (!handle_main_arg_array_set (i, array, error))
goto leave;
}
leave:
HANDLE_FUNCTION_RETURN_REF (MonoArray, array);
}
static void
free_main_args (void)
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
for (i = 0; i < num_main_args; ++i)
g_free (main_args [i]);
g_free (main_args);
num_main_args = 0;
main_args = NULL;
}
/**
* mono_runtime_set_main_args:
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* Set the command line arguments from an embedding application that doesn't otherwise call
* \c mono_runtime_run_main.
*/
int
mono_runtime_set_main_args (int argc, char* argv[])
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
free_main_args ();
main_args = g_new0 (char*, argc);
num_main_args = argc;
for (i = 0; i < argc; ++i) {
gchar *utf8_arg;
utf8_arg = mono_utf8_from_external (argv[i]);
if (utf8_arg == NULL) {
g_print ("\nCannot determine the text encoding for argument %d (%s).\n", i, argv [i]);
exit (-1);
}
main_args [i] = utf8_arg;
}
MONO_EXTERNAL_ONLY (int, 0);
}
/*
* Prepare an array of arguments in order to execute a standard Main()
* method (argc/argv contains the executable name). This method also
* sets the command line argument value needed by System.Environment.
*
*/
static MonoArray*
prepare_run_main (MonoMethod *method, int argc, char *argv[])
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
int i;
MonoArray *args = NULL;
gchar *utf8_fullpath;
MonoMethodSignature *sig;
g_assert (method != NULL);
mono_thread_set_main (mono_thread_current ());
main_args = g_new0 (char*, argc);
num_main_args = argc;
if (!g_path_is_absolute (argv [0])) {
gchar *basename = g_path_get_basename (argv [0]);
gchar *fullpath = g_build_filename (m_class_get_image (method->klass)->assembly->basedir,
basename,
(const char*)NULL);
utf8_fullpath = mono_utf8_from_external (fullpath);
if(utf8_fullpath == NULL) {
/* Printing the arg text will cause glib to
* whinge about "Invalid UTF-8", but at least
* its relevant, and shows the problem text
* string.
*/
g_print ("\nCannot determine the text encoding for the assembly location: %s\n", fullpath);
exit (-1);
}
g_free (fullpath);
g_free (basename);
} else {
utf8_fullpath = mono_utf8_from_external (argv[0]);
if(utf8_fullpath == NULL) {
g_print ("\nCannot determine the text encoding for the assembly location: %s\n", argv[0]);
exit (-1);
}
}
main_args [0] = utf8_fullpath;
for (i = 1; i < argc; ++i) {
gchar *utf8_arg;
utf8_arg=mono_utf8_from_external (argv[i]);
if(utf8_arg==NULL) {
/* Ditto the comment about Invalid UTF-8 here */
g_print ("\nCannot determine the text encoding for argument %d (%s).\n", i, argv[i]);
exit (-1);
}
main_args [i] = utf8_arg;
}
argc--;
argv++;
sig = mono_method_signature_internal (method);
if (!sig) {
g_print ("Unable to load Main method.\n");
exit (-1);
}
if (sig->param_count) {
args = (MonoArray*)mono_array_new_checked (mono_defaults.string_class, argc, error);
mono_error_assert_ok (error);
for (i = 0; i < argc; ++i) {
/* The encodings should all work, given that
* we've checked all these args for the
* main_args array.
*/
gchar *str = mono_utf8_from_external (argv [i]);
MonoString *arg = mono_string_new_checked (str, error);
mono_error_assert_ok (error);
mono_array_setref_internal (args, i, arg);
g_free (str);
}
} else {
args = (MonoArray*)mono_array_new_checked (mono_defaults.string_class, 0, error);
mono_error_assert_ok (error);
}
mono_assembly_set_main (m_class_get_image (method->klass)->assembly);
return args;
}
/**
* mono_runtime_run_main:
* \param method the method to start the application with (usually <code>Main</code>)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param exc excetption results
* Execute a standard \c Main method (\p argc / \p argv contains the
* executable name). This method also sets the command line argument value
* needed by \c System.Environment.
*/
int
mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
MonoObject **exc)
{
int res;
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MONO_ENTER_GC_UNSAFE;
MonoArray *args = prepare_run_main (method, argc, argv);
if (exc)
res = mono_runtime_try_exec_main (method, args, exc);
else
res = mono_runtime_exec_main_checked (method, args, error);
MONO_EXIT_GC_UNSAFE;
if (!exc)
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a better alternative */
return res;
}
/**
* mono_runtime_run_main_checked:
* \param method the method to start the application with (usually \c Main)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param error set on error
*
* Execute a standard \c Main method (\p argc / \p argv contains the
* executable name). This method also sets the command line argument value
* needed by \c System.Environment. On failure sets \p error.
*/
int
mono_runtime_run_main_checked (MonoMethod *method, int argc, char* argv[],
MonoError *error)
{
error_init (error);
MonoArray *args = prepare_run_main (method, argc, argv);
return mono_runtime_exec_main_checked (method, args, error);
}
/**
* mono_runtime_try_run_main:
* \param method the method to start the application with (usually \c Main)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param exc set if \c Main throws an exception
* \param error set if \c Main can't be executed
* Execute a standard \c Main method (\p argc / \p argv contains the executable
* name). This method also sets the command line argument value needed
* by \c System.Environment. On failure sets \p error if Main can't be
* executed or \p exc if it threw an exception.
*/
int
mono_runtime_try_run_main (MonoMethod *method, int argc, char* argv[],
MonoObject **exc)
{
g_assert (exc);
MonoArray *args = prepare_run_main (method, argc, argv);
return mono_runtime_try_exec_main (method, args, exc);
}
MonoObjectHandle
mono_new_null (void) // A code size optimization (source and object).
{
return MONO_HANDLE_NEW (MonoObject, NULL);
}
/* Used in call_unhandled_exception_delegate */
static MonoObjectHandle
create_unhandled_exception_eventargs (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass * const klass = mono_class_get_unhandled_exception_event_args_class ();
mono_class_init_internal (klass);
/* UnhandledExceptionEventArgs only has 1 public ctor with 2 args */
MonoMethod * const method = mono_class_get_method_from_name_checked (klass, ".ctor", 2, METHOD_ATTRIBUTE_PUBLIC, error);
goto_if_nok (error, return_null);
g_assert (method);
{
MonoBoolean is_terminating = TRUE;
gpointer args [ ] = {
MONO_HANDLE_RAW (exc), // FIXMEcoop (ok as long as handles are pinning)
&is_terminating
};
MonoObjectHandle obj = mono_object_new_handle (klass, error);
goto_if_nok (error, return_null);
mono_runtime_invoke_handle_void (method, obj, args, error);
goto_if_nok (error, return_null);
return obj;
}
return_null:
return MONO_HANDLE_NEW (MonoObject, NULL);
}
void
mono_unhandled_exception_internal (MonoObject *exc_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, exc);
mono_unhandled_exception_checked (exc, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN ();
}
/**
* mono_unhandled_exception:
* \param exc exception thrown
* This is a VM internal routine.
*
* We call this function when we detect an unhandled exception
* in the default domain.
*
* It invokes the \c UnhandledException event in \c AppDomain or prints
* a warning to the console
*/
void
mono_unhandled_exception (MonoObject *exc)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_unhandled_exception_internal (exc));
}
static MonoObjectHandle
create_first_chance_exception_eventargs (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle obj;
MonoClass *klass = mono_class_get_first_chance_exception_event_args_class ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (klass, ".ctor", 1, METHOD_ATTRIBUTE_PUBLIC, error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
goto_if_nok (error, return_null);
g_assert (ctor);
gpointer args [1];
args [0] = MONO_HANDLE_RAW (exc);
obj = mono_object_new_handle (klass, error);
goto_if_nok (error, return_null);
mono_runtime_invoke_handle_void (ctor, obj, args, error);
goto_if_nok (error, return_null);
goto leave;
return_null:
obj = MONO_HANDLE_NEW (MonoObject, NULL);
leave:
HANDLE_FUNCTION_RETURN_REF (MonoObject, obj);
}
void
mono_first_chance_exception_internal (MonoObject *exc_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, exc);
mono_first_chance_exception_checked (exc, error);
if (!is_ok (error))
g_warning ("Invoking the FirstChanceException event failed: %s", mono_error_get_message (error));
HANDLE_FUNCTION_RETURN ();
}
void
mono_first_chance_exception_checked (MonoObjectHandle exc, MonoError *error)
{
MonoClass *klass = mono_handle_class (exc);
MonoDomain *domain = mono_domain_get ();
MonoObject *delegate = NULL;
MonoObjectHandle delegate_handle;
if (klass == mono_defaults.threadabortexception_class)
return;
MONO_STATIC_POINTER_INIT (MonoClassField, field)
static gboolean inited;
if (!inited) {
field = mono_class_get_field_from_name_full (mono_defaults.appcontext_class, "FirstChanceException", NULL);
inited = TRUE;
}
MONO_STATIC_POINTER_INIT_END (MonoClassField, field)
if (!field)
return;
MonoVTable *vt = mono_class_vtable_checked (mono_defaults.appcontext_class, error);
return_if_nok (error);
// TODO: use handles directly
mono_field_static_get_value_checked (vt, field, &delegate, MONO_HANDLE_NEW (MonoString, NULL), error);
return_if_nok (error);
delegate_handle = MONO_HANDLE_NEW (MonoObject, delegate);
if (MONO_HANDLE_BOOL (delegate_handle)) {
gpointer args [2];
args [0] = domain->domain;
args [1] = MONO_HANDLE_RAW (create_first_chance_exception_eventargs (exc, error));
mono_error_assert_ok (error);
mono_runtime_delegate_try_invoke_handle (delegate_handle, args, error);
}
}
/**
* mono_unhandled_exception_checked:
* @exc: exception thrown
*
* This is a VM internal routine.
*
* We call this function when we detect an unhandled exception
* in the default domain.
*
* It invokes the * UnhandledException event in AppDomain or prints
* a warning to the console
*/
void
mono_unhandled_exception_checked (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoDomain *current_domain = mono_domain_get ();
MonoClass *klass = mono_handle_class (exc);
/*
* AppDomainUnloadedException don't behave like unhandled exceptions unless thrown from
* a thread started in unmanaged world.
* https://msdn.microsoft.com/en-us/library/system.appdomainunloadedexception(v=vs.110).aspx#Anchor_6
*/
gboolean no_event = (klass == mono_defaults.threadabortexception_class);
if (no_event)
return;
MONO_STATIC_POINTER_INIT (MonoClassField, field)
static gboolean inited;
if (!inited) {
field = mono_class_get_field_from_name_full (mono_defaults.appcontext_class, "UnhandledException", NULL);
inited = TRUE;
}
MONO_STATIC_POINTER_INIT_END (MonoClassField, field)
if (!field)
goto leave;
MonoObject *delegate = NULL;
MonoObjectHandle delegate_handle;
MonoVTable *vt = mono_class_vtable_checked (mono_defaults.appcontext_class, error);
goto_if_nok (error, leave);
// TODO: use handles directly
mono_field_static_get_value_checked (vt, field, &delegate, MONO_HANDLE_NEW (MonoString, NULL), error);
goto_if_nok (error, leave);
delegate_handle = MONO_HANDLE_NEW (MonoObject, delegate);
if (MONO_HANDLE_IS_NULL (delegate_handle)) {
mono_print_unhandled_exception_internal (MONO_HANDLE_RAW (exc)); // TODO: use handles
} else {
gpointer args [2];
args [0] = current_domain->domain;
args [1] = MONO_HANDLE_RAW (create_unhandled_exception_eventargs (exc, error));
mono_error_assert_ok (error);
mono_runtime_delegate_try_invoke_handle (delegate_handle, args, error);
}
leave:
/* set exitcode if we will abort the process */
mono_environment_exitcode_set (1);
}
/**
* mono_runtime_exec_managed_code:
* \param domain Application domain
* \param main_func function to invoke from the execution thread
* \param main_args parameter to the main_func
* Launch a new thread to execute a function
*
* \p main_func is called back from the thread with main_args as the
* parameter. The callback function is expected to start \c Main
* eventually. This function then waits for all managed threads to
* finish.
* It is not necessary anymore to execute managed code in a subthread,
* so this function should not be used anymore by default: just
* execute the code and then call mono_thread_manage().
*/
void
mono_runtime_exec_managed_code (MonoDomain *domain,
MonoMainThreadFunc mfunc,
gpointer margs)
{
// This function is external_only.
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
mono_thread_create_checked ((MonoThreadStart)mfunc, margs, error);
mono_error_assert_ok (error);
mono_thread_manage_internal ();
MONO_EXIT_GC_UNSAFE;
}
static void
prepare_thread_to_exec_main (MonoMethod *method)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoInternalThread* thread = mono_thread_internal_current ();
MonoCustomAttrInfo* cinfo;
gboolean has_stathread_attribute;
if (!mono_runtime_get_entry_assembly ())
mono_runtime_ensure_entry_assembly (m_class_get_image (method->klass)->assembly);
ERROR_DECL (cattr_error);
cinfo = mono_custom_attrs_from_method_checked (method, cattr_error);
mono_error_cleanup (cattr_error); /* FIXME warn here? */
if (cinfo) {
has_stathread_attribute = mono_custom_attrs_has_attr (cinfo, mono_class_get_sta_thread_attribute_class ());
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
has_stathread_attribute = FALSE;
}
if (has_stathread_attribute) {
thread->apartment_state = ThreadApartmentState_STA;
} else {
thread->apartment_state = ThreadApartmentState_MTA;
}
mono_thread_init_apartment_state ();
mono_thread_init_from_native ();
}
static int
do_exec_main_checked (MonoMethod *method, MonoArray *args, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
gpointer pa [1];
int rval;
error_init (error);
g_assert (args);
pa [0] = args;
/* FIXME: check signature of method */
if (mono_method_signature_internal (method)->ret->type == MONO_TYPE_I4) {
MonoObject *res;
res = mono_runtime_invoke_checked (method, NULL, pa, error);
if (is_ok (error))
rval = *(guint32 *)(mono_object_get_data (res));
else
rval = -1;
mono_environment_exitcode_set (rval);
} else {
mono_runtime_invoke_checked (method, NULL, pa, error);
if (is_ok (error))
rval = 0;
else {
rval = -1;
}
}
return rval;
}
static int
do_try_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
MONO_REQ_GC_UNSAFE_MODE;
gpointer pa [1];
int rval;
g_assert (args);
g_assert (exc);
pa [0] = args;
/* FIXME: check signature of method */
if (mono_method_signature_internal (method)->ret->type == MONO_TYPE_I4) {
ERROR_DECL (inner_error);
MonoObject *res;
res = mono_runtime_try_invoke (method, NULL, pa, exc, inner_error);
if (*exc == NULL && !is_ok (inner_error))
*exc = (MonoObject*) mono_error_convert_to_exception (inner_error);
else
mono_error_cleanup (inner_error);
if (*exc == NULL)
rval = *(guint32 *)(mono_object_get_data (res));
else
rval = -1;
mono_environment_exitcode_set (rval);
} else {
ERROR_DECL (inner_error);
mono_runtime_try_invoke (method, NULL, pa, exc, inner_error);
if (*exc == NULL && !is_ok (inner_error))
*exc = (MonoObject*) mono_error_convert_to_exception (inner_error);
else
mono_error_cleanup (inner_error);
if (*exc == NULL)
rval = 0;
else {
/* If the return type of Main is void, only
* set the exitcode if an exception was thrown
* (we don't want to blow away an
* explicitly-set exit code)
*/
rval = -1;
mono_environment_exitcode_set (rval);
}
}
return rval;
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*/
int
mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
int rval;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
prepare_thread_to_exec_main (method);
if (exc) {
rval = do_try_exec_main (method, args, exc);
} else {
rval = do_exec_main_checked (method, args, error);
// FIXME Maybe change mode back here?
mono_error_raise_exception_deprecated (error); /* OK to throw, external only with no better option */
}
MONO_EXIT_GC_UNSAFE;
return rval;
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*
* On failure sets @error
*/
int
mono_runtime_exec_main_checked (MonoMethod *method, MonoArray *args, MonoError *error)
{
error_init (error);
prepare_thread_to_exec_main (method);
return do_exec_main_checked (method, args, error);
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*
* On failure sets @error if Main couldn't be executed, or @exc if it threw an exception.
*/
int
mono_runtime_try_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
prepare_thread_to_exec_main (method);
return do_try_exec_main (method, args, exc);
}
/** invoke_span_extract_argument:
* @params: span of object arguments to the method.
* @i: the index of the argument to extract.
* @t: ith type from the method signature.
* @has_byref_nullables: outarg - TRUE if method expects a byref nullable argument
* @error: set on error.
*
* Given an array of method arguments, return the ith one using the corresponding type
* to perform necessary unboxing. If method expects a ref nullable argument, writes TRUE to @has_byref_nullables.
*
* On failure sets @error and returns NULL.
*/
static gpointer
invoke_span_extract_argument (MonoSpanOfObjects *params_span, int i, MonoType *t, MonoObject **pa_obj, gboolean* has_byref_nullables, MonoError *error)
{
MonoType *t_orig = t;
gpointer result = NULL;
*pa_obj = NULL;
error_init (error);
again:
switch (t->type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_VALUETYPE:
if (t->type == MONO_TYPE_VALUETYPE && mono_class_is_nullable (mono_class_from_mono_type_internal (t_orig))) {
/* The runtime invoke wrapper needs the original boxed vtype, it does handle byref values as well. */
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = *pa_obj;
if (m_type_is_byref (t))
*has_byref_nullables = TRUE;
} else {
/* MS seems to create the objects if a null is passed in */
gboolean was_null = FALSE;
if (!mono_span_get (params_span, MonoObject*, i)) {
MonoObject *o = mono_object_new_checked (mono_class_from_mono_type_internal (t_orig), error);
return_val_if_nok (error, NULL);
mono_span_setref (params_span, i, o);
was_null = TRUE;
}
if (m_type_is_byref (t)) {
/*
* We can't pass the unboxed vtype byref to the callee, since
* that would mean the callee would be able to modify boxed
* primitive types. So we (and MS) make a copy of the boxed
* object, pass that to the callee, and replace the original
* boxed object in the arg array with the copy.
*/
MonoObject *orig = mono_span_get (params_span, MonoObject*, i);
MonoObject *copy = mono_value_box_checked (orig->vtable->klass, mono_object_unbox_internal (orig), error);
return_val_if_nok (error, NULL);
mono_span_setref (params_span, i, copy);
}
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = mono_object_unbox_internal (*pa_obj);
if (!m_type_is_byref (t) && was_null)
mono_span_setref (params_span, i, NULL);
}
break;
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
if (m_type_is_byref (t)) {
result = mono_span_addr (params_span, MonoObject*, i);
// FIXME: I need to check this code path
} else {
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = *pa_obj;
}
break;
case MONO_TYPE_GENERICINST:
if (m_type_is_byref (t))
t = m_class_get_this_arg (t->data.generic_class->container_class);
else
t = m_class_get_byval_arg (t->data.generic_class->container_class);
goto again;
case MONO_TYPE_PTR: {
MonoObject *arg;
/* The argument should be an IntPtr */
arg = mono_span_get (params_span, MonoObject*, i);
if (arg == NULL) {
result = NULL;
} else {
g_assert (arg->vtable->klass == mono_defaults.int_class);
result = ((MonoIntPtr*)arg)->m_value;
}
break;
}
default:
g_error ("type 0x%x not handled in mono_runtime_invoke_array", t_orig->type);
}
return result;
}
/**
* mono_runtime_invoke_array:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
MonoObject **exc)
{
MonoObject *res;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
if (exc) {
res = mono_runtime_try_invoke_array (method, obj, params, exc, error);
if (*exc) {
res = NULL;
mono_error_cleanup (error);
} else if (!is_ok (error)) {
*exc = (MonoObject*)mono_error_convert_to_exception (error);
}
} else {
res = mono_runtime_try_invoke_array (method, obj, params, NULL, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return res;
}
static MonoObject*
mono_runtime_try_invoke_span (MonoMethod *method, void *obj, MonoSpanOfObjects *params_span,
MonoObject **exc, MonoError *error)
{
error_init (error);
MonoMethodSignature *sig = mono_method_signature_internal (method);
gpointer *pa = NULL;
MonoObject *res = NULL;
int i;
gboolean has_byref_nullables = FALSE;
int params_length = mono_span_length (params_span);
if (params_length > 0) {
pa = g_newa (gpointer, params_length);
for (i = 0; i < params_length; i++) {
MonoType *t = sig->params [i];
MonoObject *pa_obj;
pa [i] = invoke_span_extract_argument (params_span, i, t, &pa_obj, &has_byref_nullables, error);
if (pa_obj)
MONO_HANDLE_PIN (pa_obj);
goto_if_nok (error, exit_null);
}
}
if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
void *o = obj;
if (mono_class_is_nullable (method->klass)) {
/* Need to create a boxed vtype instead */
g_assert (!obj);
if (params_length == 0) {
goto_if_nok (error, exit_null);
} else {
res = mono_value_box_checked (m_class_get_cast_class (method->klass), pa [0], error);
goto exit;
}
}
if (!obj) {
MonoObjectHandle obj_h = mono_object_new_handle (method->klass, error);
goto_if_nok (error, exit_null);
obj = MONO_HANDLE_RAW (obj_h);
g_assert (obj); /*maybe we should raise a TLE instead?*/
if (m_class_is_valuetype (method->klass))
o = (MonoObject *)mono_object_unbox_internal ((MonoObject *)obj);
else
o = obj;
} else if (m_class_is_valuetype (method->klass)) {
MonoObjectHandle obj_h = mono_value_box_handle (method->klass, obj, error);
goto_if_nok (error, exit_null);
obj = MONO_HANDLE_RAW (obj_h);
}
if (exc) {
mono_runtime_try_invoke (method, o, pa, exc, error);
} else {
mono_runtime_invoke_checked (method, o, pa, error);
}
res = (MonoObject*)obj;
} else {
if (mono_class_is_nullable (method->klass)) {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
obj = NULL;
} else {
/* Convert the unboxed vtype into a Nullable structure */
MonoObjectHandle nullable_h = mono_object_new_handle (method->klass, error);
goto_if_nok (error, exit_null);
MonoObject* nullable = MONO_HANDLE_RAW (nullable_h);
MonoObjectHandle boxed_h = mono_value_box_handle (m_class_get_cast_class (method->klass), obj, error);
goto_if_nok (error, exit_null);
mono_nullable_init ((guint8 *)mono_object_unbox_internal (nullable), MONO_HANDLE_RAW (boxed_h), method->klass);
obj = mono_object_unbox_internal (nullable);
}
}
/* obj must be already unboxed if needed */
if (exc) {
res = mono_runtime_try_invoke (method, obj, pa, exc, error);
} else {
res = mono_runtime_invoke_checked (method, obj, pa, error);
}
MONO_HANDLE_PIN (res);
goto_if_nok (error, exit_null);
if (sig->ret->type == MONO_TYPE_PTR) {
MonoClass *pointer_class;
void *box_args [2];
MonoObject *box_exc;
/*
* The runtime-invoke wrapper returns a boxed IntPtr, need to
* convert it to a Pointer object.
*/
pointer_class = mono_class_get_pointer_class ();
MONO_STATIC_POINTER_INIT (MonoMethod, box_method)
box_method = mono_class_get_method_from_name_checked (pointer_class, "Box", -1, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, box_method)
if (res) {
g_assert (res->vtable->klass == mono_defaults.int_class);
box_args [0] = ((MonoIntPtr*)res)->m_value;
} else {
box_args [0] = NULL;
}
if (m_type_is_byref (sig->ret)) {
// byref is already unboxed by the invoke code
MonoType *tmpret = mono_metadata_type_dup (NULL, sig->ret);
tmpret->byref__ = FALSE;
MonoReflectionTypeHandle type_h = mono_type_get_object_handle (tmpret, error);
box_args [1] = MONO_HANDLE_RAW (type_h);
mono_metadata_free_type (tmpret);
} else {
MonoReflectionTypeHandle type_h = mono_type_get_object_handle (sig->ret, error);
box_args [1] = MONO_HANDLE_RAW (type_h);
}
goto_if_nok (error, exit_null);
res = mono_runtime_try_invoke (box_method, NULL, box_args, &box_exc, error);
g_assert (box_exc == NULL);
mono_error_assert_ok (error);
}
}
goto exit;
exit_null:
res = NULL;
exit:
return res;
}
/**
* mono_runtime_invoke_array_checked:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param error set on failure.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params span contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the \p params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* On failure or exception, \p error will be set. In that case, you
* can't use the \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_span_checked (MonoMethod *method, void *obj, MonoSpanOfObjects *params,
MonoError *error)
{
error_init (error);
return mono_runtime_try_invoke_span (method, obj, params, NULL, error);
}
/**
* mono_runtime_try_invoke_array:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* \param error set on failure.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to catch
* exceptions, otherwise, \c *exc will be set to the exception thrown, if
* any. On other failures, \p error will be set. If an exception is
* thrown or there's an error, you can't use the \c MonoObject* result
* from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_try_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoSpanOfObjects params_span = mono_span_create_from_object_array (params);
MonoObject *res = mono_runtime_try_invoke_span (method, obj, ¶ms_span, exc, error);
HANDLE_FUNCTION_RETURN_VAL (res);
}
// FIXME these will move to header soon
static MonoObjectHandle
mono_object_new_by_vtable (MonoVTable *vtable, MonoError *error);
/**
* object_new_common_tail:
*
* This function centralizes post-processing of objects upon creation.
* i.e. calling mono_object_register_finalizer and mono_gc_register_obj_with_weak_fields,
* and setting error.
*/
static MonoObject*
object_new_common_tail (MonoObject *o, MonoClass *klass, MonoError *error)
{
error_init (error);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (klass));
return o;
}
if (G_UNLIKELY (m_class_has_finalize (klass)))
mono_object_register_finalizer (o);
if (G_UNLIKELY (m_class_has_weak_fields (klass)))
mono_gc_register_obj_with_weak_fields (o);
return o;
}
/**
* object_new_handle_tail:
*
* This function centralizes post-processing of objects upon creation.
* i.e. calling mono_object_register_finalizer and mono_gc_register_obj_with_weak_fields.
*/
static MonoObjectHandle
object_new_handle_common_tail (MonoObjectHandle o, MonoClass *klass, MonoError *error)
{
error_init (error);
if (G_UNLIKELY (MONO_HANDLE_IS_NULL (o))) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (klass));
return o;
}
if (G_UNLIKELY (m_class_has_finalize (klass)))
mono_object_register_finalizer_handle (o);
if (G_UNLIKELY (m_class_has_weak_fields (klass)))
mono_gc_register_object_with_weak_fields (o);
return o;
}
/**
* mono_object_new:
* \param klass the class of the object that we want to create
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure.
*/
MonoObject *
mono_object_new (MonoDomain *domain, MonoClass *klass)
{
MonoObject * result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_object_new_checked (klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
MonoObject *
ves_icall_object_new (MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoObject * result = mono_object_new_checked (klass, error);
mono_error_set_pending_exception (error);
return result;
}
/**
* mono_object_new_checked:
* \param klass the class of the object that we want to create
* \param error set on error
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure and sets \p error.
*/
MonoObject *
mono_object_new_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
vtable = mono_class_vtable_checked (klass, error);
if (!is_ok (error))
return NULL;
MonoObject *o = mono_object_new_specific_checked (vtable, error);
return o;
}
/**
* mono_object_new_handle:
* \param klass the class of the object that we want to create
* \param error set on error
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure and sets \p error.
*/
MonoObjectHandle
mono_object_new_handle (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
return mono_object_new_by_vtable (vtable, error);
}
/**
* mono_object_new_pinned:
*
* Same as mono_object_new, but the returned object will be pinned.
*/
MonoObjectHandle
mono_object_new_pinned_handle (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
g_assert (vtable->klass == klass);
int const size = mono_class_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_pinned_obj (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
MonoObject *
mono_object_new_pinned (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, NULL);
MonoObject *o = mono_gc_alloc_pinned_obj (vtable, mono_class_instance_size (klass));
return object_new_common_tail (o, klass, error);
}
/**
* mono_object_new_specific:
* \param vtable the vtable of the object that we want to create
* \returns A newly created object with class and domain specified
* by \p vtable
*/
MonoObject *
mono_object_new_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_specific_checked (vtable, error);
mono_error_cleanup (error);
return o;
}
MonoObject *
mono_object_new_specific_checked (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *o;
error_init (error);
/* check for is_com_object for COM Interop */
if (mono_class_is_com_object (vtable->klass)) {
gpointer pa [1];
MonoMethod *im = create_proxy_for_type_method;
if (im == NULL) {
MonoClass *klass = mono_class_get_activation_services_class ();
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
im = mono_class_get_method_from_name_checked (klass, "CreateProxyForType", 1, 0, error);
return_val_if_nok (error, NULL);
if (!im) {
mono_error_set_not_supported (error, "Linked away.");
return NULL;
}
create_proxy_for_type_method = im;
}
pa [0] = mono_type_get_object_checked (m_class_get_byval_arg (vtable->klass), error);
if (!is_ok (error))
return NULL;
o = mono_runtime_invoke_checked (im, NULL, pa, error);
if (!is_ok (error))
return NULL;
if (o != NULL)
return o;
}
return mono_object_new_alloc_specific_checked (vtable, error);
}
static MonoObjectHandle
mono_object_new_by_vtable (MonoVTable *vtable, MonoError *error)
{
// This function handles remoting and COM.
// mono_object_new_alloc_by_vtable does not.
MONO_REQ_GC_UNSAFE_MODE;
MonoObjectHandle o = MONO_HANDLE_NEW (MonoObject, NULL);
error_init (error);
/* check for is_com_object for COM Interop */
if (mono_class_is_com_object (vtable->klass)) {
MonoMethod *im = create_proxy_for_type_method;
if (im == NULL) {
MonoClass *klass = mono_class_get_activation_services_class ();
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
im = mono_class_get_method_from_name_checked (klass, "CreateProxyForType", 1, 0, error);
return_val_if_nok (error, mono_new_null ());
if (!im) {
mono_error_set_not_supported (error, "Linked away.");
return MONO_HANDLE_NEW (MonoObject, NULL);
}
create_proxy_for_type_method = im;
}
// FIXMEcoop
gpointer pa[ ] = { mono_type_get_object_checked (m_class_get_byval_arg (vtable->klass), error) };
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
// FIXMEcoop
o = MONO_HANDLE_NEW (MonoObject, mono_runtime_invoke_checked (im, NULL, pa, error));
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
if (!MONO_HANDLE_IS_NULL (o))
return o;
}
return mono_object_new_alloc_by_vtable (vtable, error);
}
MonoObject *
ves_icall_object_new_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_specific_checked (vtable, error);
mono_error_set_pending_exception (error);
return o;
}
/**
* mono_object_new_alloc_specific:
* \param vtable virtual table for the object.
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. If the class of this object has a
* finalizer, then the object will be tracked for finalization.
*
* This method might raise an exception on errors. Use the
* \c mono_object_new_fast_checked method if you want to manually raise
* the exception.
*
* \returns the allocated object.
*/
MonoObject *
mono_object_new_alloc_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_alloc_specific_checked (vtable, error);
mono_error_cleanup (error);
return o;
}
/**
* mono_object_new_alloc_specific_checked:
* \param vtable virtual table for the object.
* \param error holds the error return value.
*
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. If the class of this object has a
* finalizer, then the object will be tracked for finalization.
*
* If there is not enough memory, the \p error parameter will be set
* and will contain a user-visible message with the amount of bytes
* that were requested.
*
* \returns the allocated object, or NULL if there is not enough memory
*/
MonoObject *
mono_object_new_alloc_specific_checked (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *o = mono_gc_alloc_obj (vtable, m_class_get_instance_size (vtable->klass));
return object_new_common_tail (o, vtable->klass, error);
}
MonoObjectHandle
mono_object_new_alloc_by_vtable (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = vtable->klass;
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_obj (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_object_new_fast:
* \param vtable virtual table for the object.
*
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. The returned object is not tracked
* for finalization. If your object implements a finalizer, you should
* use \c mono_object_new_alloc_specific instead.
*
* This method might raise an exception on errors. Use the
* \c mono_object_new_fast_checked method if you want to manually raise
* the exception.
*
* \returns the allocated object.
*/
MonoObject*
mono_object_new_fast (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_gc_alloc_obj (vtable, m_class_get_instance_size (vtable->klass));
// This deliberately skips object_new_common_tail.
if (G_UNLIKELY (!o))
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (vtable->klass));
mono_error_cleanup (error);
return o;
}
MonoObject*
mono_object_new_mature (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
int size;
size = m_class_get_instance_size (vtable->klass);
#if MONO_CROSS_COMPILE
/* In cross compile mode, we should only allocate thread objects */
/* The instance size refers to the target arch, this should be safe enough */
size *= 2;
#endif
MonoObject *o = mono_gc_alloc_mature (vtable, size);
return object_new_common_tail (o, vtable->klass, error);
}
MonoObjectHandle
mono_object_new_handle_mature (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = vtable->klass;
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_mature (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_object_new_from_token:
* \param image Context where the type_token is hosted
* \param token a token of the type that we want to create
* \returns A newly created object whose definition is
* looked up using \p token in the \p image image
*/
MonoObject *
mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoClass *klass;
klass = mono_class_get_checked (image, token, error);
mono_error_assert_ok (error);
MonoObjectHandle result = mono_object_new_handle (klass, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_clone:
* \param obj the object to clone
* \returns A newly created object who is a shallow copy of \p obj
*/
MonoObject *
mono_object_clone (MonoObject *obj)
{
ERROR_DECL (error);
MonoObject *o = mono_object_clone_checked (obj, error);
mono_error_cleanup (error);
return o;
}
MonoObject *
mono_object_clone_checked (MonoObject *obj_raw, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, obj);
HANDLE_FUNCTION_RETURN_OBJ (mono_object_clone_handle (obj, error));
}
MonoObjectHandle
mono_object_clone_handle (MonoObjectHandle obj, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = MONO_HANDLE_GETVAL (obj, vtable);
MonoClass* const klass = vtable->klass;
if (m_class_get_rank (klass))
return MONO_HANDLE_CAST (MonoObject, mono_array_clone_in_domain (MONO_HANDLE_CAST (MonoArray, obj), error));
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_obj (vtable, size);
if (G_LIKELY (!MONO_HANDLE_IS_NULL (o))) {
/* If the object doesn't contain references this will do a simple memmove. */
mono_gc_wbarrier_object_copy_handle (o, obj);
}
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_array_full_copy:
* \param src source array to copy
* \param dest destination array
* Copies the content of one array to another with exactly the same type and size.
*/
void
mono_array_full_copy (MonoArray *src, MonoArray *dest)
{
MONO_REQ_GC_UNSAFE_MODE;
uintptr_t size;
MonoClass *klass = mono_object_class (&src->obj);
g_assert (klass == mono_object_class (&dest->obj));
size = mono_array_length_internal (src);
g_assert (size == mono_array_length_internal (dest));
size *= mono_array_element_size (klass);
mono_array_full_copy_unchecked_size (src, dest, klass, size);
}
void
mono_array_full_copy_unchecked_size (MonoArray *src, MonoArray *dest, MonoClass *klass, uintptr_t size)
{
if (mono_gc_is_moving ()) {
MonoClass *element_class = m_class_get_element_class (klass);
if (m_class_is_valuetype (element_class)) {
if (m_class_has_references (element_class))
mono_value_copy_array_internal (dest, 0, mono_array_addr_with_size_fast (src, 0, 0), mono_array_length_internal (src));
else
mono_gc_memmove_atomic (&dest->vector, &src->vector, size);
} else {
mono_array_memcpy_refs_internal (dest, 0, src, 0, mono_array_length_internal (src));
}
} else {
mono_gc_memmove_atomic (&dest->vector, &src->vector, size);
}
}
/**
* mono_array_clone_in_domain:
* \param domain the domain in which the array will be cloned into
* \param array the array to clone
* \param error set on error
* This routine returns a copy of the array that is hosted on the
* specified \c MonoDomain. On failure returns NULL and sets \p error.
*/
MonoArrayHandle
mono_array_clone_in_domain (MonoArrayHandle array_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
uintptr_t size = 0;
MonoClass *klass = mono_handle_class (array_handle);
error_init (error);
/* Pin source array here - if bounds is non-NULL, it's a pointer into the object data */
MonoGCHandle src_handle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, array_handle), TRUE);
MonoArrayBounds *array_bounds = MONO_HANDLE_GETVAL (array_handle, bounds);
MonoArrayHandle o;
if (array_bounds == NULL) {
size = mono_array_handle_length (array_handle);
o = mono_array_new_full_handle (klass, &size, NULL, error);
goto_if_nok (error, leave);
size *= mono_array_element_size (klass);
} else {
guint8 klass_rank = m_class_get_rank (klass);
uintptr_t *sizes = g_newa (uintptr_t, klass_rank);
intptr_t *lower_bounds = g_newa (intptr_t, klass_rank);
size = mono_array_element_size (klass);
for (int i = 0; i < klass_rank; ++i) {
sizes [i] = array_bounds [i].length;
size *= array_bounds [i].length;
lower_bounds [i] = array_bounds [i].lower_bound;
}
o = mono_array_new_full_handle (klass, sizes, lower_bounds, error);
goto_if_nok (error, leave);
}
MonoGCHandle dst_handle;
dst_handle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, o), TRUE);
mono_array_full_copy_unchecked_size (MONO_HANDLE_RAW (array_handle), MONO_HANDLE_RAW (o), klass, size);
mono_gchandle_free_internal (dst_handle);
MONO_HANDLE_ASSIGN (result, o);
leave:
mono_gchandle_free_internal (src_handle);
return result;
}
/**
* mono_array_clone:
* \param array the array to clone
* \returns A newly created array who is a shallow copy of \p array
*/
MonoArray*
mono_array_clone (MonoArray *array)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoArray *result = mono_array_clone_checked (array, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_array_clone_checked:
* \param array the array to clone
* \param error set on error
* \returns A newly created array who is a shallow copy of \p array. On
* failure returns NULL and sets \p error.
*/
MonoArray*
mono_array_clone_checked (MonoArray *array_raw, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
/* FIXME: callers of mono_array_clone_checked should use handles */
error_init (error);
MONO_HANDLE_DCL (MonoArray, array);
MonoArrayHandle result = mono_array_clone_in_domain (array, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/* helper macros to check for overflow when calculating the size of arrays */
#ifdef MONO_BIG_ARRAYS
#define MYGUINT64_MAX 0x0000FFFFFFFFFFFFUL
#define MYGUINT_MAX MYGUINT64_MAX
#define CHECK_ADD_OVERFLOW_UN(a,b) \
(G_UNLIKELY ((guint64)(MYGUINT64_MAX) - (guint64)(b) < (guint64)(a)))
#define CHECK_MUL_OVERFLOW_UN(a,b) \
(G_UNLIKELY (((guint64)(a) > 0) && ((guint64)(b) > 0) && \
((guint64)(b) > ((MYGUINT64_MAX) / (guint64)(a)))))
#else
#define MYGUINT32_MAX 4294967295U
#define MYGUINT_MAX MYGUINT32_MAX
#define CHECK_ADD_OVERFLOW_UN(a,b) \
(G_UNLIKELY ((guint32)(MYGUINT32_MAX) - (guint32)(b) < (guint32)(a)))
#define CHECK_MUL_OVERFLOW_UN(a,b) \
(G_UNLIKELY (((guint32)(a) > 0) && ((guint32)(b) > 0) && \
((guint32)(b) > ((MYGUINT32_MAX) / (guint32)(a)))))
#endif
gboolean
mono_array_calc_byte_len (MonoClass *klass, uintptr_t len, uintptr_t *res)
{
MONO_REQ_GC_NEUTRAL_MODE;
uintptr_t byte_len;
byte_len = mono_array_element_size (klass);
if (CHECK_MUL_OVERFLOW_UN (byte_len, len))
return FALSE;
byte_len *= len;
if (CHECK_ADD_OVERFLOW_UN (byte_len, MONO_SIZEOF_MONO_ARRAY))
return FALSE;
byte_len += MONO_SIZEOF_MONO_ARRAY;
*res = byte_len;
return TRUE;
}
/**
* mono_array_new_full:
* \param domain domain where the object is created
* \param array_class array class
* \param lengths lengths for each dimension in the array
* \param lower_bounds lower bounds for each dimension in the array (may be NULL)
* This routine creates a new array object with the given dimensions,
* lower bounds and type.
*/
MonoArray*
mono_array_new_full (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds)
{
ERROR_DECL (error);
MonoArray *array = mono_array_new_full_checked (array_class, lengths, lower_bounds, error);
mono_error_cleanup (error);
return array;
}
MonoArray*
mono_array_new_full_checked (MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
uintptr_t byte_len = 0, len, bounds_size;
MonoObject *o;
MonoArray *array;
MonoArrayBounds *bounds;
MonoVTable *vtable;
int i;
error_init (error);
if (!m_class_is_inited (array_class))
mono_class_init_internal (array_class);
len = 1;
guint8 array_class_rank = m_class_get_rank (array_class);
/* A single dimensional array with a 0 lower bound is the same as an szarray */
if (array_class_rank == 1 && ((m_class_get_byval_arg (array_class)->type == MONO_TYPE_SZARRAY) || (lower_bounds && lower_bounds [0] == 0))) {
len = lengths [0];
if (len > MONO_ARRAY_MAX_INDEX) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
bounds_size = 0;
} else {
bounds_size = sizeof (MonoArrayBounds) * array_class_rank;
for (i = 0; i < array_class_rank; ++i) {
if (lengths [i] > MONO_ARRAY_MAX_INDEX) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
if (CHECK_MUL_OVERFLOW_UN (len, lengths [i])) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
len *= lengths [i];
}
}
if (!mono_array_calc_byte_len (array_class, len, &byte_len)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
if (bounds_size) {
/* align */
if (CHECK_ADD_OVERFLOW_UN (byte_len, 3)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
byte_len = (byte_len + 3) & ~3;
if (CHECK_ADD_OVERFLOW_UN (byte_len, bounds_size)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
byte_len += bounds_size;
}
/*
* Following three lines almost taken from mono_object_new ():
* they need to be kept in sync.
*/
vtable = mono_class_vtable_checked (array_class, error);
return_val_if_nok (error, NULL);
if (bounds_size)
o = (MonoObject *)mono_gc_alloc_array (vtable, byte_len, len, bounds_size);
else
o = (MonoObject *)mono_gc_alloc_vector (vtable, byte_len, len);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT "d bytes", (gsize) byte_len);
return NULL;
}
array = (MonoArray*)o;
bounds = array->bounds;
if (bounds_size) {
for (i = 0; i < array_class_rank; ++i) {
bounds [i].length = lengths [i];
if (lower_bounds)
bounds [i].lower_bound = lower_bounds [i];
}
}
return array;
}
static MonoArray*
mono_array_new_jagged_helper (MonoClass *klass, int n, uintptr_t *lengths, int index, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArray *ret = mono_array_new_full_checked (klass, &lengths [index], NULL, error);
goto_if_nok (error, exit);
MONO_HANDLE_PIN (ret);
if (index < (n - 1)) {
// We have a new dimension argument. This means the elements in the allocated array
// are also arrays and we allocate each one of them.
MonoClass *element_class = m_class_get_element_class (klass);
g_assert (m_class_get_rank (element_class) == 1);
for (int i = 0; i < lengths [index]; i++) {
MonoArray *o = mono_array_new_jagged_helper (element_class, n, lengths, index + 1, error);
goto_if_nok (error, exit);
mono_array_setref_fast (ret, i, o);
}
}
exit:
HANDLE_FUNCTION_RETURN_VAL (ret);
}
MonoArray *
mono_array_new_jagged_checked (MonoClass *klass, int n, uintptr_t *lengths, MonoError *error)
{
return mono_array_new_jagged_helper (klass, n, lengths, 0, error);
}
/**
* mono_array_new:
* \param domain domain where the object is created
* \param eclass element class
* \param n number of array elements
* This routine creates a new szarray with \p n elements of type \p eclass.
*/
MonoArray *
mono_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n)
{
MonoArray *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_array_new_checked (eclass, n, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_array_new_checked:
* \param eclass element class
* \param n number of array elements
* \param error set on error
* This routine creates a new szarray with \p n elements of type \p eclass.
* On failure returns NULL and sets \p error.
*/
MonoArray *
mono_array_new_checked (MonoClass *eclass, uintptr_t n, MonoError *error)
{
MonoClass *ac;
error_init (error);
ac = mono_class_create_array (eclass, 1);
g_assert (ac);
MonoVTable *vtable = mono_class_vtable_checked (ac, error);
return_val_if_nok (error, NULL);
return mono_array_new_specific_checked (vtable, n, error);
}
/**
* mono_array_new_specific:
* \param vtable a vtable in the appropriate domain for an initialized class
* \param n number of array elements
* This routine is a fast alternative to \c mono_array_new for code which
* can be sure about the domain it operates in.
*/
MonoArray *
mono_array_new_specific (MonoVTable *vtable, uintptr_t n)
{
ERROR_DECL (error);
MonoArray *arr = mono_array_new_specific_checked (vtable, n, error);
mono_error_cleanup (error);
return arr;
}
static MonoArray*
mono_array_new_specific_internal (MonoVTable *vtable, uintptr_t n, gboolean pinned, MonoError *error)
{
MonoArray *o;
uintptr_t byte_len;
error_init (error);
if (G_UNLIKELY (n > MONO_ARRAY_MAX_INDEX)) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
if (!mono_array_calc_byte_len (vtable->klass, n, &byte_len)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
if (pinned)
o = mono_gc_alloc_pinned_vector (vtable, byte_len, n);
else
o = mono_gc_alloc_vector (vtable, byte_len, n);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT "d bytes", (gsize) byte_len);
return NULL;
}
return o;
}
MonoArray*
mono_array_new_specific_checked (MonoVTable *vtable, uintptr_t n, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_array_new_specific_internal (vtable, n, FALSE, error);
}
MonoArrayHandle
ves_icall_System_GC_AllocPinnedArray (MonoReflectionTypeHandle array_type, gint32 length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (array_type, type));
MonoVTable *vtable = mono_class_vtable_checked (klass, error);
goto_if_nok (error, fail);
MonoArray *arr;
arr = mono_array_new_specific_internal (vtable, length, TRUE, error);
goto_if_nok (error, fail);
return MONO_HANDLE_NEW (MonoArray, arr);
fail:
return MONO_HANDLE_NEW (MonoArray, NULL);
}
MonoArrayHandle
mono_array_new_specific_handle (MonoVTable *vtable, uintptr_t n, MonoError *error)
{
// FIXMEcoop invert relationship with mono_array_new_specific_checked
return MONO_HANDLE_NEW (MonoArray, mono_array_new_specific_checked (vtable, n, error));
}
MonoArray*
ves_icall_array_new_specific (MonoVTable *vtable, uintptr_t n)
{
ERROR_DECL (error);
MonoArray *arr = mono_array_new_specific_checked (vtable, n, error);
mono_error_set_pending_exception (error);
return arr;
}
gboolean
mono_string_equal_internal (MonoString *s1, MonoString *s2)
{
int l1 = mono_string_length_internal (s1);
int l2 = mono_string_length_internal (s2);
if (s1 == s2)
return TRUE;
if (l1 != l2)
return FALSE;
return memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), l1 * 2) == 0;
}
guint
mono_string_hash_internal (MonoString *s)
{
const gunichar2 *p = mono_string_chars_internal (s);
int i, len = mono_string_length_internal (s);
guint h = 0;
for (i = 0; i < len; i++) {
h = (h << 5) - h + *p;
p++;
}
return h;
}
/**
* mono_string_empty_wrapper:
*
* Returns: The same empty string instance as the managed string.Empty
*/
MonoString*
mono_string_empty_wrapper (void)
{
MonoDomain *domain = mono_domain_get ();
return mono_string_empty_internal (domain);
}
MonoString*
mono_string_empty_internal (MonoDomain *domain)
{
g_assert (domain);
g_assert (domain->empty_string);
return domain->empty_string;
}
/**
* mono_string_empty:
*
* Returns: The same empty string instance as the managed string.Empty
*/
MonoString*
mono_string_empty (MonoDomain *domain)
{
MONO_EXTERNAL_ONLY (MonoString*, mono_string_empty_internal (domain));
}
MonoStringHandle
mono_string_empty_handle (void)
{
MonoDomain *domain = mono_get_root_domain ();
return MONO_HANDLE_NEW (MonoString, mono_string_empty_internal (domain));
}
/**
* mono_string_new_utf16:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \returns A newly created string object which contains \p text.
*/
MonoString *
mono_string_new_utf16 (MonoDomain *domain, const mono_unichar2 *text, gint32 len)
{
MonoString *res = NULL;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
res = mono_string_new_utf16_checked (text, len, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return res;
}
/**
* mono_string_new_utf16_checked:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \param error written on error.
* \returns A newly created string object which contains \p text.
* On error, returns NULL and sets \p error.
*/
MonoString *
mono_string_new_utf16_checked (const gunichar2 *text, gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString *s;
error_init (error);
s = mono_string_new_size_checked (len, error);
if (s != NULL)
memcpy (mono_string_chars_internal (s), text, len * 2);
return s;
}
/**
* mono_string_new_utf16_handle:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \param error written on error.
* \returns A newly created string object which contains \p text.
* On error, returns NULL and sets \p error.
*/
MonoStringHandle
mono_string_new_utf16_handle (const gunichar2 *text, gint32 len, MonoError *error)
{
return MONO_HANDLE_NEW (MonoString, mono_string_new_utf16_checked (text, len, error));
}
/**
* mono_string_new_utf32_checked:
* \param text a pointer to an utf32 string
* \param len the length of the string
* \param error set on failure.
* \returns A newly created string object which contains \p text. On failure returns NULL and sets \p error.
*/
static MonoString *
mono_string_new_utf32_checked (const mono_unichar4 *text, gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString *s;
mono_unichar2 *utf16_output = NULL;
error_init (error);
utf16_output = g_ucs4_to_utf16 (text, len, NULL, NULL, NULL);
gint32 utf16_len = g_utf16_len (utf16_output);
s = mono_string_new_size_checked (utf16_len, error);
goto_if_nok (error, exit);
memcpy (mono_string_chars_internal (s), utf16_output, utf16_len * 2);
exit:
g_free (utf16_output);
return s;
}
/**
* mono_string_new_utf32:
* \param text a pointer to a UTF-32 string
* \param len the length of the string
* \returns A newly created string object which contains \p text.
*/
MonoString *
mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len)
{
ERROR_DECL (error);
MonoString *result = mono_string_new_utf32_checked (text, len, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_new_size:
* \param text a pointer to a UTF-16 string
* \param len the length of the string
* \returns A newly created string object of \p len
*/
MonoString *
mono_string_new_size (MonoDomain *domain, gint32 len)
{
MonoString *str;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
str = mono_string_new_size_checked (len, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return str;
}
MonoStringHandle
mono_string_new_size_handle (gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoStringHandle s;
MonoVTable *vtable;
size_t size;
error_init (error);
/* check for overflow */
if (len < 0 || len > ((SIZE_MAX - G_STRUCT_OFFSET (MonoString, chars) - 8) / 2)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", -1);
return NULL_HANDLE_STRING;
}
size = (G_STRUCT_OFFSET (MonoString, chars) + (((size_t)len + 1) * 2));
g_assert (size > 0);
vtable = mono_class_vtable_checked (mono_defaults.string_class, error);
return_val_if_nok (error, NULL_HANDLE_STRING);
s = mono_gc_alloc_handle_string (vtable, size, len);
if (G_UNLIKELY (MONO_HANDLE_IS_NULL (s)))
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT " bytes", size);
return s;
}
MonoString *
mono_string_new_size_checked (gint32 length, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_OBJ (mono_string_new_size_handle (length, error));
}
/**
* mono_string_new_len:
* \param text a pointer to an utf8 string
* \param length number of bytes in \p text to consider
* \returns A newly created string object which contains \p text.
*/
MonoString*
mono_string_new_len (MonoDomain *domain, const char *text, guint length)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoStringHandle result;
MONO_ENTER_GC_UNSAFE;
result = mono_string_new_utf8_len (text, length, error);
MONO_EXIT_GC_UNSAFE;
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_string_new_utf8_len:
* \param text a pointer to an utf8 string
* \param length number of bytes in \p text to consider
* \param error set on error
* \returns A newly created string object which contains \p text. On
* failure returns NULL and sets \p error.
*/
MonoStringHandle
mono_string_new_utf8_len (const char *text, guint length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
GError *eg_error = NULL;
MonoStringHandle o = NULL_HANDLE_STRING;
gunichar2 *ut = NULL;
glong items_written;
ut = eg_utf8_to_utf16_with_nuls (text, length, NULL, &items_written, &eg_error);
if (eg_error) {
o = NULL_HANDLE_STRING;
// Like mono_ldstr_utf8:
mono_error_set_argument (error, "string", eg_error->message);
// FIXME? See mono_string_new_checked.
//mono_error_set_execution_engine (error, "String conversion error: %s", eg_error->message);
g_error_free (eg_error);
} else {
o = mono_string_new_utf16_handle (ut, items_written, error);
}
g_free (ut);
return o;
}
MonoString*
mono_string_new_len_checked (const char *text, guint length, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
error_init (error);
HANDLE_FUNCTION_RETURN_OBJ (mono_string_new_utf8_len (text, length, error));
}
static
MonoString*
mono_string_new_internal (const char *text)
{
ERROR_DECL (error);
MonoString *res = NULL;
res = mono_string_new_checked (text, error);
if (!is_ok (error)) {
/* Mono API compatability: assert on Out of Memory errors,
* return NULL otherwise (most likely an invalid UTF-8 byte
* sequence). */
if (mono_error_get_error_code (error) == MONO_ERROR_OUT_OF_MEMORY)
mono_error_assert_ok (error);
else
mono_error_cleanup (error);
}
return res;
}
/**
* mono_string_new:
* \param text a pointer to a UTF-8 string
* \deprecated Use \c mono_string_new_checked in new code.
* This function asserts if it cannot allocate a new string.
* \returns A newly created string object which contains \p text.
*/
MonoString*
mono_string_new (MonoDomain *domain, const char *text)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoString*, mono_string_new_internal (text));
}
/**
* mono_string_new_checked:
* \param text a pointer to an utf8 string
* \param merror set on error
* \returns A newly created string object which contains \p text.
* On error returns NULL and sets \p merror.
*/
MonoString*
mono_string_new_checked (const char *text, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
GError *eg_error = NULL;
MonoString *o = NULL;
gunichar2 *ut;
glong items_written;
int len;
error_init (error);
len = strlen (text);
ut = g_utf8_to_utf16 (text, len, NULL, &items_written, &eg_error);
if (!eg_error)
o = mono_string_new_utf16_checked (ut, items_written, error);
else {
mono_error_set_execution_engine (error, "String conversion error: %s", eg_error->message);
g_error_free (eg_error);
}
g_free (ut);
return o;
}
/**
* mono_string_new_wtf8_len_checked:
* \param text a pointer to an wtf8 string (see https://simonsapin.github.io/wtf-8/)
* \param length number of bytes in \p text to consider
* \param merror set on error
* \returns A newly created string object which contains \p text.
* On error returns NULL and sets \p merror.
*/
MonoString*
mono_string_new_wtf8_len_checked (const char *text, guint length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
GError *eg_error = NULL;
MonoString *o = NULL;
gunichar2 *ut = NULL;
glong items_written;
ut = eg_wtf8_to_utf16 (text, length, NULL, &items_written, &eg_error);
if (!eg_error)
o = mono_string_new_utf16_checked (ut, items_written, error);
else
g_error_free (eg_error);
g_free (ut);
return o;
}
MonoStringHandle
mono_string_new_wrapper_internal_impl (const char *text, MonoError *error)
{
return MONO_HANDLE_NEW (MonoString, mono_string_new_internal (text));
}
/**
* mono_string_new_wrapper:
* \param text pointer to UTF-8 characters.
* Helper function to create a string object from \p text in the current domain.
*/
MonoString*
mono_string_new_wrapper (const char *text)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoString*, mono_string_new_wrapper_internal (text));
}
/**
* mono_value_box:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \returns A newly created object which contains \p value.
*/
MonoObject *
mono_value_box (MonoDomain *domain, MonoClass *klass, gpointer value)
{
MonoObject *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_value_box_checked (klass, value, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_value_box_handle:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \param error set on error
* \returns A newly created object which contains \p value. On failure
* returns NULL and sets \p error.
*/
MonoObjectHandle
mono_value_box_handle (MonoClass *klass, gpointer value, MonoError *error)
{
// FIXMEcoop gpointer value needs more attention
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
error_init (error);
g_assert (m_class_is_valuetype (klass));
g_assert (value != NULL);
if (G_UNLIKELY (m_class_is_byreflike (klass))) {
char *full_name = mono_type_get_full_name (klass);
mono_error_set_not_supported (error, "Cannot box IsByRefLike type %s", full_name);
g_free (full_name);
return NULL_HANDLE;
}
if (mono_class_is_nullable (klass))
return mono_nullable_box_handle (value, klass, error);
vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, NULL_HANDLE);
int size = mono_class_instance_size (klass);
MonoObjectHandle res_handle = mono_object_new_alloc_by_vtable (vtable, error);
return_val_if_nok (error, NULL_HANDLE);
size -= MONO_ABI_SIZEOF (MonoObject);
if (mono_gc_is_moving ()) {
g_assert (size == mono_class_value_size (klass, NULL));
MONO_ENTER_NO_SAFEPOINTS;
gpointer data = mono_handle_get_data_unsafe (res_handle);
mono_gc_wbarrier_value_copy_internal (data, value, 1, klass);
MONO_EXIT_NO_SAFEPOINTS;
} else {
MONO_ENTER_NO_SAFEPOINTS;
gpointer data = mono_handle_get_data_unsafe (res_handle);
#if NO_UNALIGNED_ACCESS
mono_gc_memmove_atomic (data, value, size);
#else
switch (size) {
case 1:
*(guint8*)data = *(guint8 *) value;
break;
case 2:
*(guint16 *)(data) = *(guint16 *) value;
break;
case 4:
*(guint32 *)(data) = *(guint32 *) value;
break;
case 8:
*(guint64 *)(data) = *(guint64 *) value;
break;
default:
mono_gc_memmove_atomic (data, value, size);
}
#endif
MONO_EXIT_NO_SAFEPOINTS;
}
if (m_class_has_finalize (klass))
mono_object_register_finalizer_handle (res_handle);
return res_handle;
}
/**
* mono_value_box_checked:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \param error set on error
* \returns A newly created object which contains \p value. On failure
* returns NULL and sets \p error.
*/
MonoObject *
mono_value_box_checked (MonoClass *klass, gpointer value, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_OBJ (mono_value_box_handle (klass, value, error));
}
void
mono_value_copy_internal (gpointer dest, gconstpointer src, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
mono_gc_wbarrier_value_copy_internal (dest, src, 1, klass);
}
/**
* mono_value_copy:
* \param dest destination pointer
* \param src source pointer
* \param klass a valuetype class
* Copy a valuetype from \p src to \p dest. This function must be used
* when \p klass contains reference fields.
*/
void
mono_value_copy (gpointer dest, gpointer src, MonoClass *klass)
{
mono_value_copy_internal (dest, src, klass);
}
void
mono_value_copy_array_internal (MonoArray *dest, int dest_idx, gconstpointer src, int count)
{
MONO_REQ_GC_UNSAFE_MODE;
int size = mono_array_element_size (dest->obj.vtable->klass);
char *d = mono_array_addr_with_size_fast (dest, size, dest_idx);
g_assert (size == mono_class_value_size (m_class_get_element_class (mono_object_class (dest)), NULL));
// FIXME remove (gpointer) cast.
mono_gc_wbarrier_value_copy_internal (d, (gpointer)src, count, m_class_get_element_class (mono_object_class (dest)));
}
void
mono_value_copy_array_handle (MonoArrayHandle dest, int dest_idx, gconstpointer src, int count)
{
mono_value_copy_array_internal (MONO_HANDLE_RAW (dest), dest_idx, src, count);
}
/**
* mono_value_copy_array:
* \param dest destination array
* \param dest_idx index in the \p dest array
* \param src source pointer
* \param count number of items
* Copy \p count valuetype items from \p src to the array \p dest at index \p dest_idx.
* This function must be used when \p klass contains references fields.
* Overlap is handled.
*/
void
mono_value_copy_array (MonoArray *dest, int dest_idx, void* src, int count)
{
MONO_EXTERNAL_ONLY_VOID (mono_value_copy_array_internal (dest, dest_idx, src, count));
}
MonoVTable *
mono_object_get_vtable_internal (MonoObject *obj)
{
// This could be called during STW, so untag the vtable if needed.
return mono_gc_get_vtable (obj);
}
MonoVTable*
mono_object_get_vtable (MonoObject *obj)
{
MONO_EXTERNAL_ONLY (MonoVTable*, mono_object_get_vtable_internal (obj));
}
MonoDomain*
mono_object_get_domain_internal (MonoObject *obj)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_object_domain (obj);
}
/**
* mono_object_get_domain:
* \param obj object to query
* \returns the \c MonoDomain where the object is hosted
*/
MonoDomain*
mono_object_get_domain (MonoObject *obj)
{
MonoDomain* ret = NULL;
MONO_ENTER_GC_UNSAFE;
ret = mono_object_get_domain_internal (obj);
MONO_EXIT_GC_UNSAFE;
return ret;
}
/**
* mono_object_get_class:
* \param obj object to query
* Use this function to obtain the \c MonoClass* for a given \c MonoObject.
* \returns the \c MonoClass of the object.
*/
MonoClass*
mono_object_get_class (MonoObject *obj)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoClass*, mono_object_class (obj));
}
guint
mono_object_get_size_internal (MonoObject* o)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* klass = mono_object_class (o);
if (klass == mono_defaults.string_class) {
return MONO_SIZEOF_MONO_STRING + 2 * mono_string_length_internal ((MonoString*) o) + 2;
} else if (o->vtable->rank) {
MonoArray *array = (MonoArray*)o;
size_t size = MONO_SIZEOF_MONO_ARRAY + mono_array_element_size (klass) * mono_array_length_internal (array);
if (array->bounds) {
size += 3;
size &= ~3;
size += sizeof (MonoArrayBounds) * o->vtable->rank;
}
return size;
} else {
return mono_class_instance_size (klass);
}
}
/**
* mono_object_get_size:
* \param o object to query
* \returns the size, in bytes, of \p o
*/
unsigned
mono_object_get_size (MonoObject *o)
{
MONO_EXTERNAL_ONLY (unsigned, mono_object_get_size_internal (o));
}
/**
* mono_object_unbox:
* \param obj object to unbox
* \returns a pointer to the start of the valuetype boxed in this
* object.
*
* This method will assert if the object passed is not a valuetype.
*/
void*
mono_object_unbox (MonoObject *obj)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
}
/**
* mono_object_isinst:
* \param obj an object
* \param klass a pointer to a class
* \returns \p obj if \p obj is derived from \p klass or NULL otherwise.
*/
MonoObject *
mono_object_isinst (MonoObject *obj_raw, MonoClass *klass)
{
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle result;
MONO_ENTER_GC_UNSAFE;
MONO_HANDLE_DCL (MonoObject, obj);
ERROR_DECL (error);
result = mono_object_handle_isinst (obj, klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_isinst_checked:
* \param obj an object
* \param klass a pointer to a class
* \param error set on error
* \returns \p obj if \p obj is derived from \p klass or NULL if it isn't.
* On failure returns NULL and sets \p error.
*/
MonoObject *
mono_object_isinst_checked (MonoObject *obj_raw, MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
error_init (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = mono_object_handle_isinst (obj, klass, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_handle_isinst:
* \param obj an object
* \param klass a pointer to a class
* \param error set on error
* \returns \p obj if \p obj is derived from \p klass or NULL if it isn't.
* On failure returns NULL and sets \p error.
*/
MonoObjectHandle
mono_object_handle_isinst (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
error_init (error);
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
if (mono_class_is_interface (klass))
return mono_object_handle_isinst_mbyref (obj, klass, error);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_assignable_from_internal (klass, mono_handle_class (obj)))
MONO_HANDLE_ASSIGN (result, obj);
return result;
}
/**
* mono_object_isinst_mbyref:
*/
MonoObject *
mono_object_isinst_mbyref (MonoObject *obj_raw, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = mono_object_handle_isinst_mbyref (obj, klass, error);
mono_error_cleanup (error); /* FIXME better API that doesn't swallow the error */
HANDLE_FUNCTION_RETURN_OBJ (result);
}
MonoObjectHandle
mono_object_handle_isinst_mbyref (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
gboolean success = FALSE;
error_init (error);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
success = mono_object_handle_isinst_mbyref_raw (obj, klass, error);
if (success && is_ok (error))
MONO_HANDLE_ASSIGN (result, obj);
leave:
return result;
}
gboolean
mono_object_handle_isinst_mbyref_raw (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
error_init (error);
gboolean result = FALSE;
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
MonoVTable *vt;
vt = MONO_HANDLE_GETVAL (obj, vtable);
if (mono_class_is_interface (klass)) {
if (MONO_VTABLE_IMPLEMENTS_INTERFACE (vt, m_class_get_interface_id (klass))) {
result = TRUE;
goto leave;
}
/* casting an array one of the invariant interfaces that must act as such */
if (m_class_is_array_special_interface (klass)) {
if (mono_class_is_assignable_from_internal (klass, vt->klass)) {
result = TRUE;
goto leave;
}
}
/*If the above check fails we are in the slow path of possibly raising an exception. So it's ok to it this way.*/
else if (mono_class_has_variant_generic_params (klass) && mono_class_is_assignable_from_internal (klass, mono_handle_class (obj))) {
result = TRUE;
goto leave;
}
} else {
MonoClass *oklass = vt->klass;
mono_class_setup_supertypes (klass);
if (mono_class_has_parent_fast (oklass, klass)) {
result = TRUE;
goto leave;
}
}
leave:
return result;
}
/**
* mono_object_castclass_mbyref:
* \param obj an object
* \param klass a pointer to a class
* \returns \p obj if \p obj is derived from \p klass, returns NULL otherwise.
*/
MonoObject *
mono_object_castclass_mbyref (MonoObject *obj_raw, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
MONO_HANDLE_ASSIGN (result, mono_object_handle_isinst_mbyref (obj, klass, error));
mono_error_cleanup (error);
leave:
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static MonoStringHandle
mono_string_get_pinned (MonoStringHandle str, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
/* We only need to make a pinned version of a string if this is a moving GC */
if (!mono_gc_is_moving ())
return str;
const gsize length = mono_string_handle_length (str);
const gsize size = MONO_SIZEOF_MONO_STRING + (length + 1) * sizeof (gunichar2);
MonoStringHandle news = MONO_HANDLE_CAST (MonoString, mono_gc_alloc_handle_pinned_obj (MONO_HANDLE_GETVAL (str, object.vtable), size));
if (!MONO_HANDLE_BOOL (news)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT " bytes", size);
return news;
}
MONO_ENTER_NO_SAFEPOINTS;
memcpy (mono_string_chars_internal (MONO_HANDLE_RAW (news)),
mono_string_chars_internal (MONO_HANDLE_RAW (str)),
length * sizeof (gunichar2));
MONO_EXIT_NO_SAFEPOINTS;
MONO_HANDLE_SETVAL (news, length, int, length);
return news;
}
MonoStringHandle
mono_string_is_interned_lookup (MonoStringHandle str, gboolean insert, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!ldstr_table) {
MonoGHashTable *table = mono_g_hash_table_new_type_internal ((GHashFunc)mono_string_hash_internal, (GCompareFunc)mono_string_equal_internal, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, mono_get_root_domain (), "Domain String Pool Table");
mono_memory_barrier ();
ldstr_table = table;
}
ldstr_lock ();
MonoString *res = (MonoString *)mono_g_hash_table_lookup (ldstr_table, MONO_HANDLE_RAW (str));
ldstr_unlock ();
if (res)
return MONO_HANDLE_NEW (MonoString, res);
if (!insert)
return NULL_HANDLE_STRING;
// Allocate outside the lock.
MonoStringHandle s = mono_string_get_pinned (str, error);
if (!is_ok (error) || !MONO_HANDLE_BOOL (s))
return NULL_HANDLE_STRING;
// Try again inside lock.
ldstr_lock ();
res = (MonoString *)mono_g_hash_table_lookup (ldstr_table, MONO_HANDLE_RAW (str));
if (res)
MONO_HANDLE_ASSIGN_RAW (s, res);
else {
mono_g_hash_table_insert_internal (ldstr_table, MONO_HANDLE_RAW (s), MONO_HANDLE_RAW (s));
#ifdef HOST_WASM
mono_set_string_interned_internal ((MonoObject *)MONO_HANDLE_RAW (s));
#endif
}
ldstr_unlock ();
return s;
}
#ifdef HOST_WASM
/**
* mono_string_instance_is_interned:
* Checks to see if the string instance has its interned flag set.
* \param str String to probe
* \returns TRUE if the string instance is interned, FALSE otherwise.
*/
int
mono_string_instance_is_interned (MonoString *str)
{
return mono_is_string_interned_internal ((MonoObject *)str);
}
#endif
/**
* mono_string_is_interned:
* Searches the interned string table for a string with value equal to the provided string.
* \param str String to probe
* \returns The string located within the intern table, or null.
*/
MonoString*
mono_string_is_interned (MonoString *str_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoString, str);
MONO_ENTER_GC_UNSAFE;
str = mono_string_is_interned_internal (str, error);
MONO_EXIT_GC_UNSAFE;
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_OBJ (str);
}
/**
* mono_string_intern:
* \param o String to intern
* Interns the string passed.
* \returns The interned string.
*/
MonoString*
mono_string_intern (MonoString *str_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoString, str);
MONO_ENTER_GC_UNSAFE;
str = mono_string_intern_checked (str, error);
MONO_EXIT_GC_UNSAFE;
HANDLE_FUNCTION_RETURN_OBJ (str);
}
/**
* mono_ldstr:
* \param domain the domain where the string will be used.
* \param image a metadata context
* \param idx index into the user string table.
* Implementation for the \c ldstr opcode.
* \returns a loaded string from the \p image / \p idx combination.
*/
MonoString*
mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
{
MonoString *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_ldstr_checked (image, idx, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_ldstr_checked:
* \param image a metadata context
* \param idx index into the user string table.
* \param error set on error.
* Implementation for the \c ldstr opcode.
* \returns A loaded string from the \p image / \p idx combination.
* On failure returns NULL and sets \p error.
*/
MonoString*
mono_ldstr_checked (MonoImage *image, guint32 idx, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
HANDLE_FUNCTION_ENTER ();
MonoStringHandle str = MONO_HANDLE_NEW (MonoString, NULL);
if (image->dynamic) {
MONO_HANDLE_ASSIGN_RAW (str, (MonoString *)mono_lookup_dynamic_token (image, MONO_TOKEN_STRING | idx, NULL, error));
goto exit;
}
mono_ldstr_metadata_sig (mono_metadata_user_string (image, idx), str, error);
exit:
HANDLE_FUNCTION_RETURN_OBJ (str);
}
MonoStringHandle
mono_ldstr_handle (MonoImage *image, guint32 idx, MonoError *error)
{
// FIXME invert mono_ldstr_handle and mono_ldstr_checked.
return MONO_HANDLE_NEW (MonoString, mono_ldstr_checked (image, idx, error));
}
char*
mono_string_from_blob (const char *str, MonoError *error)
{
gsize len = mono_metadata_decode_blob_size (str, &str) >> 1;
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
gunichar2 *src = (gunichar2*)str;
gunichar2 *copy = g_new (gunichar2, len);
int i;
for (i = 0; i < len; ++i)
copy [i] = GUINT16_FROM_LE (src [i]);
char *res = mono_utf16_to_utf8 (copy, len, error);
g_free (copy);
return res;
#else
return mono_utf16_to_utf8 ((const gunichar2*)str, len, error);
#endif
}
/**
* mono_ldstr_metadata_sig
* \param sig the signature of a metadata string
* \param error set on error
* \returns a \c MonoString for a string stored in the metadata. On
* failure returns NULL and sets \p error.
*/
static void
mono_ldstr_metadata_sig (const char* sig, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MONO_HANDLE_ASSIGN_RAW (string_handle, NULL);
const gsize len = mono_metadata_decode_blob_size (sig, &sig) / sizeof (gunichar2);
// FIXMEcoop excess handle, use mono_string_new_utf16_checked and string_handle parameter
MonoStringHandle o = mono_string_new_utf16_handle ((gunichar2*)sig, len, error);
return_if_nok (error);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
gunichar2 *p = mono_string_chars_internal (MONO_HANDLE_RAW (o));
for (gsize i = 0; i < len; ++i)
p [i] = GUINT16_FROM_LE (p [i]);
#endif
// FIXMEcoop excess handle in mono_string_intern_checked
MONO_HANDLE_ASSIGN_RAW (string_handle, MONO_HANDLE_RAW (mono_string_intern_checked (o, error)));
}
/*
* mono_ldstr_utf8:
*
* Same as mono_ldstr, but return a NULL terminated utf8 string instead
* of an object.
*/
char*
mono_ldstr_utf8 (MonoImage *image, guint32 idx, MonoError *error)
{
const char *str;
size_t len2;
long written = 0;
char *as;
GError *gerror = NULL;
error_init (error);
str = mono_metadata_user_string (image, idx);
len2 = mono_metadata_decode_blob_size (str, &str);
len2 >>= 1;
as = g_utf16_to_utf8 ((gunichar2*)str, len2, NULL, &written, &gerror);
if (gerror) {
mono_error_set_argument (error, "string", gerror->message);
g_error_free (gerror);
return NULL;
}
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (len2 > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (len2);
memcpy (as2, as, written);
g_free (as);
as = as2;
}
return as;
}
/**
* mono_string_to_utf8:
* \param s a \c System.String
* \deprecated Use \c mono_string_to_utf8_checked_internal to avoid having an exception arbitrarily raised.
* \returns the UTF-8 representation for \p s.
* The resulting buffer needs to be freed with \c mono_free().
*/
char *
mono_string_to_utf8 (MonoString *s)
{
char *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_string_to_utf8_checked_internal (s, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
result = NULL;
}
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_utf16_to_utf8len:
*/
char *
mono_utf16_to_utf8len (const gunichar2 *s, gsize slength, gsize *utf8_length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
long written = 0;
*utf8_length = 0;
char *as;
GError *gerror = NULL;
error_init (error);
if (s == NULL)
return NULL;
if (!slength)
return g_strdup ("");
as = g_utf16_to_utf8 (s, slength, NULL, &written, &gerror);
*utf8_length = written;
if (gerror) {
mono_error_set_argument (error, "string", gerror->message);
g_error_free (gerror);
return NULL;
}
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (slength > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (slength);
memcpy (as2, as, written);
g_free (as);
as = as2;
// FIXME utf8_length is ambiguous here.
// For now it is what strlen would report.
// A lot of code does not deal correctly with embedded nuls.
}
return as;
}
/**
* mono_utf16_to_utf8:
*/
char *
mono_utf16_to_utf8 (const gunichar2 *s, gsize slength, MonoError *error)
{
gsize utf8_length = 0;
return mono_utf16_to_utf8len (s, slength, &utf8_length, error);
}
char *
mono_string_to_utf8_checked_internal (MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (s == NULL)
return NULL;
if (!s->length)
return g_strdup ("");
return mono_utf16_to_utf8 (mono_string_chars_internal (s), s->length, error);
}
char *
mono_string_to_utf8len (MonoStringHandle s, gsize *utf8len, MonoError *error)
{
*utf8len = 0;
if (MONO_HANDLE_IS_NULL (s))
return NULL;
char *utf8;
MONO_ENTER_NO_SAFEPOINTS;
utf8 = mono_utf16_to_utf8len (mono_string_chars_internal (MONO_HANDLE_RAW (s)), mono_string_handle_length (s), utf8len, error);
MONO_EXIT_NO_SAFEPOINTS;
return utf8;
}
/**
* mono_string_to_utf8_checked:
* \param s a \c System.String
* \param error a \c MonoError.
* Converts a \c MonoString to its UTF-8 representation. May fail; check
* \p error to determine whether the conversion was successful.
* The resulting buffer should be freed with \c mono_free().
*/
char*
mono_string_to_utf8_checked (MonoString *string_obj, MonoError *error)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (char*, mono_string_to_utf8_checked_internal (string_obj, error));
}
char *
mono_string_handle_to_utf8 (MonoStringHandle s, MonoError *error)
{
return mono_string_to_utf8_checked_internal (MONO_HANDLE_RAW (s), error);
}
/**
* mono_string_to_utf8_ignore:
* \param s a MonoString
* Converts a \c MonoString to its UTF-8 representation. Will ignore
* invalid surrogate pairs.
* The resulting buffer should be freed with \c mono_free().
*/
char *
mono_string_to_utf8_ignore (MonoString *s)
{
MONO_REQ_GC_UNSAFE_MODE;
long written = 0;
char *as;
if (s == NULL)
return NULL;
if (!s->length)
return g_strdup ("");
as = g_utf16_to_utf8 (mono_string_chars_internal (s), s->length, NULL, &written, NULL);
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (s->length > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (s->length);
memcpy (as2, as, written);
g_free (as);
as = as2;
}
return as;
}
mono_unichar2*
mono_string_to_utf16_internal_impl (MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXME This optimization ok to miss before wrapper? Or null is rare?
if (MONO_HANDLE_RAW (s) == NULL)
return NULL;
int const length = mono_string_handle_length (s);
mono_unichar2* const as = (mono_unichar2*)g_malloc ((length + 1) * sizeof (*as));
if (as) {
as [length] = 0;
if (length)
memcpy (as, mono_string_chars_internal (MONO_HANDLE_RAW (s)), length * sizeof (*as));
}
return as;
}
/**
* mono_string_to_utf16:
* \param s a \c MonoString
* \returns a null-terminated array of the UTF-16 chars
* contained in \p s. The result must be freed with \c g_free().
* This is a temporary helper until our string implementation
* is reworked to always include the null-terminating char.
*/
mono_unichar2*
mono_string_to_utf16 (MonoString *string_obj)
{
if (!string_obj)
return NULL;
MONO_EXTERNAL_ONLY (mono_unichar2*, mono_string_to_utf16_internal (string_obj));
}
mono_unichar4*
mono_string_to_utf32_internal_impl (MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXME This optimization ok to miss before wrapper? Or null is rare?
if (MONO_HANDLE_RAW (s) == NULL)
return NULL;
return g_utf16_to_ucs4 (MONO_HANDLE_RAW (s)->chars, mono_string_handle_length (s), NULL, NULL, NULL);
}
/**
* mono_string_to_utf32:
* \param s a \c MonoString
* \returns a null-terminated array of the UTF-32 (UCS-4) chars
* contained in \p s. The result must be freed with \c g_free().
*/
mono_unichar4*
mono_string_to_utf32 (MonoString *string_obj)
{
MONO_EXTERNAL_ONLY (mono_unichar4*, mono_string_to_utf32_internal (string_obj));
}
/**
* mono_string_from_utf16:
* \param data the UTF-16 string (LPWSTR) to convert
* Converts a NULL-terminated UTF-16 string (LPWSTR) to a \c MonoString.
* \returns a \c MonoString.
*/
MonoString *
mono_string_from_utf16 (gunichar2 *data)
{
ERROR_DECL (error);
MonoString *result = mono_string_from_utf16_checked (data, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_from_utf16_checked:
* \param data the UTF-16 string (LPWSTR) to convert
* \param error set on error
* Converts a NULL-terminated UTF-16 string (LPWSTR) to a \c MonoString.
* \returns a \c MonoString. On failure sets \p error and returns NULL.
*/
MonoString *
mono_string_from_utf16_checked (const gunichar2 *data, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (!data)
return NULL;
return mono_string_new_utf16_checked (data, g_utf16_len (data), error);
}
/**
* mono_string_from_utf32:
* \param data the UTF-32 string (LPWSTR) to convert
* Converts a UTF-32 (UCS-4) string to a \c MonoString.
* \returns a \c MonoString.
*/
MonoString *
mono_string_from_utf32 (/*const*/ mono_unichar4 *data)
{
ERROR_DECL (error);
MonoString *result = mono_string_from_utf32_checked (data, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_from_utf32_checked:
* \param data the UTF-32 string (LPWSTR) to convert
* \param error set on error
* Converts a UTF-32 (UCS-4) string to a \c MonoString.
* \returns a \c MonoString. On failure returns NULL and sets \p error.
*/
MonoString *
mono_string_from_utf32_checked (const mono_unichar4 *data, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoString* result = NULL;
mono_unichar2 *utf16_output = NULL;
GError *gerror = NULL;
glong items_written;
int len = 0;
if (!data)
return NULL;
while (data [len]) len++;
utf16_output = g_ucs4_to_utf16 (data, len, NULL, &items_written, &gerror);
if (gerror)
g_error_free (gerror);
result = mono_string_from_utf16_checked (utf16_output, error);
g_free (utf16_output);
return result;
}
static char *
mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
char *r;
char *mp_s;
int len;
r = mono_string_to_utf8_checked_internal (s, error);
if (!is_ok (error))
return NULL;
if (!mp && !image)
return r;
len = strlen (r) + 1;
if (mp)
mp_s = (char *)mono_mempool_alloc (mp, len);
else
mp_s = (char *)mono_image_alloc (image, len);
memcpy (mp_s, r, len);
g_free (r);
return mp_s;
}
/**
* mono_string_to_utf8_image:
* \param s a \c System.String
* Same as \c mono_string_to_utf8, but allocate the string from the image mempool.
*/
char *
mono_string_to_utf8_image (MonoImage *image, MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_string_to_utf8_internal (NULL, image, MONO_HANDLE_RAW (s), error); /* FIXME pin the string */
}
/**
* mono_string_to_utf8_mp:
* \param s a \c System.String
* Same as \c mono_string_to_utf8, but allocate the string from a mempool.
*/
char *
mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_string_to_utf8_internal (mp, NULL, s, error);
}
static MonoRuntimeExceptionHandlingCallbacks eh_callbacks;
void
mono_install_eh_callbacks (MonoRuntimeExceptionHandlingCallbacks *cbs)
{
eh_callbacks = *cbs;
}
MonoRuntimeExceptionHandlingCallbacks *
mono_get_eh_callbacks (void)
{
return &eh_callbacks;
}
void
mono_raise_exception_internal (MonoException *ex)
{
/* raise_exception doesn't return, so the transition to GC Unsafe is unbalanced */
MONO_STACKDATA (stackdata);
mono_threads_enter_gc_unsafe_region_unbalanced_with_info (mono_thread_info_current (), &stackdata);
mono_raise_exception_deprecated (ex);
}
/**
* mono_raise_exception:
* \param ex exception object
* Signal the runtime that the exception \p ex has been raised in unmanaged code.
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_raise_exception (MonoException *ex)
{
MONO_EXTERNAL_ONLY_VOID (mono_raise_exception_internal (ex));
}
/*
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_raise_exception_deprecated (MonoException *ex)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_raise_exception (ex);
}
/**
* mono_reraise_exception:
* \param ex exception object
* Signal the runtime that the exception \p ex has been raised in unmanaged code.
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_reraise_exception (MonoException *ex)
{
mono_reraise_exception_deprecated (ex);
}
/*
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_reraise_exception_deprecated (MonoException *ex)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_reraise_exception (ex);
}
/*
* CTX must point to managed code.
*/
void
mono_raise_exception_with_context (MonoException *ex, MonoContext *ctx)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_raise_exception_with_ctx (ex, ctx);
}
/*
* Returns the MonoMethod to call to Capture the ExecutionContext.
*/
MonoMethod*
mono_get_context_capture_method (void)
{
/* older corlib revisions won't have the class (nor the method) */
MonoClass *execution_context = mono_class_try_get_execution_context_class ();
if (!execution_context)
return NULL;
MONO_STATIC_POINTER_INIT (MonoMethod, method)
ERROR_DECL (error);
mono_class_init_internal (execution_context);
method = mono_class_get_method_from_name_checked (execution_context, "Capture", 0, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, method)
return method;
}
/**
* prepare_to_string_method:
* @obj: The object
* @target: Set to @obj or unboxed value if a valuetype
*
* Returns: the ToString override for @obj. If @obj is a valuetype, @target is unboxed otherwise it's @obj.
*/
static MonoMethod *
prepare_to_string_method (MonoObject *obj, void **target)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoMethod *method;
g_assert (target);
g_assert (obj);
*target = obj;
MONO_STATIC_POINTER_INIT (MonoMethod, to_string)
ERROR_DECL (error);
to_string = mono_class_get_method_from_name_checked (mono_get_object_class (), "ToString", 0, METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_PUBLIC, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, to_string)
method = mono_object_get_virtual_method_internal (obj, to_string);
// Unbox value type if needed
if (m_class_is_valuetype (mono_method_get_class (method))) {
*target = mono_object_unbox_internal (obj);
}
return method;
}
/**
* mono_object_to_string:
* \param obj The object
* \param exc Any exception thrown by \c ToString. May be NULL.
* \returns the result of calling \c ToString on an object.
*/
MonoString *
mono_object_to_string (MonoObject *obj, MonoObject **exc)
{
ERROR_DECL (error);
MonoString *s = NULL;
void *target;
MonoMethod *method = prepare_to_string_method (obj, &target);
if (exc) {
s = (MonoString *) mono_runtime_try_invoke (method, target, NULL, exc, error);
if (*exc == NULL && !is_ok (error))
*exc = (MonoObject*) mono_error_convert_to_exception (error);
else
mono_error_cleanup (error);
} else {
s = (MonoString *) mono_runtime_invoke_checked (method, target, NULL, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
return s;
}
/**
* mono_object_try_to_string:
* \param obj The object
* \param exc Any exception thrown by \c ToString(). Must not be NULL.
* \param error Set if method cannot be invoked.
* \returns the result of calling \c ToString() on an object. If the
* method cannot be invoked sets \p error, if it raises an exception sets \p exc,
* and returns NULL.
*/
MonoString *
mono_object_try_to_string (MonoObject *obj, MonoObject **exc, MonoError *error)
{
g_assert (exc);
error_init (error);
void *target;
MonoMethod *method = prepare_to_string_method (obj, &target);
return (MonoString*) mono_runtime_try_invoke (method, target, NULL, exc, error);
}
static char *
get_native_backtrace (MonoException *exc_raw)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL(MonoException, exc);
char * const trace = mono_exception_handle_get_native_backtrace (exc);
HANDLE_FUNCTION_RETURN_VAL (trace);
}
/**
* mono_print_unhandled_exception:
* \param exc The exception
* Prints the unhandled exception.
*/
void
mono_print_unhandled_exception_internal (MonoObject *exc)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString * str;
char *message = (char*)"";
gboolean free_message = FALSE;
ERROR_DECL (error);
if (exc == (MonoObject*)mono_object_domain (exc)->out_of_memory_ex) {
message = g_strdup ("OutOfMemoryException");
free_message = TRUE;
} else if (exc == (MonoObject*)mono_object_domain (exc)->stack_overflow_ex) {
message = g_strdup ("StackOverflowException"); //if we OVF, we can't expect to have stack space to JIT Exception::ToString.
free_message = TRUE;
} else {
if (((MonoException*)exc)->native_trace_ips) {
message = get_native_backtrace ((MonoException*)exc);
free_message = TRUE;
} else {
MonoObject *other_exc = NULL;
str = mono_object_try_to_string (exc, &other_exc, error);
if (other_exc == NULL && !is_ok (error))
other_exc = (MonoObject*)mono_error_convert_to_exception (error);
else
mono_error_cleanup (error);
if (other_exc) {
char *original_backtrace = mono_exception_get_managed_backtrace ((MonoException*)exc);
char *nested_backtrace = mono_exception_get_managed_backtrace ((MonoException*)other_exc);
message = g_strdup_printf ("Nested exception detected.\nOriginal Exception: %s\nNested exception:%s\n",
original_backtrace, nested_backtrace);
g_free (original_backtrace);
g_free (nested_backtrace);
free_message = TRUE;
} else if (str) {
message = mono_string_to_utf8_checked_internal (str, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
message = (char *) "";
} else {
free_message = TRUE;
}
}
}
}
/*
* g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
* exc->vtable->klass->name, message);
*/
g_printerr ("\nUnhandled Exception:\n%s\n", message);
if (free_message)
g_free (message);
}
void
mono_print_unhandled_exception (MonoObject *exc)
{
MONO_EXTERNAL_ONLY_VOID (mono_print_unhandled_exception_internal (exc));
}
/**
* mono_delegate_ctor:
* \param this pointer to an uninitialized delegate object
* \param target target object
* \param addr pointer to native code
* \param method method
* \param error set on error.
* Initialize a delegate and sets a specific method, not the one
* associated with \p addr. This is useful when sharing generic code.
* In that case \p addr will most probably not be associated with the
* correct instantiation of the method.
* If \method is NULL, it is looked up using \addr in the JIT info tables.
*/
void
mono_delegate_ctor (MonoObjectHandle this_obj, MonoObjectHandle target, gpointer addr, MonoMethod *method, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoDelegateHandle delegate = MONO_HANDLE_CAST (MonoDelegate, this_obj);
UnlockedIncrement (&mono_stats.delegate_creations);
MonoClass *klass = mono_handle_class (this_obj);
g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
/* Done by the EE */
callbacks.init_delegate (delegate, target, addr, method, error);
}
/**
* mono_create_ftnptr:
*
* Given a function address, create a function descriptor for it.
* This is only needed on some platforms.
*/
gpointer
mono_create_ftnptr (gpointer addr)
{
return callbacks.create_ftnptr (addr);
}
/*
* mono_get_addr_from_ftnptr:
*
* Given a pointer to a function descriptor, return the function address.
* This is only needed on some platforms.
*/
gpointer
mono_get_addr_from_ftnptr (gpointer descr)
{
return callbacks.get_addr_from_ftnptr (descr);
}
/**
* mono_string_chars:
* \param s a \c MonoString
* \returns a pointer to the UTF-16 characters stored in the \c MonoString
*/
mono_unichar2*
mono_string_chars (MonoString *s)
{
MONO_EXTERNAL_ONLY (mono_unichar2*, mono_string_chars_internal (s));
}
/**
* mono_string_length:
* \param s MonoString
* \returns the length in characters of the string
*/
int
mono_string_length (MonoString *s)
{
MONO_EXTERNAL_ONLY (int, mono_string_length_internal (s));
}
/**
* mono_array_length:
* \param array a \c MonoArray*
* \returns the total number of elements in the array. This works for
* both vectors and multidimensional arrays.
*/
uintptr_t
mono_array_length (MonoArray *array)
{
MONO_EXTERNAL_ONLY (uintptr_t, mono_array_length_internal (array));
}
#ifdef ENABLE_CHECKED_BUILD_GC
/**
* mono_string_handle_length:
* \param s \c MonoString
* \returns the length in characters of the string
*/
int
mono_string_handle_length (MonoStringHandle s)
{
MONO_REQ_GC_UNSAFE_MODE;
return MONO_HANDLE_GETVAL (s, length);
}
#endif
/**
* mono_array_addr_with_size:
* \param array a \c MonoArray*
* \param size size of the array elements
* \param idx index into the array
* Use this function to obtain the address for the \p idx item on the
* \p array containing elements of size \p size.
*
* This method performs no bounds checking or type checking.
* \returns the address of the \p idx element in the array.
*/
char*
mono_array_addr_with_size (MonoArray *array, int size, uintptr_t idx)
{
MONO_EXTERNAL_ONLY (char*, mono_array_addr_with_size_internal (array, size, idx));
}
MonoArray *
mono_glist_to_array (GList *list, MonoClass *eclass, MonoError *error)
{
MonoArray *res;
int len, i;
error_init (error);
if (!list)
return NULL;
len = g_list_length (list);
res = mono_array_new_checked (eclass, len, error);
return_val_if_nok (error, NULL);
for (i = 0; list; list = list->next, i++)
mono_array_set_internal (res, gpointer, i, list->data);
return res;
}
/**
* mono_class_value_size:
* \param klass a class
*
* This function is used for value types, and return the
* space and the alignment to store that kind of value object.
*
* \returns the size of a value of kind \p klass
*/
gint32
mono_class_value_size (MonoClass *klass, guint32 *align)
{
gint32 size;
/* fixme: check disable, because we still have external revereces to
* mscorlib and Dummy Objects
*/
/*g_assert (klass->valuetype);*/
/* this call inits klass if its not inited already */
size = mono_class_instance_size (klass);
if (m_class_has_failure (klass)) {
if (align)
*align = 1;
return 0;
}
size = size - MONO_ABI_SIZEOF (MonoObject);
g_assert (size >= 0);
if (align)
*align = m_class_get_min_align (klass);
return size;
}
/*
* mono_vtype_get_field_addr:
*
* Return the address of the FIELD in the valuetype VTYPE.
*/
gpointer
mono_vtype_get_field_addr (gpointer vtype, MonoClassField *field)
{
return ((char*)vtype) + field->offset - MONO_ABI_SIZEOF (MonoObject);
}
static GString *
quote_escape_and_append_string (char *src_str, GString *target_str)
{
#ifdef HOST_WIN32
char quote_char = '\"';
char escape_chars[] = "\"\\";
#else
char quote_char = '\'';
char escape_chars[] = "\'\\";
#endif
gboolean need_quote = FALSE;
gboolean need_escape = FALSE;
for (char *pos = src_str; *pos; ++pos) {
if (isspace (*pos))
need_quote = TRUE;
if (strchr (escape_chars, *pos))
need_escape = TRUE;
}
if (need_quote)
target_str = g_string_append_c (target_str, quote_char);
if (need_escape) {
for (char *pos = src_str; *pos; ++pos) {
if (strchr (escape_chars, *pos))
target_str = g_string_append_c (target_str, '\\');
target_str = g_string_append_c (target_str, *pos);
}
} else {
target_str = g_string_append (target_str, src_str);
}
if (need_quote)
target_str = g_string_append_c (target_str, quote_char);
return target_str;
}
static GString *
format_cmd_line (int argc, char **argv, gboolean add_host)
{
size_t total_size = 0;
char *host_path = NULL;
GString *cmd_line = NULL;
if (add_host) {
#if !defined(HOST_WIN32) && defined(HAVE_GETPID)
host_path = mono_w32process_get_path (getpid ());
#elif defined(HOST_WIN32)
gunichar2 *host_path_ucs2 = NULL;
guint32 host_path_ucs2_len = 0;
if (mono_get_module_filename (NULL, &host_path_ucs2, &host_path_ucs2_len)) {
host_path = g_utf16_to_utf8 (host_path_ucs2, -1, NULL, NULL, NULL);
g_free (host_path_ucs2);
}
#endif
}
if (host_path)
// quote + string + quote
total_size += strlen (host_path) + 2;
for (int i = 0; i < argc; ++i) {
if (argv [i]) {
if (total_size > 0) {
// add space
total_size++;
}
// quote + string + quote
total_size += strlen (argv [i]) + 2;
}
}
// String will grow if needed, so not over allocating
// to handle case of escaped characters in arguments, if
// that happens string will automatically grow.
cmd_line = g_string_sized_new (total_size + 1);
if (cmd_line) {
if (host_path)
cmd_line = quote_escape_and_append_string (host_path, cmd_line);
for (int i = 0; i < argc; ++i) {
if (argv [i]) {
if (cmd_line->len > 0) {
// add space
cmd_line = g_string_append_c (cmd_line, ' ');
}
cmd_line = quote_escape_and_append_string (argv [i], cmd_line);
}
}
}
g_free (host_path);
return cmd_line;
}
char *
mono_runtime_get_cmd_line (int argc, char **argv)
{
MONO_REQ_GC_NEUTRAL_MODE;
GString *cmd_line = format_cmd_line (num_main_args, main_args, FALSE);
return cmd_line ? g_string_free (cmd_line, FALSE) : NULL;
}
char *
mono_runtime_get_managed_cmd_line (void)
{
MONO_REQ_GC_NEUTRAL_MODE;
GString *cmd_line = format_cmd_line (num_main_args, main_args, TRUE);
return cmd_line ? g_string_free (cmd_line, FALSE) : NULL;
}
#if NEVER_DEFINED
/*
* The following section is purely to declare prototypes and
* document the API, as these C files are processed by our
* tool
*/
/**
* mono_array_set:
* \param array array to alter
* \param element_type A C type name, this macro will use the sizeof(type) to determine the element size
* \param index index into the array
* \param value value to set
* Value Type version: This sets the \p index's element of the \p array
* with elements of size sizeof(type) to the provided \p value.
*
* This macro does not attempt to perform type checking or bounds checking
* and it doesn't execute any write barriers.
*
* Use this to set value types in a \c MonoArray. This shouldn't be used if
* the copied value types contain references. Use \c mono_gc_wbarrier_value_copy
* instead when also copying references.
*/
void mono_array_set(MonoArray *array, Type element_type, uintptr_t index, Value value)
{
}
/**
* mono_array_setref:
* \param array array to alter
* \param index index into the array
* \param value value to set
* Reference Type version. This sets the \p index's element of the
* \p array with elements of size sizeof(type) to the provided \p value.
*
* This macro does not attempt to perform type checking or bounds checking.
*
* Use this to reference types in a \c MonoArray.
*/
void mono_array_setref(MonoArray *array, uintptr_t index, MonoObject *object)
{
}
/**
* mono_array_get:
* \param array array on which to operate on
* \param element_type C element type (example: \c MonoString*, \c int, \c MonoObject*)
* \param index index into the array
*
* Use this macro to retrieve the \p index element of an \p array and
* extract the value assuming that the elements of the array match
* the provided type value.
*
* This method can be used with both arrays holding value types and
* reference types. For reference types, the \p type parameter should
* be a \c MonoObject* or any subclass of it, like \c MonoString*.
*
* This macro does not attempt to perform type checking or bounds checking.
*
* \returns The element at the \p index position in the \p array.
*/
Type mono_array_get_internal (MonoArray *array, Type element_type, uintptr_t index)
{
}
#endif
| /**
* \file
* Object creation for the Mono runtime
*
* Author:
* Miguel de Icaza ([email protected])
* Paolo Molaro ([email protected])
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2011 Novell, Inc (http://www.novell.com)
* Copyright 2001 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>
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/object.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/domain-internals.h>
#include "mono/metadata/metadata-internals.h"
#include "mono/metadata/class-internals.h"
#include "mono/metadata/class-init.h"
#include <mono/metadata/assembly.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/mono-hash-internals.h>
#include "mono/metadata/debug-helpers.h"
#include <mono/metadata/threads.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/environment.h>
#include "mono/metadata/profiler-private.h"
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/w32event.h>
#include <mono/metadata/w32process.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/runtime.h>
#include <mono/metadata/metadata-update.h>
#include <mono/utils/strenc.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/mono-logger-internals.h>
#include "cominterop.h"
#include <mono/utils/w32api.h>
#include <mono/utils/unlocked.h>
#include "external-only.h"
#include "monitor.h"
#include "icall-decl.h"
#include "icall-signatures.h"
#if _MSC_VER
#pragma warning(disable:4312) // FIXME pointer cast to different size
#endif
// If no symbols in an object file in a static library are referenced, its exports will not be exported.
// There are a few workarounds:
// 1. Link to .o/.obj files directly on the link command line,
// instead of putting them in static libraries.
// 2. Use a Windows .def file, or exports on command line, or Unix equivalent.
// 3. Have a reference to at least one symbol in the .o/.obj.
// That is effectively what this include does.
#include "external-only.c"
static void
get_default_field_value (MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error);
static void
mono_ldstr_metadata_sig (const char* sig, MonoStringHandleOut string_handle, MonoError *error);
static void
free_main_args (void);
static char *
mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s, MonoError *error);
static char *
mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s, MonoError *error);
/* Class lazy loading functions */
static GENERATE_GET_CLASS_WITH_CACHE (pointer, "System.Reflection", "Pointer")
static GENERATE_GET_CLASS_WITH_CACHE (unhandled_exception_event_args, "System", "UnhandledExceptionEventArgs")
static GENERATE_GET_CLASS_WITH_CACHE (first_chance_exception_event_args, "System.Runtime.ExceptionServices", "FirstChanceExceptionEventArgs")
static GENERATE_GET_CLASS_WITH_CACHE (sta_thread_attribute, "System", "STAThreadAttribute")
static GENERATE_GET_CLASS_WITH_CACHE (activation_services, "System.Runtime.Remoting.Activation", "ActivationServices")
static GENERATE_TRY_GET_CLASS_WITH_CACHE (execution_context, "System.Threading", "ExecutionContext")
#define ldstr_lock() mono_coop_mutex_lock (&ldstr_section)
#define ldstr_unlock() mono_coop_mutex_unlock (&ldstr_section)
static MonoCoopMutex ldstr_section;
/* Used by remoting proxies */
static MonoMethod *create_proxy_for_type_method;
static MonoGHashTable *ldstr_table;
static GString *
quote_escape_and_append_string (char *src_str, GString *target_str);
static GString *
format_cmd_line (int argc, char **argv, gboolean add_host);
/**
* mono_runtime_object_init:
* \param this_obj the object to initialize
* This function calls the zero-argument constructor (which must
* exist) for the given object.
*/
void
mono_runtime_object_init (MonoObject *this_obj)
{
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
mono_runtime_object_init_checked (this_obj, error);
mono_error_assert_ok (error);
MONO_EXIT_GC_UNSAFE;
}
/**
* mono_runtime_object_init_handle:
* \param this_obj the object to initialize
* \param error set on error.
* This function calls the zero-argument constructor (which must
* exist) for the given object and returns TRUE on success, or FALSE
* on error and sets \p error.
*/
gboolean
mono_runtime_object_init_handle (MonoObjectHandle this_obj, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
error_init (error);
MonoClass * const klass = MONO_HANDLE_GETVAL (this_obj, vtable)->klass;
MonoMethod * const method = mono_class_get_method_from_name_checked (klass, ".ctor", 0, 0, error);
mono_error_assert_msg_ok (error, "Could not lookup zero argument constructor");
g_assertf (method, "Could not lookup zero argument constructor for class %s", mono_type_get_full_name (klass));
if (m_class_is_valuetype (method->klass)) {
MonoGCHandle gchandle = NULL;
gpointer raw = mono_object_handle_pin_unbox (this_obj, &gchandle);
mono_runtime_invoke_checked (method, raw, NULL, error);
mono_gchandle_free_internal (gchandle);
} else {
mono_runtime_invoke_handle_void (method, this_obj, NULL, error);
}
HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
}
/**
* mono_runtime_object_init_checked:
* \param this_obj the object to initialize
* \param error set on error.
* This function calls the zero-argument constructor (which must
* exist) for the given object and returns TRUE on success, or FALSE
* on error and sets \p error.
*/
gboolean
mono_runtime_object_init_checked (MonoObject *this_obj_raw, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, this_obj);
gboolean const result = mono_runtime_object_init_handle (this_obj, error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/* The pseudo algorithm for type initialization from the spec
Note it doesn't say anything about domains - only threads.
2. If the type is initialized you are done.
2.1. If the type is not yet initialized, try to take an
initialization lock.
2.2. If successful, record this thread as responsible for
initializing the type and proceed to step 2.3.
2.2.1. If not, see whether this thread or any thread
waiting for this thread to complete already holds the lock.
2.2.2. If so, return since blocking would create a deadlock. This thread
will now see an incompletely initialized state for the type,
but no deadlock will arise.
2.2.3 If not, block until the type is initialized then return.
2.3 Initialize the parent type and then all interfaces implemented
by this type.
2.4 Execute the type initialization code for this type.
2.5 Mark the type as initialized, release the initialization lock,
awaken any threads waiting for this type to be initialized,
and return.
*/
typedef struct
{
MonoNativeThreadId initializing_tid;
guint32 waiting_count;
gboolean done;
MonoCoopMutex mutex;
/* condvar used to wait for 'done' becoming TRUE */
MonoCoopCond cond;
} TypeInitializationLock;
/* for locking access to type_initialization_hash and blocked_thread_hash */
static MonoCoopMutex type_initialization_section;
static void
mono_type_initialization_lock (void)
{
/* The critical sections protected by this lock in mono_runtime_class_init_full () can block */
mono_coop_mutex_lock (&type_initialization_section);
}
static void
mono_type_initialization_unlock (void)
{
mono_coop_mutex_unlock (&type_initialization_section);
}
static void
mono_type_init_lock (TypeInitializationLock *lock)
{
MONO_REQ_GC_NEUTRAL_MODE;
mono_coop_mutex_lock (&lock->mutex);
}
static void
mono_type_init_unlock (TypeInitializationLock *lock)
{
mono_coop_mutex_unlock (&lock->mutex);
}
/* from vtable to lock */
static GHashTable *type_initialization_hash;
/* from thread id to thread id being waited on */
static GHashTable *blocked_thread_hash;
/* Main thread */
static MonoThread *main_thread;
/* Functions supplied by the runtime */
static MonoRuntimeCallbacks callbacks;
/**
* mono_thread_set_main:
* \param thread thread to set as the main thread
* This function can be used to instruct the runtime to treat \p thread
* as the main thread, ie, the thread that would normally execute the \c Main
* method. This basically means that at the end of \p thread, the runtime will
* wait for the existing foreground threads to quit and other such details.
*/
void
mono_thread_set_main (MonoThread *thread)
{
MONO_REQ_GC_UNSAFE_MODE;
static gboolean registered = FALSE;
if (!registered) {
void *key = thread->internal_thread ? (gpointer)(gsize) MONO_UINT_TO_NATIVE_THREAD_ID (thread->internal_thread->tid) : NULL;
MONO_GC_REGISTER_ROOT_SINGLE (main_thread, MONO_ROOT_SOURCE_THREADING, key, "Thread Main Object");
registered = TRUE;
}
main_thread = thread;
}
/**
* mono_thread_get_main:
*/
MonoThread*
mono_thread_get_main (void)
{
MONO_REQ_GC_UNSAFE_MODE;
return main_thread;
}
void
mono_type_initialization_init (void)
{
mono_coop_mutex_init_recursive (&type_initialization_section);
type_initialization_hash = g_hash_table_new (NULL, NULL);
blocked_thread_hash = g_hash_table_new (NULL, NULL);
mono_coop_mutex_init (&ldstr_section);
mono_register_jit_icall (ves_icall_string_alloc, mono_icall_sig_object_int, FALSE);
}
static MonoException*
mono_get_exception_type_initialization_checked (const gchar *type_name, MonoException* inner_raw, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoException, inner);
HANDLE_FUNCTION_RETURN_OBJ (mono_get_exception_type_initialization_handle (type_name, inner, error));
}
/**
* get_type_init_exception_for_vtable:
*
* Return the stored type initialization exception for VTABLE.
*/
static MonoException*
get_type_init_exception_for_vtable (MonoVTable *vtable)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoClass *klass = vtable->klass;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
MonoException *ex;
gchar *full_name;
if (!vtable->init_failed)
g_error ("Trying to get the init exception for a non-failed vtable of class %s", mono_type_get_full_name (klass));
/*
* If the initializing thread was rudely aborted, the exception is not stored
* in the hash.
*/
ex = NULL;
mono_mem_manager_lock (mem_manager);
ex = (MonoException *)mono_g_hash_table_lookup (mem_manager->type_init_exception_hash, klass);
mono_mem_manager_unlock (mem_manager);
if (!ex) {
const char *klass_name_space = m_class_get_name_space (klass);
const char *klass_name = m_class_get_name (klass);
if (klass_name_space && *klass_name_space)
full_name = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
else
full_name = g_strdup (klass_name);
ex = mono_get_exception_type_initialization_checked (full_name, NULL, error);
g_free (full_name);
return_val_if_nok (error, NULL);
}
return ex;
}
/**
* mono_runtime_class_init:
* \param vtable vtable that needs to be initialized
* This routine calls the class constructor for \p vtable.
*/
void
mono_runtime_class_init (MonoVTable *vtable)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
mono_runtime_class_init_full (vtable, error);
mono_error_assert_ok (error);
}
/*
* Returns TRUE if the lock was freed.
* LOCKING: Caller should hold type_initialization_lock.
*/
static gboolean
unref_type_lock (TypeInitializationLock *lock)
{
--lock->waiting_count;
if (lock->waiting_count == 0) {
mono_coop_mutex_destroy (&lock->mutex);
mono_coop_cond_destroy (&lock->cond);
g_free (lock);
return TRUE;
} else {
return FALSE;
}
}
/**
* mono_runtime_run_module_cctor:
* \param image the image whose module ctor to run
* \param error set on error
* This routine runs the module ctor for \p image, if it hasn't already run
*/
gboolean
mono_runtime_run_module_cctor (MonoImage *image, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!image->checked_module_cctor) {
mono_image_check_for_module_cctor (image);
if (image->has_module_cctor) {
MonoClass *module_klass;
MonoVTable *module_vtable;
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE, "Running module .cctor for '%s'", image->name);
module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, error);
if (!module_klass) {
return FALSE;
}
module_vtable = mono_class_vtable_checked (module_klass, error);
if (!module_vtable)
return FALSE;
if (!mono_runtime_class_init_full (module_vtable, error))
return FALSE;
}
}
return TRUE;
}
/**
* mono_runtime_class_init_full:
* \param vtable that neeeds to be initialized
* \param error set on error
* \returns TRUE if class constructor \c .cctor has been initialized successfully, or FALSE otherwise and sets \p error.
*/
gboolean
mono_runtime_class_init_full (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (vtable->initialized)
return TRUE;
MonoClass *klass = vtable->klass;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
MonoImage *klass_image = m_class_get_image (klass);
if (!mono_runtime_run_module_cctor (klass_image, error)) {
return FALSE;
}
MonoMethod *method = mono_class_get_cctor (klass);
if (!method) {
vtable->initialized = 1;
return TRUE;
}
MonoNativeThreadId tid = mono_native_thread_id_get ();
/*
* Due some preprocessing inside a global lock. If we are the first thread
* trying to initialize this class, create a separate lock+cond var, and
* acquire it before leaving the global lock. The other threads will wait
* on this cond var.
*/
mono_type_initialization_lock ();
/* double check... */
if (vtable->initialized) {
mono_type_initialization_unlock ();
return TRUE;
}
gboolean do_initialization = FALSE;
TypeInitializationLock *lock = NULL;
gboolean pending_tae = FALSE;
gboolean ret = FALSE;
HANDLE_FUNCTION_ENTER ();
if (vtable->init_failed) {
/* The type initialization already failed once, rethrow the same exception */
MonoException *exp = get_type_init_exception_for_vtable (vtable);
MONO_HANDLE_NEW (MonoException, exp);
/* Reset the stack_trace and trace_ips because the exception is reused */
exp->stack_trace = NULL;
exp->trace_ips = NULL;
mono_type_initialization_unlock ();
mono_error_set_exception_instance (error, exp);
goto return_false;
}
lock = (TypeInitializationLock *)g_hash_table_lookup (type_initialization_hash, vtable);
if (lock == NULL) {
lock = (TypeInitializationLock *)g_malloc0 (sizeof (TypeInitializationLock));
mono_coop_mutex_init_recursive (&lock->mutex);
mono_coop_cond_init (&lock->cond);
lock->initializing_tid = tid;
lock->waiting_count = 1;
lock->done = FALSE;
g_hash_table_insert (type_initialization_hash, vtable, lock);
do_initialization = TRUE;
} else {
gpointer blocked;
TypeInitializationLock *pending_lock;
if (mono_native_thread_id_equals (lock->initializing_tid, tid)) {
mono_type_initialization_unlock ();
goto return_true;
}
/* see if the thread doing the initialization is already blocked on this thread */
gboolean is_blocked = TRUE;
blocked = GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (lock->initializing_tid));
while ((pending_lock = (TypeInitializationLock*) g_hash_table_lookup (blocked_thread_hash, blocked))) {
if (mono_native_thread_id_equals (pending_lock->initializing_tid, tid)) {
if (!pending_lock->done) {
mono_type_initialization_unlock ();
goto return_true;
} else {
/* the thread doing the initialization is blocked on this thread,
but on a lock that has already been freed. It just hasn't got
time to awake */
is_blocked = FALSE;
break;
}
}
blocked = GUINT_TO_POINTER (MONO_NATIVE_THREAD_ID_TO_UINT (pending_lock->initializing_tid));
}
++lock->waiting_count;
/* record the fact that we are waiting on the initializing thread */
if (is_blocked)
g_hash_table_insert (blocked_thread_hash, GUINT_TO_POINTER (tid), lock);
}
mono_type_initialization_unlock ();
if (do_initialization) {
MonoException *exc = NULL;
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE)) {
char* type_name = mono_type_full_name (m_class_get_byval_arg (klass));
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_TYPE, "Running class .cctor for %s from '%s'", type_name, m_class_get_image (klass)->name);
g_free (type_name);
}
/* We are holding the per-vtable lock, do the actual initialization */
mono_threads_begin_abort_protected_block ();
mono_runtime_try_invoke (method, NULL, NULL, (MonoObject**) &exc, error);
MonoExceptionHandle exch = MONO_HANDLE_NEW (MonoException, exc);
mono_threads_end_abort_protected_block ();
//exception extracted, error will be set to the right value later
if (exc == NULL && !is_ok (error)) { // invoking failed but exc was not set
exc = mono_error_convert_to_exception (error);
MONO_HANDLE_ASSIGN_RAW (exch, exc);
} else
mono_error_cleanup (error);
error_init_reuse (error);
const char *klass_name_space = m_class_get_name_space (klass);
const char *klass_name = m_class_get_name (klass);
/* If the initialization failed, mark the class as unusable. */
/* Avoid infinite loops */
if (!(!exc ||
(klass_image == mono_defaults.corlib &&
!strcmp (klass_name_space, "System") &&
!strcmp (klass_name, "TypeInitializationException")))) {
vtable->init_failed = 1;
char *full_name;
if (klass_name_space && *klass_name_space)
full_name = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
else
full_name = g_strdup (klass_name);
MonoException *exc_to_throw = mono_get_exception_type_initialization_checked (full_name, exc, error);
MONO_HANDLE_NEW (MonoException, exc_to_throw);
g_free (full_name);
mono_error_assert_ok (error); //We can't recover from this, no way to fail a type we can't alloc a failure.
/*
* Store the exception object so it could be thrown on subsequent
* accesses.
*/
mono_mem_manager_lock (mem_manager);
mono_g_hash_table_insert_internal (mem_manager->type_init_exception_hash, klass, exc_to_throw);
mono_mem_manager_unlock (mem_manager);
}
/* Signal to the other threads that we are done */
mono_type_init_lock (lock);
lock->done = TRUE;
mono_coop_cond_broadcast (&lock->cond);
mono_type_init_unlock (lock);
/*
* This can happen if the cctor self-aborts. We need to reactivate tae
* (next interruption checkpoint will throw it) and make sure we won't
* throw tie for the type.
*/
if (exc && mono_object_class (exc) == mono_defaults.threadabortexception_class) {
pending_tae = TRUE;
mono_thread_resume_interruption (FALSE);
}
} else {
/* this just blocks until the initializing thread is done */
mono_type_init_lock (lock);
while (!lock->done)
mono_coop_cond_wait (&lock->cond, &lock->mutex);
mono_type_init_unlock (lock);
}
/* Do cleanup and setting vtable->initialized inside the global lock again */
mono_type_initialization_lock ();
if (!do_initialization)
g_hash_table_remove (blocked_thread_hash, GUINT_TO_POINTER (tid));
{
gboolean deleted = unref_type_lock (lock);
if (deleted)
g_hash_table_remove (type_initialization_hash, vtable);
}
/* Have to set this here since we check it inside the global lock */
if (do_initialization && !vtable->init_failed)
vtable->initialized = 1;
mono_type_initialization_unlock ();
/* If vtable init fails because of TAE, we don't throw TIE, only the TAE */
if (vtable->init_failed && !pending_tae) {
/* Either we were the initializing thread or we waited for the initialization */
mono_error_set_exception_instance (error, get_type_init_exception_for_vtable (vtable));
goto return_false;
}
return_true:
ret = TRUE;
goto exit;
return_false:
ret = FALSE;
exit:
HANDLE_FUNCTION_RETURN_VAL (ret);
}
MonoDomain *
mono_vtable_domain_internal (MonoVTable *vtable)
{
return mono_get_root_domain ();
}
MonoDomain*
mono_vtable_domain (MonoVTable *vtable)
{
MONO_EXTERNAL_ONLY (MonoDomain*, mono_get_root_domain ());
}
MonoClass *
mono_vtable_class_internal (MonoVTable *vtable)
{
return vtable->klass;
}
MonoClass*
mono_vtable_class (MonoVTable *vtable)
{
MONO_EXTERNAL_ONLY (MonoClass*, mono_vtable_class_internal (vtable));
}
static
gboolean release_type_locks (gpointer key, gpointer value, gpointer user)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoVTable *vtable = (MonoVTable*)key;
TypeInitializationLock *lock = (TypeInitializationLock*) value;
if (mono_native_thread_id_equals (lock->initializing_tid, MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (user))) && !lock->done) {
lock->done = TRUE;
/*
* Have to set this since it cannot be set by the normal code in
* mono_runtime_class_init (). In this case, the exception object is not stored,
* and get_type_init_exception_for_class () needs to be aware of this.
*/
mono_type_init_lock (lock);
vtable->init_failed = 1;
mono_coop_cond_broadcast (&lock->cond);
mono_type_init_unlock (lock);
gboolean deleted = unref_type_lock (lock);
if (deleted)
return TRUE;
}
return FALSE;
}
void
mono_release_type_locks (MonoInternalThread *thread)
{
MONO_REQ_GC_UNSAFE_MODE;
mono_type_initialization_lock ();
g_hash_table_foreach_remove (type_initialization_hash, release_type_locks, GUINT_TO_POINTER (thread->tid));
mono_type_initialization_unlock ();
}
static MonoImtTrampolineBuilder imt_trampoline_builder;
static gboolean always_build_imt_trampolines;
#if (MONO_IMT_SIZE > 32)
#error "MONO_IMT_SIZE cannot be larger than 32"
#endif
void
mono_install_callbacks (MonoRuntimeCallbacks *cbs)
{
memcpy (&callbacks, cbs, sizeof (*cbs));
}
MonoRuntimeCallbacks*
mono_get_runtime_callbacks (void)
{
return &callbacks;
}
void
mono_install_imt_trampoline_builder (MonoImtTrampolineBuilder func)
{
imt_trampoline_builder = func;
}
void
mono_set_always_build_imt_trampolines (gboolean value)
{
always_build_imt_trampolines = value;
}
/**
* mono_compile_method:
* \param method The method to compile.
* This JIT-compiles the method, and returns the pointer to the native code
* produced.
*/
gpointer
mono_compile_method (MonoMethod *method)
{
gpointer result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_compile_method_checked (method, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_compile_method_checked:
* \param method The method to compile.
* \param error set on error.
* This JIT-compiles the method, and returns the pointer to the native code
* produced. On failure returns NULL and sets \p error.
*/
gpointer
mono_compile_method_checked (MonoMethod *method, MonoError *error)
{
gpointer res;
MONO_REQ_GC_NEUTRAL_MODE
error_init (error);
g_assert (callbacks.compile_method);
res = callbacks.compile_method (method, error);
return res;
}
gpointer
mono_runtime_create_delegate_trampoline (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE
g_assert (callbacks.create_delegate_trampoline);
return callbacks.create_delegate_trampoline (klass);
}
/**
* mono_runtime_free_method:
* \param method method to release
* This routine is invoked to free the resources associated with
* a method that has been JIT compiled. This is used to discard
* methods that were used only temporarily (for example, used in marshalling)
*/
void
mono_runtime_free_method (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE
if (callbacks.free_method)
callbacks.free_method (method);
mono_method_clear_object (method);
mono_free_method (method);
}
/*
* The vtables in the root appdomain are assumed to be reachable by other
* roots, and we don't use typed allocation in the other domains.
*/
/* The sync block is no longer a GC pointer */
#define GC_HEADER_BITMAP (0)
#define BITMAP_EL_SIZE (sizeof (gsize) * 8)
#define MONO_OBJECT_HEADER_BITS (MONO_ABI_SIZEOF (MonoObject) / MONO_ABI_SIZEOF (gpointer))
static gsize*
compute_class_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int *max_set, gboolean static_fields)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoClassField *field;
MonoClass *p;
guint32 pos;
int max_size, wordsize;
wordsize = TARGET_SIZEOF_VOID_P;
if (static_fields)
max_size = mono_class_data_size (klass) / wordsize;
else
max_size = m_class_get_instance_size (klass) / wordsize;
if (max_size > size) {
g_assert (offset <= 0);
bitmap = (gsize *)g_malloc0 ((max_size + BITMAP_EL_SIZE - 1) / BITMAP_EL_SIZE * sizeof (gsize));
size = max_size;
}
/* An Ephemeron cannot be marked by sgen */
if (mono_gc_is_moving () && !static_fields && m_class_get_image (klass) == mono_defaults.corlib && !strcmp ("Ephemeron", m_class_get_name (klass))) {
*max_set = 0;
memset (bitmap, 0, size / 8);
return bitmap;
}
for (p = klass; p != NULL; p = m_class_get_parent (p)) {
gpointer iter = NULL;
while ((field = mono_class_get_fields_internal (p, &iter))) {
MonoType *type;
if (static_fields) {
if (!(field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)))
continue;
if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
continue;
} else {
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
}
/* FIXME: should not happen, flag as type load error */
if (m_type_is_byref (field->type))
break;
if (static_fields && field->offset == -1)
/* special static */
continue;
pos = field->offset / TARGET_SIZEOF_VOID_P;
pos += offset;
type = mono_type_get_underlying_type (field->type);
switch (type->type) {
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
break;
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
g_assert ((field->offset % wordsize) == 0);
g_assert (pos < size || pos <= max_size);
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
*max_set = MAX (*max_set, pos);
break;
case MONO_TYPE_GENERICINST:
if (!mono_type_generic_inst_is_valuetype (type)) {
g_assert ((field->offset % wordsize) == 0);
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
*max_set = MAX (*max_set, pos);
break;
} else {
/* fall through */
}
case MONO_TYPE_TYPEDBYREF:
case MONO_TYPE_VALUETYPE: {
MonoClass *fclass = mono_class_from_mono_type_internal (field->type);
if (m_class_has_references (fclass)) {
/* remove the object header */
compute_class_bitmap (fclass, bitmap, size, pos - MONO_OBJECT_HEADER_BITS, max_set, FALSE);
}
break;
}
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_BOOLEAN:
case MONO_TYPE_CHAR:
break;
default:
g_error ("compute_class_bitmap: Invalid type %x for field %s:%s\n", type->type, mono_type_get_full_name (m_field_get_parent (field)), field->name);
break;
}
}
if (static_fields)
break;
}
return bitmap;
}
/**
* mono_class_compute_bitmap:
*
* Mono internal function to compute a bitmap of reference fields in a class.
*/
gsize*
mono_class_compute_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int *max_set, gboolean static_fields)
{
MONO_REQ_GC_NEUTRAL_MODE;
return compute_class_bitmap (klass, bitmap, size, offset, max_set, static_fields);
}
#if 0
/*
* similar to the above, but sets the bits in the bitmap for any non-ref field
* and ignores static fields
*/
static gsize*
compute_class_non_ref_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset)
{
MonoClassField *field;
MonoClass *p;
guint32 pos, pos2;
int max_size, wordsize;
wordsize = TARGET_SIZEOF_VOID_P;
max_size = class->instance_size / wordsize;
if (max_size >= size)
bitmap = g_malloc0 (sizeof (gsize) * ((max_size) + 1));
for (p = class; p != NULL; p = p->parent) {
gpointer iter = NULL;
while ((field = mono_class_get_fields_internal (p, &iter))) {
MonoType *type;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
/* FIXME: should not happen, flag as type load error */
if (m_type_is_byref (field->type))
break;
pos = field->offset / wordsize;
pos += offset;
type = mono_type_get_underlying_type (field->type);
switch (type->type) {
#if SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
#endif
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R8:
if ((((field->offset + 7) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 7) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
#if SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
#endif
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_R4:
if ((((field->offset + 3) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 3) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
case MONO_TYPE_CHAR:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
if ((((field->offset + 1) / wordsize) + offset) != pos) {
pos2 = ((field->offset + 1) / wordsize) + offset;
bitmap [pos2 / BITMAP_EL_SIZE] |= ((gsize)1) << (pos2 % BITMAP_EL_SIZE);
}
/* fall through */
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
break;
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
break;
case MONO_TYPE_GENERICINST:
if (!mono_type_generic_inst_is_valuetype (type)) {
break;
} else {
/* fall through */
}
case MONO_TYPE_VALUETYPE: {
MonoClass *fclass = mono_class_from_mono_type_internal (field->type);
/* remove the object header */
compute_class_non_ref_bitmap (fclass, bitmap, size, pos - MONO_OBJECT_HEADER_BITS);
break;
}
default:
g_assert_not_reached ();
break;
}
}
}
return bitmap;
}
/**
* mono_class_insecure_overlapping:
* check if a class with explicit layout has references and non-references
* fields overlapping.
*
* Returns: TRUE if it is insecure to load the type.
*/
gboolean
mono_class_insecure_overlapping (MonoClass *klass)
{
int max_set = 0;
gsize *bitmap;
gsize default_bitmap [4] = {0};
gsize *nrbitmap;
gsize default_nrbitmap [4] = {0};
int i, insecure = FALSE;
return FALSE;
bitmap = compute_class_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, FALSE);
nrbitmap = compute_class_non_ref_bitmap (klass, default_nrbitmap, sizeof (default_nrbitmap) * 8, 0);
for (i = 0; i <= max_set; i += sizeof (bitmap [0]) * 8) {
int idx = i % (sizeof (bitmap [0]) * 8);
if (bitmap [idx] & nrbitmap [idx]) {
insecure = TRUE;
break;
}
}
if (bitmap != default_bitmap)
g_free (bitmap);
if (nrbitmap != default_nrbitmap)
g_free (nrbitmap);
if (insecure) {
g_print ("class %s.%s in assembly %s has overlapping references\n", klass->name_space, klass->name, klass->image->name);
return FALSE;
}
return insecure;
}
#endif
MonoStringHandle
ves_icall_string_alloc_impl (int length, MonoError *error)
{
MonoString *s = mono_string_new_size_checked (length, error);
return_val_if_nok (error, NULL_HANDLE_STRING);
return MONO_HANDLE_NEW (MonoString, s);
}
#define BITMAP_EL_SIZE (sizeof (gsize) * 8)
/* LOCKING: Acquires the loader lock */
/*
* Sets the following fields in KLASS:
* - gc_desc
* - gc_descr_inited
*/
void
mono_class_compute_gc_descriptor (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE;
int max_set = 0;
gsize *bitmap;
gsize default_bitmap [4] = {0};
MonoGCDescriptor gc_descr;
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
if (m_class_is_gc_descr_inited (klass))
return;
bitmap = default_bitmap;
if (klass == mono_defaults.string_class) {
gc_descr = mono_gc_make_descr_for_string (bitmap, 2);
} else if (m_class_get_rank (klass)) {
MonoClass *klass_element_class = m_class_get_element_class (klass);
mono_class_compute_gc_descriptor (klass_element_class);
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (klass_element_class))) {
gsize abm = 1;
gc_descr = mono_gc_make_descr_for_array (m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY, &abm, 1, sizeof (gpointer));
/*printf ("new array descriptor: 0x%x for %s.%s\n", class->gc_descr,
class->name_space, class->name);*/
} else {
/* remove the object header */
bitmap = mono_class_compute_bitmap (klass_element_class, default_bitmap, sizeof (default_bitmap) * 8, - (int)(MONO_OBJECT_HEADER_BITS), &max_set, FALSE);
gc_descr = mono_gc_make_descr_for_array (m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY, bitmap, mono_array_element_size (klass) / sizeof (gpointer), mono_array_element_size (klass));
/*printf ("new vt array descriptor: 0x%x for %s.%s\n", class->gc_descr,
class->name_space, class->name);*/
}
} else {
/*static int count = 0;
if (count++ > 58)
return;*/
bitmap = mono_class_compute_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, FALSE);
/*
if (class->gc_descr == MONO_GC_DESCRIPTOR_NULL)
g_print ("disabling typed alloc (%d) for %s.%s\n", max_set, class->name_space, class->name);
*/
/*printf ("new descriptor: %p 0x%x for %s.%s\n", class->gc_descr, bitmap [0], class->name_space, class->name);*/
#ifdef ENABLE_WEAK_ATTR
if (m_class_has_weak_fields (klass)) {
gsize *weak_bitmap = NULL;
int weak_bitmap_nbits = 0;
weak_bitmap = (gsize *)mono_class_alloc0 (klass, m_class_get_instance_size (klass) / sizeof (gsize));
if (mono_class_has_static_metadata (klass)) {
for (MonoClass *p = klass; p != NULL; p = m_class_get_parent (p)) {
gpointer iter = NULL;
guint32 first_field_idx = mono_class_get_first_field_idx (p);
MonoClassField *field;
MonoClassField *p_fields = m_class_get_fields (p);
MonoImage *p_image = m_class_get_image (p);
while ((field = mono_class_get_fields_internal (p, &iter))) {
guint32 field_idx = first_field_idx + (field - p_fields);
if (MONO_TYPE_IS_REFERENCE (field->type) && mono_assembly_is_weak_field (p_image, field_idx + 1)) {
int pos = field->offset / sizeof (gpointer);
if (pos + 1 > weak_bitmap_nbits)
weak_bitmap_nbits = pos + 1;
weak_bitmap [pos / BITMAP_EL_SIZE] |= ((gsize)1) << (pos % BITMAP_EL_SIZE);
}
}
}
}
for (int pos = 0; pos < weak_bitmap_nbits; ++pos) {
if (weak_bitmap [pos / BITMAP_EL_SIZE] & ((gsize)1) << (pos % BITMAP_EL_SIZE)) {
/* Clear the normal bitmap so these refs don't keep an object alive */
bitmap [pos / BITMAP_EL_SIZE] &= ~(((gsize)1) << (pos % BITMAP_EL_SIZE));
}
}
mono_loader_lock ();
mono_class_set_weak_bitmap (klass, weak_bitmap_nbits, weak_bitmap);
mono_loader_unlock ();
}
#endif
gc_descr = mono_gc_make_descr_for_object (bitmap, max_set + 1, m_class_get_instance_size (klass));
}
if (bitmap != default_bitmap)
g_free (bitmap);
/* Publish the data */
mono_class_publish_gc_descriptor (klass, gc_descr);
}
/**
* field_is_special_static:
* @fklass: The MonoClass to look up.
* @field: The MonoClassField describing the field.
*
* Returns: SPECIAL_STATIC_THREAD if the field is thread static, SPECIAL_STATIC_NONE otherwise.
*/
static gint32
field_is_special_static (MonoClass *fklass, MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE;
ERROR_DECL (error);
MonoCustomAttrInfo *ainfo;
int i;
ainfo = mono_custom_attrs_from_field_checked (fklass, field, error);
mono_error_cleanup (error); /* FIXME don't swallow the error? */
if (!ainfo)
return FALSE;
for (i = 0; i < ainfo->num_attrs; ++i) {
MonoClass *klass = ainfo->attrs [i].ctor->klass;
if (m_class_get_image (klass) == mono_defaults.corlib) {
const char *klass_name = m_class_get_name (klass);
if (strcmp (klass_name, "ThreadStaticAttribute") == 0) {
mono_custom_attrs_free (ainfo);
return SPECIAL_STATIC_THREAD;
}
}
}
mono_custom_attrs_free (ainfo);
return SPECIAL_STATIC_NONE;
}
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) { \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define mono_final(a,b,c) { \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
/*
* mono_method_get_imt_slot:
*
* The IMT slot is embedded into AOTed code, so this must return the same value
* for the same method across all executions. This means:
* - pointers shouldn't be used as hash values.
* - mono_metadata_str_hash () should be used for hashing strings.
*/
guint32
mono_method_get_imt_slot (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethodSignature *sig;
int hashes_count;
guint32 *hashes_start, *hashes;
guint32 a, b, c;
int i;
/* This can be used to stress tests the collision code */
//return 0;
/*
* We do this to simplify generic sharing. It will hurt
* performance in cases where a class implements two different
* instantiations of the same generic interface.
* The code in build_imt_slots () depends on this.
*/
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
sig = mono_method_signature_internal (method);
hashes_count = sig->param_count + 4;
hashes_start = (guint32 *)g_malloc (hashes_count * sizeof (guint32));
hashes = hashes_start;
if (! MONO_CLASS_IS_INTERFACE_INTERNAL (method->klass)) {
g_error ("mono_method_get_imt_slot: %s.%s.%s is not an interface MonoMethod",
m_class_get_name_space (method->klass), m_class_get_name (method->klass), method->name);
}
/* Initialize hashes */
hashes [0] = mono_metadata_str_hash (m_class_get_name (method->klass));
hashes [1] = mono_metadata_str_hash (m_class_get_name_space (method->klass));
hashes [2] = mono_metadata_str_hash (method->name);
hashes [3] = mono_metadata_type_hash (sig->ret);
for (i = 0; i < sig->param_count; i++) {
hashes [4 + i] = mono_metadata_type_hash (sig->params [i]);
}
/* Setup internal state */
a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
/* Handle most of the hashes */
while (hashes_count > 3) {
a += hashes [0];
b += hashes [1];
c += hashes [2];
mix (a,b,c);
hashes_count -= 3;
hashes += 3;
}
/* Handle the last 3 hashes (all the case statements fall through) */
switch (hashes_count) {
case 3 : c += hashes [2];
case 2 : b += hashes [1];
case 1 : a += hashes [0];
mono_final (a,b,c);
case 0: /* nothing left to add */
break;
}
g_free (hashes_start);
/* Report the result */
return c % MONO_IMT_SIZE;
}
#undef rot
#undef mix
#undef mono_final
#define DEBUG_IMT 0
static void
add_imt_builder_entry (MonoImtBuilderEntry **imt_builder, MonoMethod *method, guint32 *imt_collisions_bitmap, int vtable_slot, int slot_num) {
MONO_REQ_GC_NEUTRAL_MODE;
guint32 imt_slot = mono_method_get_imt_slot (method);
MonoImtBuilderEntry *entry;
if (slot_num >= 0 && imt_slot != slot_num) {
/* we build just a single imt slot and this is not it */
return;
}
entry = (MonoImtBuilderEntry *)g_malloc0 (sizeof (MonoImtBuilderEntry));
entry->key = method;
entry->value.vtable_slot = vtable_slot;
entry->next = imt_builder [imt_slot];
if (imt_builder [imt_slot] != NULL) {
entry->children = imt_builder [imt_slot]->children + 1;
if (entry->children == 1) {
UnlockedIncrement (&mono_stats.imt_slots_with_collisions);
*imt_collisions_bitmap |= (1 << imt_slot);
}
} else {
entry->children = 0;
UnlockedIncrement (&mono_stats.imt_used_slots);
}
imt_builder [imt_slot] = entry;
#if DEBUG_IMT
{
char *method_name = mono_method_full_name (method, TRUE);
printf ("Added IMT slot for method (%p) %s: imt_slot = %d, vtable_slot = %d, colliding with other %d entries\n",
method, method_name, imt_slot, vtable_slot, entry->children);
g_free (method_name);
}
#endif
}
#if DEBUG_IMT
static void
print_imt_entry (const char* message, MonoImtBuilderEntry *e, int num) {
if (e != NULL) {
MonoMethod *method = e->key;
printf (" * %s [%d]: (%p) '%s.%s.%s'\n",
message,
num,
method,
method->klass->name_space,
method->klass->name,
method->name);
} else {
printf (" * %s: NULL\n", message);
}
}
#endif
static int
compare_imt_builder_entries (const void *p1, const void *p2) {
MonoImtBuilderEntry *e1 = *(MonoImtBuilderEntry**) p1;
MonoImtBuilderEntry *e2 = *(MonoImtBuilderEntry**) p2;
return (e1->key < e2->key) ? -1 : ((e1->key > e2->key) ? 1 : 0);
}
static int
imt_emit_ir (MonoImtBuilderEntry **sorted_array, int start, int end, GPtrArray *out_array)
{
MONO_REQ_GC_NEUTRAL_MODE;
int count = end - start;
int chunk_start = out_array->len;
if (count < 4) {
int i;
for (i = start; i < end; ++i) {
MonoIMTCheckItem *item = g_new0 (MonoIMTCheckItem, 1);
item->key = sorted_array [i]->key;
item->value = sorted_array [i]->value;
item->has_target_code = sorted_array [i]->has_target_code;
item->is_equals = TRUE;
if (i < end - 1)
item->check_target_idx = out_array->len + 1;
else
item->check_target_idx = 0;
g_ptr_array_add (out_array, item);
}
} else {
int middle = start + count / 2;
MonoIMTCheckItem *item = g_new0 (MonoIMTCheckItem, 1);
item->key = sorted_array [middle]->key;
item->is_equals = FALSE;
g_ptr_array_add (out_array, item);
imt_emit_ir (sorted_array, start, middle, out_array);
item->check_target_idx = imt_emit_ir (sorted_array, middle, end, out_array);
}
return chunk_start;
}
static GPtrArray*
imt_sort_slot_entries (MonoImtBuilderEntry *entries) {
MONO_REQ_GC_NEUTRAL_MODE;
int number_of_entries = entries->children + 1;
MonoImtBuilderEntry **sorted_array = (MonoImtBuilderEntry **)g_malloc (sizeof (MonoImtBuilderEntry*) * number_of_entries);
GPtrArray *result = g_ptr_array_new ();
MonoImtBuilderEntry *current_entry;
int i;
for (current_entry = entries, i = 0; current_entry != NULL; current_entry = current_entry->next, i++) {
sorted_array [i] = current_entry;
}
mono_qsort (sorted_array, number_of_entries, sizeof (MonoImtBuilderEntry*), compare_imt_builder_entries);
/*for (i = 0; i < number_of_entries; i++) {
print_imt_entry (" sorted array:", sorted_array [i], i);
}*/
imt_emit_ir (sorted_array, 0, number_of_entries, result);
g_free (sorted_array);
return result;
}
static gpointer
initialize_imt_slot (MonoVTable *vtable, MonoImtBuilderEntry *imt_builder_entry, gpointer fail_tramp)
{
MONO_REQ_GC_NEUTRAL_MODE;
if (imt_builder_entry != NULL) {
if (imt_builder_entry->children == 0 && !fail_tramp && !always_build_imt_trampolines) {
/* No collision, return the vtable slot contents */
return vtable->vtable [imt_builder_entry->value.vtable_slot];
} else {
/* Collision, build the trampoline */
GPtrArray *imt_ir = imt_sort_slot_entries (imt_builder_entry);
gpointer result;
int i;
result = imt_trampoline_builder (vtable,
(MonoIMTCheckItem**)imt_ir->pdata, imt_ir->len, fail_tramp);
for (i = 0; i < imt_ir->len; ++i)
g_free (g_ptr_array_index (imt_ir, i));
g_ptr_array_free (imt_ir, TRUE);
return result;
}
} else {
if (fail_tramp)
return fail_tramp;
else
/* Empty slot */
return NULL;
}
}
static MonoImtBuilderEntry*
get_generic_virtual_entries (MonoMemoryManager *mem_manager, gpointer *vtable_slot);
/*
* LOCKING: assume the loader lock is held
*
*/
static void
build_imt_slots (MonoClass *klass, MonoVTable *vt, gpointer* imt, GSList *extra_interfaces, int slot_num)
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
GSList *list_item;
guint32 imt_collisions_bitmap = 0;
MonoImtBuilderEntry **imt_builder = (MonoImtBuilderEntry **)g_calloc (MONO_IMT_SIZE, sizeof (MonoImtBuilderEntry*));
int method_count = 0;
gboolean record_method_count_for_max_collisions = FALSE;
gboolean has_generic_virtual = FALSE, has_variant_iface = FALSE;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (klass);
#if DEBUG_IMT
printf ("Building IMT for class %s.%s slot %d\n", m_class_get_name_space (klass), m_class_get_name (klass), slot_num);
#endif
int klass_interface_offsets_count = m_class_get_interface_offsets_count (klass);
MonoClass **klass_interfaces_packed = m_class_get_interfaces_packed (klass);
guint16 *klass_interface_offsets_packed = m_class_get_interface_offsets_packed (klass);
for (i = 0; i < klass_interface_offsets_count; ++i) {
MonoClass *iface = klass_interfaces_packed [i];
int interface_offset = klass_interface_offsets_packed [i];
int method_slot_in_interface, vt_slot;
if (mono_class_has_variant_generic_params (iface))
has_variant_iface = TRUE;
mono_class_setup_methods (iface);
vt_slot = interface_offset;
int mcount = mono_class_get_method_count (iface);
for (method_slot_in_interface = 0; method_slot_in_interface < mcount; method_slot_in_interface++) {
MonoMethod *method;
if (slot_num >= 0 && mono_class_is_ginst (iface)) {
/*
* The imt slot of the method is the same as for its declaring method,
* see the comment in mono_method_get_imt_slot (), so we can
* avoid inflating methods which will be discarded by
* add_imt_builder_entry anyway.
*/
method = mono_class_get_method_by_index (mono_class_get_generic_class (iface)->container_class, method_slot_in_interface);
if (m_method_is_static (method))
continue;
if (mono_method_get_imt_slot (method) != slot_num) {
vt_slot ++;
continue;
}
}
method = mono_class_get_method_by_index (iface, method_slot_in_interface);
if (method->is_generic) {
has_generic_virtual = TRUE;
vt_slot ++;
continue;
}
if (m_method_is_static (method))
continue;
if (method->flags & METHOD_ATTRIBUTE_VIRTUAL) {
add_imt_builder_entry (imt_builder, method, &imt_collisions_bitmap, vt_slot, slot_num);
vt_slot ++;
}
}
}
if (extra_interfaces) {
int interface_offset = m_class_get_vtable_size (klass);
for (list_item = extra_interfaces; list_item != NULL; list_item=list_item->next) {
MonoClass* iface = (MonoClass *)list_item->data;
int method_slot_in_interface;
int mcount = mono_class_get_method_count (iface);
for (method_slot_in_interface = 0; method_slot_in_interface < mcount; method_slot_in_interface++) {
MonoMethod *method = mono_class_get_method_by_index (iface, method_slot_in_interface);
if (method->is_generic)
has_generic_virtual = TRUE;
add_imt_builder_entry (imt_builder, method, &imt_collisions_bitmap, interface_offset + method_slot_in_interface, slot_num);
}
interface_offset += mcount;
}
}
for (i = 0; i < MONO_IMT_SIZE; ++i) {
/* overwrite the imt slot only if we're building all the entries or if
* we're building this specific one
*/
if (slot_num < 0 || i == slot_num) {
MonoImtBuilderEntry *entries = get_generic_virtual_entries (mem_manager, &imt [i]);
if (entries) {
if (imt_builder [i]) {
MonoImtBuilderEntry *entry;
/* Link entries with imt_builder [i] */
for (entry = entries; entry->next; entry = entry->next) {
#if DEBUG_IMT
MonoMethod *method = (MonoMethod*)entry->key;
char *method_name = mono_method_full_name (method, TRUE);
printf ("Added extra entry for method (%p) %s: imt_slot = %d\n", method, method_name, i);
g_free (method_name);
#endif
}
entry->next = imt_builder [i];
entries->children += imt_builder [i]->children + 1;
}
imt_builder [i] = entries;
}
if (has_generic_virtual || has_variant_iface) {
/*
* There might be collisions later when the the trampoline is expanded.
*/
imt_collisions_bitmap |= (1 << i);
/*
* The IMT trampoline might be called with an instance of one of the
* generic virtual methods, so has to fallback to the IMT trampoline.
*/
imt [i] = initialize_imt_slot (vt, imt_builder [i], callbacks.get_imt_trampoline (vt, i));
} else {
imt [i] = initialize_imt_slot (vt, imt_builder [i], NULL);
}
#if DEBUG_IMT
printf ("initialize_imt_slot[%d]: %p methods %d\n", i, imt [i], imt_builder [i]->children + 1);
#endif
}
if (imt_builder [i] != NULL) {
int methods_in_slot = imt_builder [i]->children + 1;
if (methods_in_slot > UnlockedRead (&mono_stats.imt_max_collisions_in_slot)) {
UnlockedWrite (&mono_stats.imt_max_collisions_in_slot, methods_in_slot);
record_method_count_for_max_collisions = TRUE;
}
method_count += methods_in_slot;
}
}
UnlockedAdd (&mono_stats.imt_number_of_methods, method_count);
if (record_method_count_for_max_collisions) {
UnlockedWrite (&mono_stats.imt_method_count_when_max_collisions, method_count);
}
for (i = 0; i < MONO_IMT_SIZE; i++) {
MonoImtBuilderEntry* entry = imt_builder [i];
while (entry != NULL) {
MonoImtBuilderEntry* next = entry->next;
g_free (entry);
entry = next;
}
}
g_free (imt_builder);
/* we OR the bitmap since we may build just a single imt slot at a time */
vt->imt_collisions_bitmap |= imt_collisions_bitmap;
}
/**
* mono_vtable_build_imt_slot:
* \param vtable virtual object table struct
* \param imt_slot slot in the IMT table
* Fill the given \p imt_slot in the IMT table of \p vtable with
* a trampoline or a trampoline for the case of collisions.
* This is part of the internal mono API.
* LOCKING: Take the loader lock.
*/
void
mono_vtable_build_imt_slot (MonoVTable* vtable, int imt_slot)
{
MONO_REQ_GC_NEUTRAL_MODE;
gpointer *imt = (gpointer*)vtable;
imt -= MONO_IMT_SIZE;
g_assert (imt_slot >= 0 && imt_slot < MONO_IMT_SIZE);
/* no support for extra interfaces: the proxy objects will need
* to build the complete IMT
* Update and heck needs to ahppen inside the proper domain lock, as all
* the changes made to a MonoVTable.
*/
mono_loader_lock ();
/* we change the slot only if it wasn't changed from the generic imt trampoline already */
if (!callbacks.imt_entry_inited (vtable, imt_slot))
build_imt_slots (vtable->klass, vtable, imt, NULL, imt_slot);
mono_loader_unlock ();
}
#define THUNK_THRESHOLD 10
typedef struct _GenericVirtualCase {
MonoMethod *method;
gpointer code;
int count;
struct _GenericVirtualCase *next;
} GenericVirtualCase;
/*
* get_generic_virtual_entries:
*
* Return IMT entries for the generic virtual method instances and
* variant interface methods for vtable slot
* VTABLE_SLOT.
*/
static MonoImtBuilderEntry*
get_generic_virtual_entries (MonoMemoryManager *mem_manager, gpointer *vtable_slot)
{
MONO_REQ_GC_NEUTRAL_MODE;
GenericVirtualCase *list;
MonoImtBuilderEntry *entries;
mono_mem_manager_lock (mem_manager);
if (!mem_manager->generic_virtual_cases)
mem_manager->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
list = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
entries = NULL;
for (; list; list = list->next) {
MonoImtBuilderEntry *entry;
if (list->count < THUNK_THRESHOLD)
continue;
entry = g_new0 (MonoImtBuilderEntry, 1);
entry->key = list->method;
entry->value.target_code = mono_get_addr_from_ftnptr (list->code);
entry->has_target_code = 1;
if (entries)
entry->children = entries->children + 1;
entry->next = entries;
entries = entry;
}
mono_mem_manager_unlock (mem_manager);
/* FIXME: Leaking memory ? */
return entries;
}
/**
* \param domain a domain
* \param vtable_slot pointer to the vtable slot
* \param method the inflated generic virtual method
* \param code the method's code
*
* Registers a call via unmanaged code to a generic virtual method
* instantiation or variant interface method. If the number of calls reaches a threshold
* (THUNK_THRESHOLD), the method is added to the vtable slot's generic
* virtual method trampoline.
*/
void
mono_method_add_generic_virtual_invocation (MonoVTable *vtable,
gpointer *vtable_slot,
MonoMethod *method, gpointer code)
{
MONO_REQ_GC_NEUTRAL_MODE;
static gboolean inited = FALSE;
static int num_added = 0;
static int num_freed = 0;
GenericVirtualCase *gvc, *list;
MonoImtBuilderEntry *entries;
GPtrArray *sorted;
MonoMemoryManager *mem_manager = m_class_get_mem_manager (vtable->klass);
mono_loader_lock ();
mono_mem_manager_lock (mem_manager);
if (!mem_manager->generic_virtual_cases)
mem_manager->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
if (!inited) {
mono_counters_register ("Generic virtual cases", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_added);
mono_counters_register ("Freed IMT trampolines", MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_freed);
inited = TRUE;
}
/* Check whether the case was already added */
list = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
gvc = list;
while (gvc) {
if (gvc->method == method)
break;
gvc = gvc->next;
}
/* If not found, make a new one */
if (!gvc) {
gvc = (GenericVirtualCase *)m_class_alloc (vtable->klass, sizeof (GenericVirtualCase));
gvc->method = method;
gvc->code = code;
gvc->count = 0;
gvc->next = (GenericVirtualCase *)g_hash_table_lookup (mem_manager->generic_virtual_cases, vtable_slot);
g_hash_table_insert (mem_manager->generic_virtual_cases, vtable_slot, gvc);
num_added++;
}
mono_mem_manager_unlock (mem_manager);
if (++gvc->count == THUNK_THRESHOLD) {
gpointer *old_thunk = (void **)*vtable_slot;
gpointer vtable_trampoline = NULL;
gpointer imt_trampoline = NULL;
if ((gpointer)vtable_slot < (gpointer)vtable) {
int displacement = (gpointer*)vtable_slot - (gpointer*)vtable;
int imt_slot = MONO_IMT_SIZE + displacement;
/* Force the rebuild of the trampoline at the next call */
imt_trampoline = callbacks.get_imt_trampoline (vtable, imt_slot);
*vtable_slot = imt_trampoline;
} else {
vtable_trampoline = callbacks.get_vtable_trampoline ? callbacks.get_vtable_trampoline (vtable, (gpointer*)vtable_slot - (gpointer*)vtable->vtable) : NULL;
entries = get_generic_virtual_entries (mem_manager, vtable_slot);
sorted = imt_sort_slot_entries (entries);
*vtable_slot = imt_trampoline_builder (vtable, (MonoIMTCheckItem**)sorted->pdata, sorted->len,
vtable_trampoline);
while (entries) {
MonoImtBuilderEntry *next = entries->next;
g_free (entries);
entries = next;
}
for (int i = 0; i < sorted->len; ++i)
g_free (g_ptr_array_index (sorted, i));
g_ptr_array_free (sorted, TRUE);
if (old_thunk != vtable_trampoline && old_thunk != imt_trampoline)
num_freed ++;
}
}
mono_loader_unlock ();
}
static MonoVTable *mono_class_create_runtime_vtable (MonoClass *klass, MonoError *error);
/**
* mono_class_vtable:
* \param domain the application domain
* \param class the class to initialize
* VTables are domain specific because we create domain specific code, and
* they contain the domain specific static class data.
* On failure, NULL is returned, and \c class->exception_type is set.
*/
MonoVTable *
mono_class_vtable (MonoDomain *domain, MonoClass *klass)
{
MonoVTable* vtable;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
vtable = mono_class_vtable_checked (klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return vtable;
}
/**
* mono_class_vtable_checked:
* \param class the class to initialize
* \param error set on failure.
* VTables are domain specific because we create domain specific code, and
* they contain the domain specific static class data.
*/
MonoVTable *
mono_class_vtable_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
error_init (error);
g_assert (klass);
if (mono_class_has_failure (klass)) {
mono_error_set_for_class_failure (error, klass);
return NULL;
}
vtable = m_class_get_runtime_vtable (klass);
if (vtable)
return vtable;
return mono_class_create_runtime_vtable (klass, error);
}
/**
* mono_class_try_get_vtable:
* \param class the class to initialize
* This function tries to get the associated vtable from \p class if
* it was already created.
*/
MonoVTable *
mono_class_try_get_vtable (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoVTable *vtable;
g_assert (klass);
vtable = m_class_get_runtime_vtable (klass);
if (vtable)
return vtable;
return NULL;
}
static gpointer*
alloc_vtable (MonoClass *klass, size_t vtable_size, size_t imt_table_bytes)
{
MONO_REQ_GC_NEUTRAL_MODE;
size_t alloc_offset;
/*
* We want the pointer to the MonoVTable aligned to 8 bytes because SGen uses three
* address bits. The IMT has an odd number of entries, however, so on 32 bits the
* alignment will be off. In that case we allocate 4 more bytes and skip over them.
*/
if (sizeof (gpointer) == 4 && (imt_table_bytes & 7)) {
g_assert ((imt_table_bytes & 7) == 4);
vtable_size += 4;
alloc_offset = 4;
} else {
alloc_offset = 0;
}
return (gpointer*) ((char*)m_class_alloc0 (klass, vtable_size) + alloc_offset);
}
static MonoVTable *
mono_class_create_runtime_vtable (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoVTable *vt;
MonoClassField *field;
MonoMemoryManager *mem_manager;
char *t;
int i, vtable_slots;
size_t imt_table_bytes;
int gc_bits;
guint32 vtable_size, class_size;
gpointer iter;
gpointer *interface_offsets;
gboolean is_primitive_type_array = FALSE;
gboolean use_interpreter = callbacks.is_interpreter_enabled ();
MonoDomain *domain = mono_get_root_domain ();
mono_loader_lock ();
vt = m_class_get_runtime_vtable (klass);
if (vt) {
mono_loader_unlock ();
goto exit;
}
if (!m_class_is_inited (klass) || mono_class_has_failure (klass)) {
if (!mono_class_init_internal (klass) || mono_class_has_failure (klass)) {
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
}
/* Array types require that their element type be valid*/
if (m_class_get_byval_arg (klass)->type == MONO_TYPE_ARRAY || m_class_get_byval_arg (klass)->type == MONO_TYPE_SZARRAY) {
MonoClass *element_class = m_class_get_element_class (klass);
is_primitive_type_array = m_class_is_primitive (element_class);
if (!m_class_is_inited (element_class))
mono_class_init_internal (element_class);
/*mono_class_init_internal can leave the vtable layout to be lazily done and we can't afford this here*/
if (!mono_class_has_failure (element_class) && !m_class_get_vtable_size (element_class))
mono_class_setup_vtable (element_class);
if (mono_class_has_failure (element_class)) {
/*Can happen if element_class only got bad after mono_class_setup_vtable*/
if (!mono_class_has_failure (klass))
mono_class_set_type_load_failure (klass, "");
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
}
/*
* For some classes, mono_class_init_internal () already computed klass->vtable_size, and
* that is all that is needed because of the vtable trampolines.
*/
if (!m_class_get_vtable_size (klass))
mono_class_setup_vtable (klass);
if (mono_class_is_ginst (klass) && !m_class_get_vtable (klass))
mono_class_check_vtable_constraints (klass, NULL);
/* Initialize klass->has_finalize */
mono_class_has_finalizer (klass);
if (mono_class_has_failure (klass)) {
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
goto return_null;
}
vtable_slots = m_class_get_vtable_size (klass);
/* we add an additional vtable slot to store the pointer to static field data only when needed */
class_size = mono_class_data_size (klass);
if (class_size)
vtable_slots++;
if (m_class_get_interface_offsets_count (klass)) {
imt_table_bytes = sizeof (gpointer) * (MONO_IMT_SIZE);
/* Interface table for the interpreter */
if (use_interpreter)
imt_table_bytes *= 2;
UnlockedIncrement (&mono_stats.imt_number_of_tables);
UnlockedAdd (&mono_stats.imt_tables_size, imt_table_bytes);
} else {
imt_table_bytes = 0;
}
vtable_size = imt_table_bytes + MONO_SIZEOF_VTABLE + vtable_slots * sizeof (gpointer);
UnlockedIncrement (&mono_stats.used_class_count);
UnlockedAdd (&mono_stats.class_vtable_size, vtable_size);
interface_offsets = alloc_vtable (klass, vtable_size, imt_table_bytes);
vt = (MonoVTable*) ((char*)interface_offsets + imt_table_bytes);
/* If on interp, skip the interp interface table */
if (use_interpreter)
interface_offsets = (gpointer*)((char*)interface_offsets + imt_table_bytes / 2);
g_assert (!((gsize)vt & 7));
vt->klass = klass;
vt->rank = m_class_get_rank (klass);
vt->domain = domain;
if ((vt->rank > 0) || klass == mono_get_string_class ())
vt->flags |= MONO_VT_FLAG_ARRAY_OR_STRING;
if (m_class_has_references (klass))
vt->flags |= MONO_VT_FLAG_HAS_REFERENCES;
if (is_primitive_type_array)
vt->flags |= MONO_VT_FLAG_ARRAY_IS_PRIMITIVE;
MONO_PROFILER_RAISE (vtable_loading, (vt));
mono_class_compute_gc_descriptor (klass);
vt->gc_descr = m_class_get_gc_descr (klass);
gc_bits = mono_gc_get_vtable_bits (klass);
g_assert (!(gc_bits & ~((1 << MONO_VTABLE_AVAILABLE_GC_BITS) - 1)));
vt->gc_bits = gc_bits;
if (class_size) {
/* we store the static field pointer at the end of the vtable: vt->vtable [class->vtable_size] */
if (m_class_has_static_refs (klass)) {
MonoGCDescriptor statics_gc_descr;
int max_set = 0;
gsize default_bitmap [4] = {0};
gsize *bitmap;
bitmap = compute_class_bitmap (klass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, TRUE);
/*g_print ("bitmap 0x%x for %s.%s (size: %d)\n", bitmap [0], klass->name_space, klass->name, class_size);*/
statics_gc_descr = mono_gc_make_descr_from_bitmap (bitmap, max_set + 1);
vt->vtable [m_class_get_vtable_size (klass)] = mono_gc_alloc_fixed (class_size, statics_gc_descr, MONO_ROOT_SOURCE_STATIC, vt, "Static Fields");
if (bitmap != default_bitmap)
g_free (bitmap);
} else {
vt->vtable [m_class_get_vtable_size (klass)] = m_class_alloc0 (klass, class_size);
}
vt->has_static_fields = TRUE;
UnlockedAdd (&mono_stats.class_static_data_size, class_size);
}
mem_manager = m_class_get_mem_manager (klass);
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (mono_field_is_deleted (field))
continue;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) {
gint32 special_static = m_class_has_no_special_static_fields (klass) ? SPECIAL_STATIC_NONE : field_is_special_static (klass, field);
if (special_static != SPECIAL_STATIC_NONE) {
guint32 size, offset;
gint32 align;
gsize default_bitmap [4] = {0};
gsize *bitmap;
int max_set = 0;
int numbits;
MonoClass *fclass;
if (mono_type_is_reference (field->type)) {
default_bitmap [0] = 1;
numbits = 1;
bitmap = default_bitmap;
} else if (mono_type_is_struct (field->type)) {
fclass = mono_class_from_mono_type_internal (field->type);
bitmap = compute_class_bitmap (fclass, default_bitmap, sizeof (default_bitmap) * 8, - (int)(MONO_OBJECT_HEADER_BITS), &max_set, FALSE);
numbits = max_set + 1;
} else {
default_bitmap [0] = 0;
numbits = 0;
bitmap = default_bitmap;
}
size = mono_type_size (field->type, &align);
offset = mono_alloc_special_static_data (special_static, size, align, (uintptr_t*)bitmap, numbits);
mono_mem_manager_lock (mem_manager);
if (!mem_manager->special_static_fields)
mem_manager->special_static_fields = g_hash_table_new (NULL, NULL);
g_hash_table_insert (mem_manager->special_static_fields, field, GUINT_TO_POINTER (offset));
mono_mem_manager_unlock (mem_manager);
if (bitmap != default_bitmap)
g_free (bitmap);
/*
* This marks the field as special static to speed up the
* checks in mono_field_static_get/set_value ().
*/
field->offset = -1;
continue;
}
}
if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
MonoClass *fklass = mono_class_from_mono_type_internal (field->type);
const char *data = mono_field_get_data (field);
g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT));
t = (char*)mono_static_field_get_addr (vt, field);
/* some fields don't really have rva, they are just zeroed (bss? bug #343083) */
if (!data)
continue;
if (m_class_is_valuetype (fklass)) {
memcpy (t, data, mono_class_value_size (fklass, NULL));
} else {
/* it's a pointer type: add check */
g_assert ((m_class_get_byval_arg (fklass)->type == MONO_TYPE_PTR) || (m_class_get_byval_arg (fklass)->type == MONO_TYPE_FNPTR));
*t = *(char *)data;
}
continue;
}
}
vt->max_interface_id = m_class_get_max_interface_id (klass);
vt->interface_bitmap = m_class_get_interface_bitmap (klass);
//printf ("Initializing VT for class %s (interface_offsets_count = %d)\n",
// class->name, klass->interface_offsets_count);
/* Initialize vtable */
if (callbacks.get_vtable_trampoline) {
// This also covers the AOT case
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
vt->vtable [i] = callbacks.get_vtable_trampoline (vt, i);
}
} else {
mono_class_setup_vtable (klass);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm;
cm = m_class_get_vtable (klass) [i];
if (cm) {
vt->vtable [i] = callbacks.create_jit_trampoline (cm, error);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
}
}
}
if (imt_table_bytes) {
/* Now that the vtable is full, we can actually fill up the IMT */
for (i = 0; i < MONO_IMT_SIZE; ++i)
interface_offsets [i] = callbacks.get_imt_trampoline (vt, i);
}
/*
* FIXME: Is it ok to allocate while holding the domain/loader locks ? If not, we can release them, allocate, then
* re-acquire them and check if another thread has created the vtable in the meantime.
*/
/* Special case System.MonoType to avoid infinite recursion */
if (!mono_runtime_get_no_exec () && klass != mono_defaults.runtimetype_class) {
MonoReflectionTypeHandle vt_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error);
vt->type = MONO_HANDLE_RAW (vt_type);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
if (mono_handle_class (vt_type) != mono_defaults.runtimetype_class)
/* This is unregistered in
unregister_vtable_reflection_type() in
domain.c. */
MONO_GC_REGISTER_ROOT_IF_MOVING (vt->type, MONO_ROOT_SOURCE_REFLECTION, vt, "Reflection Type Object");
}
/* class_vtable_array keeps an array of created vtables
*/
mono_mem_manager_lock (mem_manager);
g_ptr_array_add (mem_manager->class_vtable_array, vt);
mono_mem_manager_unlock (mem_manager);
/*
* Store the vtable in klass_vtable.
* klass->runtime_vtable is accessed without locking, so this do this last after the vtable has been constructed.
*/
mono_memory_barrier ();
mono_class_set_runtime_vtable (klass, vt);
if (!mono_runtime_get_no_exec () && klass == mono_defaults.runtimetype_class) {
MonoReflectionTypeHandle vt_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error);
vt->type = MONO_HANDLE_RAW (vt_type);
if (!is_ok (error)) {
mono_loader_unlock ();
MONO_PROFILER_RAISE (vtable_failed, (vt));
goto return_null;
}
if (mono_handle_class (vt_type) != mono_defaults.runtimetype_class)
/* This is unregistered in
unregister_vtable_reflection_type() in
domain.c. */
MONO_GC_REGISTER_ROOT_IF_MOVING(vt->type, MONO_ROOT_SOURCE_REFLECTION, vt, "Reflection Type Object");
}
mono_loader_unlock ();
/* make sure the parent is initialized */
/*FIXME shouldn't this fail the current type?*/
if (m_class_get_parent (klass))
mono_class_vtable_checked (m_class_get_parent (klass), error);
MONO_PROFILER_RAISE (vtable_loaded, (vt));
goto exit;
return_null:
vt = NULL;
exit:
HANDLE_FUNCTION_RETURN_VAL (vt);
}
/**
* mono_class_field_is_special_static:
* \returns whether \p field is a thread/context static field.
*/
gboolean
mono_class_field_is_special_static (MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return FALSE;
if (mono_field_is_deleted (field))
return FALSE;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) {
if (field_is_special_static (m_field_get_parent (field), field) != SPECIAL_STATIC_NONE)
return TRUE;
}
return FALSE;
}
/**
* mono_class_field_get_special_static_type:
* \param field The \c MonoClassField describing the field.
* \returns \c SPECIAL_STATIC_THREAD if the field is thread static, \c SPECIAL_STATIC_CONTEXT if it is context static,
* \c SPECIAL_STATIC_NONE otherwise.
*/
guint32
mono_class_field_get_special_static_type (MonoClassField *field)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return SPECIAL_STATIC_NONE;
if (mono_field_is_deleted (field))
return SPECIAL_STATIC_NONE;
if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
return field_is_special_static (m_field_get_parent (field), field);
return SPECIAL_STATIC_NONE;
}
/**
* mono_class_has_special_static_fields:
* \returns whether \p klass has any thread/context static fields.
*/
gboolean
mono_class_has_special_static_fields (MonoClass *klass)
{
MONO_REQ_GC_NEUTRAL_MODE
MonoClassField *field;
gpointer iter;
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
g_assert (m_field_get_parent (field) == klass);
if (mono_class_field_is_special_static (field))
return TRUE;
}
return FALSE;
}
MonoMethod*
mono_object_get_virtual_method_internal (MonoObject *obj_raw, MonoMethod *method)
{
HANDLE_FUNCTION_ENTER ();
MonoMethod *result;
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
result = mono_object_handle_get_virtual_method (obj, method, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_VAL (result);
}
/**
* mono_object_get_virtual_method:
* \param obj object to operate on.
* \param method method
* Retrieves the \c MonoMethod that would be called on \p obj if \p obj is passed as
* the instance of a callvirt of \p method.
*/
MonoMethod*
mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoMethod*, mono_object_get_virtual_method_internal (obj, method));
}
/**
* mono_object_handle_get_virtual_method:
* \param obj object to operate on.
* \param method method
* Retrieves the \c MonoMethod that would be called on \p obj if \p obj is passed as
* the instance of a callvirt of \p method.
*/
MonoMethod*
mono_object_handle_get_virtual_method (MonoObjectHandle obj, MonoMethod *method, MonoError *error)
{
error_init (error);
MonoClass *klass = mono_handle_class (obj);
return mono_class_get_virtual_method (klass, method, error);
}
MonoMethod*
mono_class_get_virtual_method (MonoClass *klass, MonoMethod *method, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
error_init (error);
if (((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)))
return method;
mono_class_setup_vtable (klass);
MonoMethod **vtable = m_class_get_vtable (klass);
if (method->slot == -1) {
/* method->slot might not be set for instances of generic methods */
if (method->is_inflated) {
g_assert (((MonoMethodInflated*)method)->declaring->slot != -1);
method->slot = ((MonoMethodInflated*)method)->declaring->slot;
} else {
g_assert_not_reached ();
}
}
MonoMethod *res = NULL;
/* check method->slot is a valid index: perform isinstance? */
if (method->slot != -1) {
if (mono_class_is_interface (method->klass)) {
gboolean variance_used = FALSE;
int iface_offset = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
g_assert (iface_offset > 0);
res = vtable [iface_offset + method->slot];
} else {
res = vtable [method->slot];
}
}
{
if (method->is_inflated) {
/* Have to inflate the result */
res = mono_class_inflate_generic_method_checked (res, &((MonoMethodInflated*)method)->context, error);
}
}
return res;
}
static MonoObject*
do_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *result = NULL;
g_assert (callbacks.runtime_invoke);
error_init (error);
MONO_PROFILER_RAISE (method_begin_invoke, (method));
result = callbacks.runtime_invoke (method, obj, params, exc, error);
MONO_PROFILER_RAISE (method_end_invoke, (method));
if (!is_ok (error))
return NULL;
return result;
}
/**
* mono_runtime_invoke:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* Invokes the method represented by \p method on the object \p obj.
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* \c mono_runtime_invoke variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
{
MonoObject *res;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
if (exc) {
res = mono_runtime_try_invoke (method, obj, params, exc, error);
if (*exc == NULL && !is_ok(error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else
mono_error_cleanup (error);
} else {
res = mono_runtime_invoke_checked (method, obj, params, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return res;
}
/**
* mono_runtime_try_invoke:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* \param error set on error
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* For this function, you must not pass NULL as the \p exc argument if
* you don't want to catch exceptions, use
* mono_runtime_invoke_checked(). If an exception is thrown, you
* can't use the \c MonoObject* result from the function.
*
* If this method cannot be invoked, \p error will be set and \p exc and
* the return value must not be used.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_try_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError* error)
{
MONO_REQ_GC_UNSAFE_MODE;
g_assert (exc != NULL);
if (mono_runtime_get_no_exec ())
g_warning ("Invoking method '%s' when running in no-exec mode.\n", mono_method_full_name (method, TRUE));
return do_runtime_invoke (method, obj, params, exc, error);
}
MonoObjectHandle
mono_runtime_try_invoke_handle (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
// FIXME? typing of params
MonoException *exc = NULL;
MonoObject *obj_raw = mono_runtime_try_invoke (method, MONO_HANDLE_RAW (obj), params, (MonoObject**)&exc, error);
if (exc && is_ok (error))
mono_error_set_exception_instance (error, exc);
return MONO_HANDLE_NEW (MonoObject, obj_raw);
}
/**
* mono_runtime_invoke_checked:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param error set on error
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* If an exception is thrown, you can't use the \c MonoObject* result
* from the function.
*
* If this method cannot be invoked, \p error will be set. If the
* method throws an exception (and we're in coop mode) the exception
* will be set in \p error.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_checked (MonoMethod *method, void *obj, void **params, MonoError* error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (mono_runtime_get_no_exec ())
g_error ("Invoking method '%s' when running in no-exec mode.\n", mono_method_full_name (method, TRUE));
return do_runtime_invoke (method, obj, params, NULL, error);
}
MonoObjectHandle
mono_runtime_invoke_handle (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
return MONO_HANDLE_NEW (MonoObject, mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (obj), params, error));
}
void
mono_runtime_invoke_handle_void (MonoMethod *method, MonoObjectHandle obj, void **params, MonoError* error)
{
mono_runtime_invoke_checked (method, MONO_HANDLE_RAW (obj), params, error);
}
/**
* mono_method_get_unmanaged_thunk:
* \param method method to generate a thunk for.
*
* Returns an \c unmanaged->managed thunk that can be used to call
* a managed method directly from C.
*
* The thunk's C signature closely matches the managed signature:
*
* C#: <code>public bool Equals (object obj);</code>
*
* C: <code>typedef MonoBoolean (*Equals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* The 1st (<code>this</code>) parameter must not be used with static methods:
*
* C#: <code>public static bool ReferenceEquals (object a, object b);</code>
*
* C: <code>typedef MonoBoolean (*ReferenceEquals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* The last argument must be a non-null \c MonoException* pointer.
* It has "out" semantics. After invoking the thunk, \c *ex will be NULL if no
* exception has been thrown in managed code. Otherwise it will point
* to the \c MonoException* caught by the thunk. In this case, the result of
* the thunk is undefined:
*
* <pre>
* MonoMethod *method = ... // MonoMethod* of System.Object.Equals
*
* MonoException *ex = NULL;
*
* Equals func = mono_method_get_unmanaged_thunk (method);
*
* MonoBoolean res = func (thisObj, objToCompare, &ex);
*
* if (ex) {
*
* // handle exception
*
* }
* </pre>
*
* The calling convention of the thunk matches the platform's default
* convention. This means that under Windows, C declarations must
* contain the \c __stdcall attribute:
*
* C: <code>typedef MonoBoolean (__stdcall *Equals)(MonoObject*, MonoObject*, MonoException**);</code>
*
* LIMITATIONS
*
* Value type arguments and return values are treated as they were objects:
*
* C#: <code>public static Rectangle Intersect (Rectangle a, Rectangle b);</code>
* C: <code>typedef MonoObject* (*Intersect)(MonoObject*, MonoObject*, MonoException**);</code>
*
* Arguments must be properly boxed upon trunk's invocation, while return
* values must be unboxed.
*/
gpointer
mono_method_get_unmanaged_thunk (MonoMethod *method)
{
MONO_REQ_GC_NEUTRAL_MODE;
MONO_REQ_API_ENTRYPOINT;
ERROR_DECL (error);
gpointer res;
MONO_ENTER_GC_UNSAFE;
method = mono_marshal_get_thunk_invoke_wrapper (method);
res = mono_compile_method_checked (method, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return res;
}
void
mono_copy_value (MonoType *type, void *dest, void *value, int deref_pointer)
{
MONO_REQ_GC_UNSAFE_MODE;
int t;
if (m_type_is_byref (type)) {
/* object fields cannot be byref, so we don't need a
wbarrier here */
gpointer *p = (gpointer*)dest;
*p = value;
return;
}
t = type->type;
handle_enum:
switch (t) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1: {
guint8 *p = (guint8*)dest;
*p = value ? *(guint8*)value : 0;
return;
}
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR: {
guint16 *p = (guint16*)dest;
*p = value ? *(guint16*)value : 0;
return;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gint32 *p = (gint32*)dest;
*p = value ? *(gint32*)value : 0;
return;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_I:
case MONO_TYPE_U:
#endif
case MONO_TYPE_I8:
case MONO_TYPE_U8: {
gint64 *p = (gint64*)dest;
*p = value ? *(gint64*)value : 0;
return;
}
case MONO_TYPE_R4: {
float *p = (float*)dest;
*p = value ? *(float*)value : 0;
return;
}
case MONO_TYPE_R8: {
double *p = (double*)dest;
*p = value ? *(double*)value : 0;
return;
}
case MONO_TYPE_STRING:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_ARRAY:
mono_gc_wbarrier_generic_store_internal (dest, deref_pointer ? *(MonoObject **)value : (MonoObject *)value);
return;
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR: {
gpointer *p = (gpointer*)dest;
*p = deref_pointer? *(gpointer*)value: value;
return;
}
case MONO_TYPE_VALUETYPE:
/* note that 't' and 'type->type' can be different */
if (type->type == MONO_TYPE_VALUETYPE && m_class_is_enumtype (type->data.klass)) {
t = mono_class_enum_basetype_internal (type->data.klass)->type;
goto handle_enum;
} else {
MonoClass *klass = mono_class_from_mono_type_internal (type);
int size = mono_class_value_size (klass, NULL);
if (value == NULL)
mono_gc_bzero_atomic (dest, size);
else
mono_gc_wbarrier_value_copy_internal (dest, value, 1, klass);
}
return;
case MONO_TYPE_GENERICINST:
t = m_class_get_byval_arg (type->data.generic_class->container_class)->type;
goto handle_enum;
default:
g_error ("got type %x", type->type);
}
}
void
mono_field_set_value_internal (MonoObject *obj, MonoClassField *field, void *value)
{
void *dest;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
return;
dest = (char*)obj + field->offset;
mono_copy_value (field->type, dest, value, value && field->type->type == MONO_TYPE_PTR);
}
/**
* mono_field_set_value:
* \param obj Instance object
* \param field \c MonoClassField describing the field to set
* \param value The value to be set
*
* Sets the value of the field described by \p field in the object instance \p obj
* to the value passed in \p value. This method should only be used for instance
* fields. For static fields, use \c mono_field_static_set_value.
*
* The value must be in the native format of the field type.
*/
void
mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_set_value_internal (obj, field, value));
}
void
mono_field_static_set_value_internal (MonoVTable *vt, MonoClassField *field, void *value)
{
void *dest;
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC) == 0)
return;
/* you cant set a constant! */
if ((field->type->attrs & FIELD_ATTRIBUTE_LITERAL))
return;
dest = mono_static_field_get_addr (vt, field);
mono_copy_value (field->type, dest, value, value && field->type->type == MONO_TYPE_PTR);
}
gpointer
mono_special_static_field_get_offset (MonoClassField *field, MonoError *error)
{
MonoMemoryManager *mem_manager = m_class_get_mem_manager (m_field_get_parent (field));
gpointer addr = NULL;
mono_mem_manager_lock (mem_manager);
if (mem_manager->special_static_fields)
addr = g_hash_table_lookup (mem_manager->special_static_fields, field);
mono_mem_manager_unlock (mem_manager);
return addr;
}
/**
* mono_field_static_set_value:
* \param field \c MonoClassField describing the field to set
* \param value The value to be set
* Sets the value of the static field described by \p field
* to the value passed in \p value.
* The value must be in the native format of the field type.
*/
void
mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_static_set_value_internal (vt, field, value));
}
/**
* mono_vtable_get_static_field_data:
*
* Internal use function: return a pointer to the memory holding the static fields
* for a class or NULL if there are no static fields.
* This is exported only for use by the debugger.
*/
void *
mono_vtable_get_static_field_data (MonoVTable *vt)
{
MONO_REQ_GC_NEUTRAL_MODE
if (!vt->has_static_fields)
return NULL;
return vt->vtable [m_class_get_vtable_size (vt->klass)];
}
static guint8*
mono_field_get_addr (MonoObject *obj, MonoVTable *vt, MonoClassField *field)
{
MONO_REQ_GC_UNSAFE_MODE;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
return mono_static_field_get_addr (vt, field);
else
return (guint8*)obj + field->offset;
}
guint8*
mono_static_field_get_addr (MonoVTable *vt, MonoClassField *field)
{
MONO_REQ_GC_UNSAFE_MODE;
guint8 *src;
g_assert (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
if (field->offset == -1) {
if (G_UNLIKELY (m_field_is_from_update (field))) {
return mono_metadata_update_get_static_field_addr (field);
}
/* Special static */
ERROR_DECL (error);
gpointer addr = mono_special_static_field_get_offset (field, error);
mono_error_assert_ok (error);
src = (guint8 *)mono_get_special_static_data (GPOINTER_TO_UINT (addr));
} else {
src = (guint8*)mono_vtable_get_static_field_data (vt) + field->offset;
}
return src;
}
/**
* mono_field_get_value:
* \param obj Object instance
* \param field \c MonoClassField describing the field to fetch information from
* \param value pointer to the location where the value will be stored
* Use this routine to get the value of the field \p field in the object
* passed.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
*
* <pre>
* int i;
*
* mono_field_get_value (obj, int_field, &i);
* </pre>
*/
void
mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_field_get_value_internal (obj, field, value));
}
void
mono_field_get_value_internal (MonoObject *obj, MonoClassField *field, void *value)
{
MONO_REQ_GC_UNSAFE_MODE;
void *src;
g_assert (obj);
g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
src = (char*)obj + field->offset;
mono_copy_value (field->type, value, src, TRUE);
}
/**
* mono_field_get_value_object:
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed.
*/
MonoObject *
mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObject *obj)
{
MonoObject* result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_field_get_value_object_checked (field, obj, error);
mono_error_assert_ok (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_static_field_get_value_handle:
* \param domain domain where the object will be created (if boxing)
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed.
*/
MonoObjectHandle
mono_static_field_get_value_handle (MonoClassField *field, MonoError *error)
// FIXMEcoop invert
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_REF (MonoObject, MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (field, NULL, error)));
}
/**
* mono_field_get_value_object_checked:
* \param field \c MonoClassField describing the field to fetch information from
* \param obj The object instance for the field.
* \param error Set on error.
* \returns a new \c MonoObject with the value from the given field. If the
* field represents a value type, the value is boxed. On error returns NULL and sets \p error.
*/
MonoObject *
mono_field_get_value_object_checked (MonoClassField *field, MonoObject *obj, MonoError *error)
{
// FIXMEcoop
HANDLE_FUNCTION_ENTER ();
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoObject *o = NULL;
MonoClass *klass;
MonoVTable *vtable = NULL;
gpointer v;
gboolean is_static = FALSE;
gboolean is_ref = FALSE;
gboolean is_literal = FALSE;
gboolean is_ptr = FALSE;
MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL);
MonoType *type = mono_field_get_type_checked (field, error);
goto_if_nok (error, return_null);
switch (type->type) {
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
is_ref = TRUE;
break;
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_VALUETYPE:
is_ref = m_type_is_byref (type);
break;
case MONO_TYPE_GENERICINST:
is_ref = !mono_type_generic_inst_is_valuetype (type);
break;
case MONO_TYPE_PTR:
is_ptr = TRUE;
break;
default:
g_error ("type 0x%x not handled in "
"mono_field_get_value_object", type->type);
goto return_null;
}
if (type->attrs & FIELD_ATTRIBUTE_LITERAL)
is_literal = TRUE;
if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
is_static = TRUE;
if (!is_literal) {
vtable = mono_class_vtable_checked (m_field_get_parent (field), error);
goto_if_nok (error, return_null);
if (!vtable->initialized) {
mono_runtime_class_init_full (vtable, error);
goto_if_nok (error, return_null);
}
}
} else {
g_assert (obj);
}
if (is_ref) {
if (is_literal) {
get_default_field_value (field, &o, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, &o, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, &o);
}
goto exit;
}
if (is_ptr) {
gpointer args [2];
gpointer *ptr;
MONO_STATIC_POINTER_INIT (MonoMethod, m)
MonoClass *ptr_klass = mono_class_get_pointer_class ();
m = mono_class_get_method_from_name_checked (ptr_klass, "Box", 2, METHOD_ATTRIBUTE_STATIC, error);
goto_if_nok (error, return_null);
g_assert (m);
MONO_STATIC_POINTER_INIT_END (MonoMethod, m)
v = &ptr;
if (is_literal) {
get_default_field_value (field, v, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, v, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, v);
}
args [0] = ptr;
args [1] = mono_type_get_object_checked (type, error);
goto_if_nok (error, return_null);
o = mono_runtime_invoke_checked (m, NULL, args, error);
goto_if_nok (error, return_null);
goto exit;
}
/* boxed value type */
klass = mono_class_from_mono_type_internal (type);
if (mono_class_is_nullable (klass)) {
o = mono_nullable_box (mono_field_get_addr (obj, vtable, field), klass, error);
goto exit;
}
o = mono_object_new_checked (klass, error);
goto_if_nok (error, return_null);
v = mono_object_get_data (o);
if (is_literal) {
get_default_field_value (field, v, string_handle, error);
goto_if_nok (error, return_null);
} else if (is_static) {
mono_field_static_get_value_checked (vtable, field, v, string_handle, error);
goto_if_nok (error, return_null);
} else {
mono_field_get_value_internal (obj, field, v);
}
goto exit;
return_null:
o = NULL;
exit:
HANDLE_FUNCTION_RETURN_VAL (o);
}
/*
* Important detail, if type is MONO_TYPE_STRING we return a blob encoded string (ie, utf16 + leb128 prefixed size)
*/
gboolean
mono_metadata_read_constant_value (const char *blob, MonoTypeEnum type, void *value, MonoError *error)
{
error_init (error);
gboolean retval = TRUE;
const char *p = blob;
mono_metadata_decode_blob_size (p, &p);
switch (type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*(guint8 *) value = *p;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
*(guint16*) value = read16 (p);
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
*(guint32*) value = read32 (p);
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
*(guint64*) value = read64 (p);
break;
case MONO_TYPE_R4:
readr4 (p, (float*) value);
break;
case MONO_TYPE_R8:
readr8 (p, (double*) value);
break;
case MONO_TYPE_STRING:
*(const char**) value = blob;
break;
case MONO_TYPE_CLASS:
*(gpointer*) value = NULL;
break;
default:
retval = FALSE;
mono_error_set_execution_engine (error, "Type 0x%02x should not be in constant table", type);
}
return retval;
}
gboolean
mono_get_constant_value_from_blob (MonoTypeEnum type, const char *blob, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXMEcoop excess frame, but mono_ldstr_metadata_sig does allocate a handle.
HANDLE_FUNCTION_ENTER ();
gboolean result = FALSE;
if (!mono_metadata_read_constant_value (blob, type, value, error))
goto exit;
if (type == MONO_TYPE_STRING) {
mono_ldstr_metadata_sig (*(const char**)value, string_handle, error);
*(gpointer*)value = MONO_HANDLE_RAW (string_handle);
}
result = TRUE;
exit:
HANDLE_FUNCTION_RETURN_VAL (result);
}
static void
get_default_field_value (MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoTypeEnum def_type;
const char* data;
error_init (error);
data = mono_class_get_field_default_value (field, &def_type);
(void)mono_get_constant_value_from_blob (def_type, data, value, string_handle, error);
}
void
mono_field_static_get_value_for_thread (MonoInternalThread *thread, MonoVTable *vt, MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
void *src;
error_init (error);
g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL) {
get_default_field_value (field, value, string_handle, error);
return;
}
src = mono_static_field_get_addr (vt, field);
mono_copy_value (field->type, value, src, TRUE);
}
/**
* mono_field_static_get_value:
* \param vt vtable to the object
* \param field \c MonoClassField describing the field to fetch information from
* \param value where the value is returned
* Use this routine to get the value of the static field \p field value.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
*
* <pre>
* int i;
*
* mono_field_static_get_value (vt, int_field, &i);
* </pre>
*/
void
mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
{
MONO_REQ_GC_NEUTRAL_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
mono_field_static_get_value_checked (vt, field, value, MONO_HANDLE_NEW (MonoString, NULL), error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN ();
}
/**
* mono_field_static_get_value_checked:
* \param vt vtable to the object
* \param field \c MonoClassField describing the field to fetch information from
* \param value where the value is returned
* \param error set on error
* Use this routine to get the value of the static field \p field value.
*
* The pointer provided by value must be of the field type, for reference
* types this is a \c MonoObject*, for value types its the actual pointer to
* the value type.
*
* For example:
* int i;
* mono_field_static_get_value_checked (vt, int_field, &i, error);
* if (!is_ok (error)) { ... }
*
* On failure sets \p error.
*/
void
mono_field_static_get_value_checked (MonoVTable *vt, MonoClassField *field, void *value, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
mono_field_static_get_value_for_thread (mono_thread_internal_current (), vt, field, value, string_handle, error);
}
/**
* mono_property_set_value:
* \param prop MonoProperty to set
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param exc optional exception
* Invokes the property's set method with the given arguments on the
* object instance obj (or NULL for static properties).
*
* You can pass NULL as the exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
void
mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
{
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
do_runtime_invoke (prop->set, obj, params, exc, error);
if (exc && *exc == NULL && !is_ok (error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else {
mono_error_cleanup (error);
}
MONO_EXIT_GC_UNSAFE;
}
/**
* mono_property_set_value_handle:
* \param prop \c MonoProperty to set
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param error set on error
* Invokes the property's set method with the given arguments on the
* object instance \p obj (or NULL for static properties).
* \returns TRUE on success. On failure returns FALSE and sets \p error.
* If an exception is thrown, it will be caught and returned via \p error.
*/
gboolean
mono_property_set_value_handle (MonoProperty *prop, MonoObjectHandle obj, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *exc;
error_init (error);
do_runtime_invoke (prop->set, MONO_HANDLE_RAW (obj), params, &exc, error);
if (exc != NULL && is_ok (error))
mono_error_set_exception_instance (error, (MonoException*)exc);
return is_ok (error);
}
/**
* mono_property_get_value:
* \param prop \c MonoProperty to fetch
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param exc optional exception
* Invokes the property's \c get method with the given arguments on the
* object instance \p obj (or NULL for static properties).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* \returns the value from invoking the \c get method on the property.
*/
MonoObject*
mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
{
MonoObject *val;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
val = do_runtime_invoke (prop->get, obj, params, exc, error);
if (exc && *exc == NULL && !is_ok (error)) {
*exc = (MonoObject*) mono_error_convert_to_exception (error);
} else {
mono_error_cleanup (error); /* FIXME don't raise here */
}
MONO_EXIT_GC_UNSAFE;
return val;
}
/**
* mono_property_get_value_checked:
* \param prop \c MonoProperty to fetch
* \param obj instance object on which to act
* \param params parameters to pass to the propery
* \param error set on error
* Invokes the property's \c get method with the given arguments on the
* object instance obj (or NULL for static properties).
*
* If an exception is thrown, you can't use the
* \c MonoObject* result from the function. The exception will be propagated via \p error.
*
* \returns the value from invoking the get method on the property. On
* failure returns NULL and sets \p error.
*/
MonoObject*
mono_property_get_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *exc;
MonoObject *val = do_runtime_invoke (prop->get, obj, params, &exc, error);
if (exc != NULL && !is_ok (error))
mono_error_set_exception_instance (error, (MonoException*) exc);
if (!is_ok (error))
val = NULL;
return val;
}
static MonoClassField*
nullable_class_get_value_field (MonoClass *klass)
{
mono_class_setup_fields (klass);
g_assert (m_class_is_fields_inited (klass));
MonoClassField *klass_fields = m_class_get_fields (klass);
return &klass_fields [1];
}
static MonoClassField*
nullable_class_get_has_value_field (MonoClass *klass)
{
mono_class_setup_fields (klass);
g_assert (m_class_is_fields_inited (klass));
MonoClassField *klass_fields = m_class_get_fields (klass);
return &klass_fields [0];
}
static gpointer
nullable_get_has_value_field_addr (guint8 *nullable, MonoClass *klass)
{
MonoClassField *has_value_field = nullable_class_get_has_value_field (klass);
return mono_vtype_get_field_addr (nullable, has_value_field);
}
static gpointer
nullable_get_value_field_addr (guint8 *nullable, MonoClass *klass)
{
MonoClassField *has_value_field = nullable_class_get_value_field (klass);
return mono_vtype_get_field_addr (nullable, has_value_field);
}
/*
* mono_nullable_init:
* @buf: The nullable structure to initialize.
* @value: the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*/
void
mono_nullable_init (guint8 *buf, MonoObject *value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
*(guint8*)(has_value_field_addr) = value ? 1 : 0;
if (value) {
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (value_field_addr, mono_object_unbox_internal (value), 1, param_class);
else
mono_gc_memmove_atomic (value_field_addr, mono_object_unbox_internal (value), mono_class_value_size (param_class, NULL));
} else {
mono_gc_bzero_atomic (value_field_addr, mono_class_value_size (param_class, NULL));
}
}
/*
* mono_nullable_init_from_handle:
* @buf: The nullable structure to initialize.
* @value: the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*/
void
mono_nullable_init_from_handle (guint8 *buf, MonoObjectHandle value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!MONO_HANDLE_IS_NULL (value)) {
MonoGCHandle value_gchandle = NULL;
gpointer src = mono_object_handle_pin_unbox (value, &value_gchandle);
mono_nullable_init_unboxed (buf, src, klass);
mono_gchandle_free_internal (value_gchandle);
} else {
mono_nullable_init_unboxed (buf, NULL, klass);
}
}
/*
* mono_nullable_init_unboxed
*
* @buf: The nullable structure to initialize.
* @value: the unboxed address of the value to initialize from
* @klass: the type for the object
*
* Initialize the nullable structure pointed to by @buf from @value which
* should be a boxed value type. The size of @buf should be able to hold
* as much data as the @klass->instance_size (which is the number of bytes
* that will be copies).
*
* Since Nullables have variable structure, we can not define a C
* structure for them.
*
* This function expects all objects to be pinned or for
* MONO_ENTER_NO_SAFEPOINTS to be used in a caller.
*/
void
mono_nullable_init_unboxed (guint8 *buf, gpointer value, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
*(guint8*)(has_value_field_addr) = (value == NULL) ? 0 : 1;
if (value) {
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (value_field_addr, value, 1, param_class);
else
mono_gc_memmove_atomic (value_field_addr, value, mono_class_value_size (param_class, NULL));
} else {
mono_gc_bzero_atomic (value_field_addr, mono_class_value_size (param_class, NULL));
}
}
/**
* mono_nullable_box:
* \param buf The buffer representing the data to be boxed
* \param klass the type to box it as.
* \param error set on error
*
* Creates a boxed vtype or NULL from the \c Nullable structure pointed to by
* \p buf. On failure returns NULL and sets \p error.
*/
MonoObject*
mono_nullable_box (gpointer vbuf, MonoClass *klass, MonoError *error)
{
guint8 *buf = (guint8*)vbuf;
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoClass *param_class = m_class_get_cast_class (klass);
gpointer has_value_field_addr = nullable_get_has_value_field_addr (buf, klass);
gpointer value_field_addr = nullable_get_value_field_addr (buf, klass);
g_assertf (!m_class_is_byreflike (param_class), "Unexpected Nullable<%s> - generic type instantiated with IsByRefLike type", mono_type_get_full_name (param_class));
if (*(guint8*)(has_value_field_addr)) {
MonoObject *o = mono_object_new_checked (param_class, error);
return_val_if_nok (error, NULL);
if (m_class_has_references (param_class))
mono_gc_wbarrier_value_copy_internal (mono_object_unbox_internal (o), value_field_addr, 1, param_class);
else
mono_gc_memmove_atomic (mono_object_unbox_internal (o), value_field_addr, mono_class_value_size (param_class, NULL));
return o;
}
else
return NULL;
}
MonoObjectHandle
mono_nullable_box_handle (gpointer buf, MonoClass *klass, MonoError *error)
{
// FIXMEcoop gpointer buf needs more attention
return MONO_HANDLE_NEW (MonoObject, mono_nullable_box (buf, klass, error));
}
MonoMethod *
mono_get_delegate_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c Invoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_invoke_internal (klass));
}
/**
* mono_get_delegate_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c Invoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "Invoke", -1, 0, error);
return im;
}
MonoMethod *
mono_get_delegate_begin_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_begin_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_begin_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c BeginInvoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_begin_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_begin_invoke_internal (klass));
}
/**
* mono_get_delegate_begin_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c BeginInvoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_begin_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "BeginInvoke", -1, 0, error);
return im;
}
MonoMethod *
mono_get_delegate_end_invoke_internal (MonoClass *klass)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_get_delegate_end_invoke_checked (klass, error);
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
return result;
}
/**
* mono_get_delegate_end_invoke:
* \param klass The delegate class
* \returns the \c MonoMethod for the \c EndInvoke method in the delegate class or NULL if \p klass is a broken delegate type
*/
MonoMethod*
mono_get_delegate_end_invoke (MonoClass *klass)
{
MONO_EXTERNAL_ONLY (MonoMethod*, mono_get_delegate_end_invoke_internal (klass));
}
/**
* mono_get_delegate_end_invoke_checked:
* \param klass The delegate class
* \param error set on error
* \returns the \c MonoMethod for the \c EndInvoke method in the delegate class or NULL if \p klass is a broken delegate type or not a delegate class.
*
* Sets \p error on error
*/
MonoMethod *
mono_get_delegate_end_invoke_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_NEUTRAL_MODE;
MonoMethod *im;
/* This is called at runtime, so avoid the slower search in metadata */
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return NULL;
im = mono_class_get_method_from_name_checked (klass, "EndInvoke", -1, 0, error);
return im;
}
/**
* mono_runtime_delegate_invoke:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param exc Pointer to the exception result.
*
* Invokes the delegate method \p delegate with the parameters provided.
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
MonoObject*
mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
{
ERROR_DECL (error);
MonoObject* result = NULL;
MONO_ENTER_GC_UNSAFE;
if (exc) {
result = mono_runtime_delegate_try_invoke (delegate, params, exc, error);
if (*exc) {
mono_error_cleanup (error);
result = NULL;
} else {
if (!is_ok (error))
*exc = (MonoObject*)mono_error_convert_to_exception (error);
}
} else {
result = mono_runtime_delegate_invoke_checked (delegate, params, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_runtime_delegate_try_invoke:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param exc Pointer to the exception result.
* \param error set on error
* Invokes the delegate method \p delegate with the parameters provided.
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. On failure to execute, \p error will be set.
* if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*/
MonoObject*
mono_runtime_delegate_try_invoke (MonoObject *delegate, void **params, MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoMethod *im;
MonoClass *klass = delegate->vtable->klass;
MonoObject *o;
im = mono_get_delegate_invoke_internal (klass);
g_assertf (im, "Could not lookup delegate invoke method for delegate %s", mono_type_get_full_name (klass));
if (exc) {
o = mono_runtime_try_invoke (im, delegate, params, exc, error);
} else {
o = mono_runtime_invoke_checked (im, delegate, params, error);
}
return o;
}
static MonoObjectHandle
mono_runtime_delegate_try_invoke_handle (MonoObjectHandle delegate, void **params, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = MONO_HANDLE_GETVAL (delegate, vtable)->klass;
MonoMethod* const im = mono_get_delegate_invoke_internal (klass);
g_assertf (im, "Could not lookup delegate invoke method for delegate %s", mono_type_get_full_name (klass));
return mono_runtime_try_invoke_handle (im, delegate, params, error);
}
/**
* mono_runtime_delegate_invoke_checked:
* \param delegate pointer to a delegate object.
* \param params parameters for the delegate.
* \param error set on error
* Invokes the delegate method \p delegate with the parameters provided.
* On failure \p error will be set and you can't use the \c MonoObject*
* result from the function.
*/
MonoObject*
mono_runtime_delegate_invoke_checked (MonoObject *delegate, void **params, MonoError *error)
{
error_init (error);
return mono_runtime_delegate_try_invoke (delegate, params, NULL, error);
}
static char **main_args = NULL;
static int num_main_args = 0;
/**
* mono_runtime_get_main_args:
* \returns A \c MonoArray with the arguments passed to the main program
*/
MonoArray*
mono_runtime_get_main_args (void)
{
HANDLE_FUNCTION_ENTER ();
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
error_init (error);
MonoArrayHandle arg_array = mono_runtime_get_main_args_handle (error);
goto_if_nok (error, leave);
MONO_HANDLE_ASSIGN (result, arg_array);
leave:
/* FIXME: better external API that doesn't swallow the error */
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static gboolean
handle_main_arg_array_set (int idx, MonoArrayHandle dest, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
error_init (error);
MonoStringHandle value = mono_string_new_handle (main_args [idx], error);
goto_if_nok (error, leave);
MONO_HANDLE_ARRAY_SETREF (dest, idx, value);
leave:
HANDLE_FUNCTION_RETURN_VAL (is_ok (error));
}
/**
* mono_runtime_get_main_args_handle:
* \param error set on error
* \returns a \c MonoArray with the arguments passed to the main
* program. On failure returns NULL and sets \p error.
*/
MonoArrayHandle
mono_runtime_get_main_args_handle (MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArrayHandle array;
int i;
error_init (error);
array = mono_array_new_handle (mono_defaults.string_class, num_main_args, error);
if (!is_ok (error)) {
array = MONO_HANDLE_CAST (MonoArray, NULL_HANDLE);
goto leave;
}
for (i = 0; i < num_main_args; ++i) {
if (!handle_main_arg_array_set (i, array, error))
goto leave;
}
leave:
HANDLE_FUNCTION_RETURN_REF (MonoArray, array);
}
static void
free_main_args (void)
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
for (i = 0; i < num_main_args; ++i)
g_free (main_args [i]);
g_free (main_args);
num_main_args = 0;
main_args = NULL;
}
/**
* mono_runtime_set_main_args:
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* Set the command line arguments from an embedding application that doesn't otherwise call
* \c mono_runtime_run_main.
*/
int
mono_runtime_set_main_args (int argc, char* argv[])
{
MONO_REQ_GC_NEUTRAL_MODE;
int i;
free_main_args ();
main_args = g_new0 (char*, argc);
num_main_args = argc;
for (i = 0; i < argc; ++i) {
gchar *utf8_arg;
utf8_arg = mono_utf8_from_external (argv[i]);
if (utf8_arg == NULL) {
g_print ("\nCannot determine the text encoding for argument %d (%s).\n", i, argv [i]);
exit (-1);
}
main_args [i] = utf8_arg;
}
MONO_EXTERNAL_ONLY (int, 0);
}
/*
* Prepare an array of arguments in order to execute a standard Main()
* method (argc/argv contains the executable name). This method also
* sets the command line argument value needed by System.Environment.
*
*/
static MonoArray*
prepare_run_main (MonoMethod *method, int argc, char *argv[])
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
int i;
MonoArray *args = NULL;
gchar *utf8_fullpath;
MonoMethodSignature *sig;
g_assert (method != NULL);
mono_thread_set_main (mono_thread_current ());
main_args = g_new0 (char*, argc);
num_main_args = argc;
if (!g_path_is_absolute (argv [0])) {
gchar *basename = g_path_get_basename (argv [0]);
gchar *fullpath = g_build_filename (m_class_get_image (method->klass)->assembly->basedir,
basename,
(const char*)NULL);
utf8_fullpath = mono_utf8_from_external (fullpath);
if(utf8_fullpath == NULL) {
/* Printing the arg text will cause glib to
* whinge about "Invalid UTF-8", but at least
* its relevant, and shows the problem text
* string.
*/
g_print ("\nCannot determine the text encoding for the assembly location: %s\n", fullpath);
exit (-1);
}
g_free (fullpath);
g_free (basename);
} else {
utf8_fullpath = mono_utf8_from_external (argv[0]);
if(utf8_fullpath == NULL) {
g_print ("\nCannot determine the text encoding for the assembly location: %s\n", argv[0]);
exit (-1);
}
}
main_args [0] = utf8_fullpath;
for (i = 1; i < argc; ++i) {
gchar *utf8_arg;
utf8_arg=mono_utf8_from_external (argv[i]);
if(utf8_arg==NULL) {
/* Ditto the comment about Invalid UTF-8 here */
g_print ("\nCannot determine the text encoding for argument %d (%s).\n", i, argv[i]);
exit (-1);
}
main_args [i] = utf8_arg;
}
argc--;
argv++;
sig = mono_method_signature_internal (method);
if (!sig) {
g_print ("Unable to load Main method.\n");
exit (-1);
}
if (sig->param_count) {
args = (MonoArray*)mono_array_new_checked (mono_defaults.string_class, argc, error);
mono_error_assert_ok (error);
for (i = 0; i < argc; ++i) {
/* The encodings should all work, given that
* we've checked all these args for the
* main_args array.
*/
gchar *str = mono_utf8_from_external (argv [i]);
MonoString *arg = mono_string_new_checked (str, error);
mono_error_assert_ok (error);
mono_array_setref_internal (args, i, arg);
g_free (str);
}
} else {
args = (MonoArray*)mono_array_new_checked (mono_defaults.string_class, 0, error);
mono_error_assert_ok (error);
}
mono_assembly_set_main (m_class_get_image (method->klass)->assembly);
return args;
}
/**
* mono_runtime_run_main:
* \param method the method to start the application with (usually <code>Main</code>)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param exc excetption results
* Execute a standard \c Main method (\p argc / \p argv contains the
* executable name). This method also sets the command line argument value
* needed by \c System.Environment.
*/
int
mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
MonoObject **exc)
{
int res;
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MONO_ENTER_GC_UNSAFE;
MonoArray *args = prepare_run_main (method, argc, argv);
if (exc)
res = mono_runtime_try_exec_main (method, args, exc);
else
res = mono_runtime_exec_main_checked (method, args, error);
MONO_EXIT_GC_UNSAFE;
if (!exc)
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a better alternative */
return res;
}
/**
* mono_runtime_run_main_checked:
* \param method the method to start the application with (usually \c Main)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param error set on error
*
* Execute a standard \c Main method (\p argc / \p argv contains the
* executable name). This method also sets the command line argument value
* needed by \c System.Environment. On failure sets \p error.
*/
int
mono_runtime_run_main_checked (MonoMethod *method, int argc, char* argv[],
MonoError *error)
{
error_init (error);
MonoArray *args = prepare_run_main (method, argc, argv);
return mono_runtime_exec_main_checked (method, args, error);
}
/**
* mono_runtime_try_run_main:
* \param method the method to start the application with (usually \c Main)
* \param argc number of arguments from the command line
* \param argv array of strings from the command line
* \param exc set if \c Main throws an exception
* \param error set if \c Main can't be executed
* Execute a standard \c Main method (\p argc / \p argv contains the executable
* name). This method also sets the command line argument value needed
* by \c System.Environment. On failure sets \p error if Main can't be
* executed or \p exc if it threw an exception.
*/
int
mono_runtime_try_run_main (MonoMethod *method, int argc, char* argv[],
MonoObject **exc)
{
g_assert (exc);
MonoArray *args = prepare_run_main (method, argc, argv);
return mono_runtime_try_exec_main (method, args, exc);
}
MonoObjectHandle
mono_new_null (void) // A code size optimization (source and object).
{
return MONO_HANDLE_NEW (MonoObject, NULL);
}
/* Used in call_unhandled_exception_delegate */
static MonoObjectHandle
create_unhandled_exception_eventargs (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass * const klass = mono_class_get_unhandled_exception_event_args_class ();
mono_class_init_internal (klass);
/* UnhandledExceptionEventArgs only has 1 public ctor with 2 args */
MonoMethod * const method = mono_class_get_method_from_name_checked (klass, ".ctor", 2, METHOD_ATTRIBUTE_PUBLIC, error);
goto_if_nok (error, return_null);
g_assert (method);
{
MonoBoolean is_terminating = TRUE;
gpointer args [ ] = {
MONO_HANDLE_RAW (exc), // FIXMEcoop (ok as long as handles are pinning)
&is_terminating
};
MonoObjectHandle obj = mono_object_new_handle (klass, error);
goto_if_nok (error, return_null);
mono_runtime_invoke_handle_void (method, obj, args, error);
goto_if_nok (error, return_null);
return obj;
}
return_null:
return MONO_HANDLE_NEW (MonoObject, NULL);
}
void
mono_unhandled_exception_internal (MonoObject *exc_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, exc);
mono_unhandled_exception_checked (exc, error);
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN ();
}
/**
* mono_unhandled_exception:
* \param exc exception thrown
* This is a VM internal routine.
*
* We call this function when we detect an unhandled exception
* in the default domain.
*
* It invokes the \c UnhandledException event in \c AppDomain or prints
* a warning to the console
*/
void
mono_unhandled_exception (MonoObject *exc)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE_VOID (mono_unhandled_exception_internal (exc));
}
static MonoObjectHandle
create_first_chance_exception_eventargs (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle obj;
MonoClass *klass = mono_class_get_first_chance_exception_event_args_class ();
MONO_STATIC_POINTER_INIT (MonoMethod, ctor)
ctor = mono_class_get_method_from_name_checked (klass, ".ctor", 1, METHOD_ATTRIBUTE_PUBLIC, error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, ctor)
goto_if_nok (error, return_null);
g_assert (ctor);
gpointer args [1];
args [0] = MONO_HANDLE_RAW (exc);
obj = mono_object_new_handle (klass, error);
goto_if_nok (error, return_null);
mono_runtime_invoke_handle_void (ctor, obj, args, error);
goto_if_nok (error, return_null);
goto leave;
return_null:
obj = MONO_HANDLE_NEW (MonoObject, NULL);
leave:
HANDLE_FUNCTION_RETURN_REF (MonoObject, obj);
}
void
mono_first_chance_exception_internal (MonoObject *exc_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, exc);
mono_first_chance_exception_checked (exc, error);
if (!is_ok (error))
g_warning ("Invoking the FirstChanceException event failed: %s", mono_error_get_message (error));
HANDLE_FUNCTION_RETURN ();
}
void
mono_first_chance_exception_checked (MonoObjectHandle exc, MonoError *error)
{
MonoClass *klass = mono_handle_class (exc);
MonoDomain *domain = mono_domain_get ();
MonoObject *delegate = NULL;
MonoObjectHandle delegate_handle;
if (klass == mono_defaults.threadabortexception_class)
return;
MONO_STATIC_POINTER_INIT (MonoClassField, field)
static gboolean inited;
if (!inited) {
field = mono_class_get_field_from_name_full (mono_defaults.appcontext_class, "FirstChanceException", NULL);
inited = TRUE;
}
MONO_STATIC_POINTER_INIT_END (MonoClassField, field)
if (!field)
return;
MonoVTable *vt = mono_class_vtable_checked (mono_defaults.appcontext_class, error);
return_if_nok (error);
// TODO: use handles directly
mono_field_static_get_value_checked (vt, field, &delegate, MONO_HANDLE_NEW (MonoString, NULL), error);
return_if_nok (error);
delegate_handle = MONO_HANDLE_NEW (MonoObject, delegate);
if (MONO_HANDLE_BOOL (delegate_handle)) {
gpointer args [2];
args [0] = domain->domain;
args [1] = MONO_HANDLE_RAW (create_first_chance_exception_eventargs (exc, error));
mono_error_assert_ok (error);
mono_runtime_delegate_try_invoke_handle (delegate_handle, args, error);
}
}
/**
* mono_unhandled_exception_checked:
* @exc: exception thrown
*
* This is a VM internal routine.
*
* We call this function when we detect an unhandled exception
* in the default domain.
*
* It invokes the * UnhandledException event in AppDomain or prints
* a warning to the console
*/
void
mono_unhandled_exception_checked (MonoObjectHandle exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoDomain *current_domain = mono_domain_get ();
MonoClass *klass = mono_handle_class (exc);
/*
* AppDomainUnloadedException don't behave like unhandled exceptions unless thrown from
* a thread started in unmanaged world.
* https://msdn.microsoft.com/en-us/library/system.appdomainunloadedexception(v=vs.110).aspx#Anchor_6
*/
gboolean no_event = (klass == mono_defaults.threadabortexception_class);
if (no_event)
return;
MONO_STATIC_POINTER_INIT (MonoClassField, field)
static gboolean inited;
if (!inited) {
field = mono_class_get_field_from_name_full (mono_defaults.appcontext_class, "UnhandledException", NULL);
inited = TRUE;
}
MONO_STATIC_POINTER_INIT_END (MonoClassField, field)
if (!field)
goto leave;
MonoObject *delegate = NULL;
MonoObjectHandle delegate_handle;
MonoVTable *vt = mono_class_vtable_checked (mono_defaults.appcontext_class, error);
goto_if_nok (error, leave);
// TODO: use handles directly
mono_field_static_get_value_checked (vt, field, &delegate, MONO_HANDLE_NEW (MonoString, NULL), error);
goto_if_nok (error, leave);
delegate_handle = MONO_HANDLE_NEW (MonoObject, delegate);
if (MONO_HANDLE_IS_NULL (delegate_handle)) {
mono_print_unhandled_exception_internal (MONO_HANDLE_RAW (exc)); // TODO: use handles
} else {
gpointer args [2];
args [0] = current_domain->domain;
args [1] = MONO_HANDLE_RAW (create_unhandled_exception_eventargs (exc, error));
mono_error_assert_ok (error);
mono_runtime_delegate_try_invoke_handle (delegate_handle, args, error);
}
leave:
/* set exitcode if we will abort the process */
mono_environment_exitcode_set (1);
}
/**
* mono_runtime_exec_managed_code:
* \param domain Application domain
* \param main_func function to invoke from the execution thread
* \param main_args parameter to the main_func
* Launch a new thread to execute a function
*
* \p main_func is called back from the thread with main_args as the
* parameter. The callback function is expected to start \c Main
* eventually. This function then waits for all managed threads to
* finish.
* It is not necessary anymore to execute managed code in a subthread,
* so this function should not be used anymore by default: just
* execute the code and then call mono_thread_manage().
*/
void
mono_runtime_exec_managed_code (MonoDomain *domain,
MonoMainThreadFunc mfunc,
gpointer margs)
{
// This function is external_only.
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
mono_thread_create_checked ((MonoThreadStart)mfunc, margs, error);
mono_error_assert_ok (error);
mono_thread_manage_internal ();
MONO_EXIT_GC_UNSAFE;
}
static void
prepare_thread_to_exec_main (MonoMethod *method)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoInternalThread* thread = mono_thread_internal_current ();
MonoCustomAttrInfo* cinfo;
gboolean has_stathread_attribute;
if (!mono_runtime_get_entry_assembly ())
mono_runtime_ensure_entry_assembly (m_class_get_image (method->klass)->assembly);
ERROR_DECL (cattr_error);
cinfo = mono_custom_attrs_from_method_checked (method, cattr_error);
mono_error_cleanup (cattr_error); /* FIXME warn here? */
if (cinfo) {
has_stathread_attribute = mono_custom_attrs_has_attr (cinfo, mono_class_get_sta_thread_attribute_class ());
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
has_stathread_attribute = FALSE;
}
if (has_stathread_attribute) {
thread->apartment_state = ThreadApartmentState_STA;
} else {
thread->apartment_state = ThreadApartmentState_MTA;
}
mono_thread_init_apartment_state ();
mono_thread_init_from_native ();
}
static int
do_exec_main_checked (MonoMethod *method, MonoArray *args, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
gpointer pa [1];
int rval;
error_init (error);
g_assert (args);
pa [0] = args;
/* FIXME: check signature of method */
if (mono_method_signature_internal (method)->ret->type == MONO_TYPE_I4) {
MonoObject *res;
res = mono_runtime_invoke_checked (method, NULL, pa, error);
if (is_ok (error))
rval = *(guint32 *)(mono_object_get_data (res));
else
rval = -1;
mono_environment_exitcode_set (rval);
} else {
mono_runtime_invoke_checked (method, NULL, pa, error);
if (is_ok (error))
rval = 0;
else {
rval = -1;
}
}
return rval;
}
static int
do_try_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
MONO_REQ_GC_UNSAFE_MODE;
gpointer pa [1];
int rval;
g_assert (args);
g_assert (exc);
pa [0] = args;
/* FIXME: check signature of method */
if (mono_method_signature_internal (method)->ret->type == MONO_TYPE_I4) {
ERROR_DECL (inner_error);
MonoObject *res;
res = mono_runtime_try_invoke (method, NULL, pa, exc, inner_error);
if (*exc == NULL && !is_ok (inner_error))
*exc = (MonoObject*) mono_error_convert_to_exception (inner_error);
else
mono_error_cleanup (inner_error);
if (*exc == NULL)
rval = *(guint32 *)(mono_object_get_data (res));
else
rval = -1;
mono_environment_exitcode_set (rval);
} else {
ERROR_DECL (inner_error);
mono_runtime_try_invoke (method, NULL, pa, exc, inner_error);
if (*exc == NULL && !is_ok (inner_error))
*exc = (MonoObject*) mono_error_convert_to_exception (inner_error);
else
mono_error_cleanup (inner_error);
if (*exc == NULL)
rval = 0;
else {
/* If the return type of Main is void, only
* set the exitcode if an exception was thrown
* (we don't want to blow away an
* explicitly-set exit code)
*/
rval = -1;
mono_environment_exitcode_set (rval);
}
}
return rval;
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*/
int
mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
int rval;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
prepare_thread_to_exec_main (method);
if (exc) {
rval = do_try_exec_main (method, args, exc);
} else {
rval = do_exec_main_checked (method, args, error);
// FIXME Maybe change mode back here?
mono_error_raise_exception_deprecated (error); /* OK to throw, external only with no better option */
}
MONO_EXIT_GC_UNSAFE;
return rval;
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*
* On failure sets @error
*/
int
mono_runtime_exec_main_checked (MonoMethod *method, MonoArray *args, MonoError *error)
{
error_init (error);
prepare_thread_to_exec_main (method);
return do_exec_main_checked (method, args, error);
}
/*
* Execute a standard Main() method (args doesn't contain the
* executable name).
*
* On failure sets @error if Main couldn't be executed, or @exc if it threw an exception.
*/
int
mono_runtime_try_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
{
prepare_thread_to_exec_main (method);
return do_try_exec_main (method, args, exc);
}
/** invoke_span_extract_argument:
* @params: span of object arguments to the method.
* @i: the index of the argument to extract.
* @t: ith type from the method signature.
* @has_byref_nullables: outarg - TRUE if method expects a byref nullable argument
* @error: set on error.
*
* Given an array of method arguments, return the ith one using the corresponding type
* to perform necessary unboxing. If method expects a ref nullable argument, writes TRUE to @has_byref_nullables.
*
* On failure sets @error and returns NULL.
*/
static gpointer
invoke_span_extract_argument (MonoSpanOfObjects *params_span, int i, MonoType *t, MonoObject **pa_obj, gboolean* has_byref_nullables, MonoError *error)
{
MonoType *t_orig = t;
gpointer result = NULL;
*pa_obj = NULL;
error_init (error);
again:
switch (t->type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_VALUETYPE:
if (t->type == MONO_TYPE_VALUETYPE && mono_class_is_nullable (mono_class_from_mono_type_internal (t_orig))) {
/* The runtime invoke wrapper needs the original boxed vtype, it does handle byref values as well. */
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = *pa_obj;
if (m_type_is_byref (t))
*has_byref_nullables = TRUE;
} else {
/* MS seems to create the objects if a null is passed in */
gboolean was_null = FALSE;
if (!mono_span_get (params_span, MonoObject*, i)) {
MonoObject *o = mono_object_new_checked (mono_class_from_mono_type_internal (t_orig), error);
return_val_if_nok (error, NULL);
mono_span_setref (params_span, i, o);
was_null = TRUE;
}
if (m_type_is_byref (t)) {
/*
* We can't pass the unboxed vtype byref to the callee, since
* that would mean the callee would be able to modify boxed
* primitive types. So we (and MS) make a copy of the boxed
* object, pass that to the callee, and replace the original
* boxed object in the arg array with the copy.
*/
MonoObject *orig = mono_span_get (params_span, MonoObject*, i);
MonoObject *copy = mono_value_box_checked (orig->vtable->klass, mono_object_unbox_internal (orig), error);
return_val_if_nok (error, NULL);
mono_span_setref (params_span, i, copy);
}
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = mono_object_unbox_internal (*pa_obj);
if (!m_type_is_byref (t) && was_null)
mono_span_setref (params_span, i, NULL);
}
break;
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
if (m_type_is_byref (t)) {
result = mono_span_addr (params_span, MonoObject*, i);
// FIXME: I need to check this code path
} else {
*pa_obj = mono_span_get (params_span, MonoObject*, i);
result = *pa_obj;
}
break;
case MONO_TYPE_GENERICINST:
if (m_type_is_byref (t))
t = m_class_get_this_arg (t->data.generic_class->container_class);
else
t = m_class_get_byval_arg (t->data.generic_class->container_class);
goto again;
case MONO_TYPE_PTR: {
MonoObject *arg;
/* The argument should be an IntPtr */
arg = mono_span_get (params_span, MonoObject*, i);
if (arg == NULL) {
result = NULL;
} else {
g_assert (arg->vtable->klass == mono_defaults.int_class);
result = ((MonoIntPtr*)arg)->m_value;
}
break;
}
default:
g_error ("type 0x%x not handled in mono_runtime_invoke_array", t_orig->type);
}
return result;
}
/**
* mono_runtime_invoke_array:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to
* catch exceptions, otherwise, \c *exc will be set to the exception
* thrown, if any. if an exception is thrown, you can't use the
* \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
MonoObject **exc)
{
MonoObject *res;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
if (exc) {
res = mono_runtime_try_invoke_array (method, obj, params, exc, error);
if (*exc) {
res = NULL;
mono_error_cleanup (error);
} else if (!is_ok (error)) {
*exc = (MonoObject*)mono_error_convert_to_exception (error);
}
} else {
res = mono_runtime_try_invoke_array (method, obj, params, NULL, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
MONO_EXIT_GC_UNSAFE;
return res;
}
static MonoObject*
mono_runtime_try_invoke_span (MonoMethod *method, void *obj, MonoSpanOfObjects *params_span,
MonoObject **exc, MonoError *error)
{
error_init (error);
MonoMethodSignature *sig = mono_method_signature_internal (method);
gpointer *pa = NULL;
MonoObject *res = NULL;
int i;
gboolean has_byref_nullables = FALSE;
int params_length = mono_span_length (params_span);
if (params_length > 0) {
pa = g_newa (gpointer, params_length);
for (i = 0; i < params_length; i++) {
MonoType *t = sig->params [i];
MonoObject *pa_obj;
pa [i] = invoke_span_extract_argument (params_span, i, t, &pa_obj, &has_byref_nullables, error);
if (pa_obj)
MONO_HANDLE_PIN (pa_obj);
goto_if_nok (error, exit_null);
}
}
if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
void *o = obj;
if (mono_class_is_nullable (method->klass)) {
/* Need to create a boxed vtype instead */
g_assert (!obj);
if (params_length == 0) {
goto_if_nok (error, exit_null);
} else {
res = mono_value_box_checked (m_class_get_cast_class (method->klass), pa [0], error);
goto exit;
}
}
if (!obj) {
MonoObjectHandle obj_h = mono_object_new_handle (method->klass, error);
goto_if_nok (error, exit_null);
obj = MONO_HANDLE_RAW (obj_h);
g_assert (obj); /*maybe we should raise a TLE instead?*/
if (m_class_is_valuetype (method->klass))
o = (MonoObject *)mono_object_unbox_internal ((MonoObject *)obj);
else
o = obj;
} else if (m_class_is_valuetype (method->klass)) {
MonoObjectHandle obj_h = mono_value_box_handle (method->klass, obj, error);
goto_if_nok (error, exit_null);
obj = MONO_HANDLE_RAW (obj_h);
}
if (exc) {
mono_runtime_try_invoke (method, o, pa, exc, error);
} else {
mono_runtime_invoke_checked (method, o, pa, error);
}
res = (MonoObject*)obj;
} else {
if (mono_class_is_nullable (method->klass)) {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
obj = NULL;
} else {
/* Convert the unboxed vtype into a Nullable structure */
MonoObjectHandle nullable_h = mono_object_new_handle (method->klass, error);
goto_if_nok (error, exit_null);
MonoObject* nullable = MONO_HANDLE_RAW (nullable_h);
MonoObjectHandle boxed_h = mono_value_box_handle (m_class_get_cast_class (method->klass), obj, error);
goto_if_nok (error, exit_null);
mono_nullable_init ((guint8 *)mono_object_unbox_internal (nullable), MONO_HANDLE_RAW (boxed_h), method->klass);
obj = mono_object_unbox_internal (nullable);
}
}
/* obj must be already unboxed if needed */
if (exc) {
res = mono_runtime_try_invoke (method, obj, pa, exc, error);
} else {
res = mono_runtime_invoke_checked (method, obj, pa, error);
}
MONO_HANDLE_PIN (res);
goto_if_nok (error, exit_null);
if (sig->ret->type == MONO_TYPE_PTR) {
MonoClass *pointer_class;
void *box_args [2];
MonoObject *box_exc;
/*
* The runtime-invoke wrapper returns a boxed IntPtr, need to
* convert it to a Pointer object.
*/
pointer_class = mono_class_get_pointer_class ();
MONO_STATIC_POINTER_INIT (MonoMethod, box_method)
box_method = mono_class_get_method_from_name_checked (pointer_class, "Box", -1, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, box_method)
if (res) {
g_assert (res->vtable->klass == mono_defaults.int_class);
box_args [0] = ((MonoIntPtr*)res)->m_value;
} else {
box_args [0] = NULL;
}
if (m_type_is_byref (sig->ret)) {
// byref is already unboxed by the invoke code
MonoType *tmpret = mono_metadata_type_dup (NULL, sig->ret);
tmpret->byref__ = FALSE;
MonoReflectionTypeHandle type_h = mono_type_get_object_handle (tmpret, error);
box_args [1] = MONO_HANDLE_RAW (type_h);
mono_metadata_free_type (tmpret);
} else {
MonoReflectionTypeHandle type_h = mono_type_get_object_handle (sig->ret, error);
box_args [1] = MONO_HANDLE_RAW (type_h);
}
goto_if_nok (error, exit_null);
res = mono_runtime_try_invoke (box_method, NULL, box_args, &box_exc, error);
g_assert (box_exc == NULL);
mono_error_assert_ok (error);
}
}
goto exit;
exit_null:
res = NULL;
exit:
return res;
}
/**
* mono_runtime_invoke_array_checked:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param error set on failure.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params span contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the \p params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* On failure or exception, \p error will be set. In that case, you
* can't use the \c MonoObject* result from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_invoke_span_checked (MonoMethod *method, void *obj, MonoSpanOfObjects *params,
MonoError *error)
{
error_init (error);
return mono_runtime_try_invoke_span (method, obj, params, NULL, error);
}
/**
* mono_runtime_try_invoke_array:
* \param method method to invoke
* \param obj object instance
* \param params arguments to the method
* \param exc exception information.
* \param error set on failure.
* Invokes the method represented by \p method on the object \p obj.
*
* \p obj is the \c this pointer, it should be NULL for static
* methods, a \c MonoObject* for object instances and a pointer to
* the value type for value types.
*
* The \p params array contains the arguments to the method with the
* same convention: \c MonoObject* pointers for object instances and
* pointers to the value type otherwise. The \c _invoke_array
* variant takes a C# \c object[] as the params argument (\c MonoArray*):
* in this case the value types are boxed inside the
* respective reference representation.
*
* From unmanaged code you'll usually use the
* mono_runtime_invoke_checked() variant.
*
* Note that this function doesn't handle virtual methods for
* you, it will exec the exact method you pass: we still need to
* expose a function to lookup the derived class implementation
* of a virtual method (there are examples of this in the code,
* though).
*
* You can pass NULL as the \p exc argument if you don't want to catch
* exceptions, otherwise, \c *exc will be set to the exception thrown, if
* any. On other failures, \p error will be set. If an exception is
* thrown or there's an error, you can't use the \c MonoObject* result
* from the function.
*
* If the method returns a value type, it is boxed in an object
* reference.
*/
MonoObject*
mono_runtime_try_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
MonoObject **exc, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MonoSpanOfObjects params_span = mono_span_create_from_object_array (params);
MonoObject *res = mono_runtime_try_invoke_span (method, obj, ¶ms_span, exc, error);
HANDLE_FUNCTION_RETURN_VAL (res);
}
// FIXME these will move to header soon
static MonoObjectHandle
mono_object_new_by_vtable (MonoVTable *vtable, MonoError *error);
/**
* object_new_common_tail:
*
* This function centralizes post-processing of objects upon creation.
* i.e. calling mono_object_register_finalizer and mono_gc_register_obj_with_weak_fields,
* and setting error.
*/
static MonoObject*
object_new_common_tail (MonoObject *o, MonoClass *klass, MonoError *error)
{
error_init (error);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (klass));
return o;
}
if (G_UNLIKELY (m_class_has_finalize (klass)))
mono_object_register_finalizer (o);
#ifdef ENABLE_WEAK_ATTR
if (G_UNLIKELY (m_class_has_weak_fields (klass)))
mono_gc_register_obj_with_weak_fields (o);
#endif
return o;
}
/**
* object_new_handle_tail:
*
* This function centralizes post-processing of objects upon creation.
* i.e. calling mono_object_register_finalizer and mono_gc_register_obj_with_weak_fields.
*/
static MonoObjectHandle
object_new_handle_common_tail (MonoObjectHandle o, MonoClass *klass, MonoError *error)
{
error_init (error);
if (G_UNLIKELY (MONO_HANDLE_IS_NULL (o))) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (klass));
return o;
}
if (G_UNLIKELY (m_class_has_finalize (klass)))
mono_object_register_finalizer_handle (o);
#ifdef ENABLE_WEAK_ATTR
if (G_UNLIKELY (m_class_has_weak_fields (klass)))
mono_gc_register_object_with_weak_fields (o);
#endif
return o;
}
/**
* mono_object_new:
* \param klass the class of the object that we want to create
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure.
*/
MonoObject *
mono_object_new (MonoDomain *domain, MonoClass *klass)
{
MonoObject * result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_object_new_checked (klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
MonoObject *
ves_icall_object_new (MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoObject * result = mono_object_new_checked (klass, error);
mono_error_set_pending_exception (error);
return result;
}
/**
* mono_object_new_checked:
* \param klass the class of the object that we want to create
* \param error set on error
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure and sets \p error.
*/
MonoObject *
mono_object_new_checked (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
vtable = mono_class_vtable_checked (klass, error);
if (!is_ok (error))
return NULL;
MonoObject *o = mono_object_new_specific_checked (vtable, error);
return o;
}
/**
* mono_object_new_handle:
* \param klass the class of the object that we want to create
* \param error set on error
* \returns a newly created object whose definition is
* looked up using \p klass. This will not invoke any constructors,
* so the consumer of this routine has to invoke any constructors on
* its own to initialize the object.
*
* It returns NULL on failure and sets \p error.
*/
MonoObjectHandle
mono_object_new_handle (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
return mono_object_new_by_vtable (vtable, error);
}
/**
* mono_object_new_pinned:
*
* Same as mono_object_new, but the returned object will be pinned.
*/
MonoObjectHandle
mono_object_new_pinned_handle (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
g_assert (vtable->klass == klass);
int const size = mono_class_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_pinned_obj (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
MonoObject *
mono_object_new_pinned (MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, NULL);
MonoObject *o = mono_gc_alloc_pinned_obj (vtable, mono_class_instance_size (klass));
return object_new_common_tail (o, klass, error);
}
/**
* mono_object_new_specific:
* \param vtable the vtable of the object that we want to create
* \returns A newly created object with class and domain specified
* by \p vtable
*/
MonoObject *
mono_object_new_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_specific_checked (vtable, error);
mono_error_cleanup (error);
return o;
}
MonoObject *
mono_object_new_specific_checked (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *o;
error_init (error);
/* check for is_com_object for COM Interop */
if (mono_class_is_com_object (vtable->klass)) {
gpointer pa [1];
MonoMethod *im = create_proxy_for_type_method;
if (im == NULL) {
MonoClass *klass = mono_class_get_activation_services_class ();
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
im = mono_class_get_method_from_name_checked (klass, "CreateProxyForType", 1, 0, error);
return_val_if_nok (error, NULL);
if (!im) {
mono_error_set_not_supported (error, "Linked away.");
return NULL;
}
create_proxy_for_type_method = im;
}
pa [0] = mono_type_get_object_checked (m_class_get_byval_arg (vtable->klass), error);
if (!is_ok (error))
return NULL;
o = mono_runtime_invoke_checked (im, NULL, pa, error);
if (!is_ok (error))
return NULL;
if (o != NULL)
return o;
}
return mono_object_new_alloc_specific_checked (vtable, error);
}
static MonoObjectHandle
mono_object_new_by_vtable (MonoVTable *vtable, MonoError *error)
{
// This function handles remoting and COM.
// mono_object_new_alloc_by_vtable does not.
MONO_REQ_GC_UNSAFE_MODE;
MonoObjectHandle o = MONO_HANDLE_NEW (MonoObject, NULL);
error_init (error);
/* check for is_com_object for COM Interop */
if (mono_class_is_com_object (vtable->klass)) {
MonoMethod *im = create_proxy_for_type_method;
if (im == NULL) {
MonoClass *klass = mono_class_get_activation_services_class ();
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
im = mono_class_get_method_from_name_checked (klass, "CreateProxyForType", 1, 0, error);
return_val_if_nok (error, mono_new_null ());
if (!im) {
mono_error_set_not_supported (error, "Linked away.");
return MONO_HANDLE_NEW (MonoObject, NULL);
}
create_proxy_for_type_method = im;
}
// FIXMEcoop
gpointer pa[ ] = { mono_type_get_object_checked (m_class_get_byval_arg (vtable->klass), error) };
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
// FIXMEcoop
o = MONO_HANDLE_NEW (MonoObject, mono_runtime_invoke_checked (im, NULL, pa, error));
return_val_if_nok (error, MONO_HANDLE_NEW (MonoObject, NULL));
if (!MONO_HANDLE_IS_NULL (o))
return o;
}
return mono_object_new_alloc_by_vtable (vtable, error);
}
MonoObject *
ves_icall_object_new_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_specific_checked (vtable, error);
mono_error_set_pending_exception (error);
return o;
}
/**
* mono_object_new_alloc_specific:
* \param vtable virtual table for the object.
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. If the class of this object has a
* finalizer, then the object will be tracked for finalization.
*
* This method might raise an exception on errors. Use the
* \c mono_object_new_fast_checked method if you want to manually raise
* the exception.
*
* \returns the allocated object.
*/
MonoObject *
mono_object_new_alloc_specific (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_object_new_alloc_specific_checked (vtable, error);
mono_error_cleanup (error);
return o;
}
/**
* mono_object_new_alloc_specific_checked:
* \param vtable virtual table for the object.
* \param error holds the error return value.
*
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. If the class of this object has a
* finalizer, then the object will be tracked for finalization.
*
* If there is not enough memory, the \p error parameter will be set
* and will contain a user-visible message with the amount of bytes
* that were requested.
*
* \returns the allocated object, or NULL if there is not enough memory
*/
MonoObject *
mono_object_new_alloc_specific_checked (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoObject *o = mono_gc_alloc_obj (vtable, m_class_get_instance_size (vtable->klass));
return object_new_common_tail (o, vtable->klass, error);
}
MonoObjectHandle
mono_object_new_alloc_by_vtable (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = vtable->klass;
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_obj (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_object_new_fast:
* \param vtable virtual table for the object.
*
* This function allocates a new \c MonoObject with the type derived
* from the \p vtable information. The returned object is not tracked
* for finalization. If your object implements a finalizer, you should
* use \c mono_object_new_alloc_specific instead.
*
* This method might raise an exception on errors. Use the
* \c mono_object_new_fast_checked method if you want to manually raise
* the exception.
*
* \returns the allocated object.
*/
MonoObject*
mono_object_new_fast (MonoVTable *vtable)
{
ERROR_DECL (error);
MonoObject *o = mono_gc_alloc_obj (vtable, m_class_get_instance_size (vtable->klass));
// This deliberately skips object_new_common_tail.
if (G_UNLIKELY (!o))
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", m_class_get_instance_size (vtable->klass));
mono_error_cleanup (error);
return o;
}
MonoObject*
mono_object_new_mature (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
int size;
size = m_class_get_instance_size (vtable->klass);
#if MONO_CROSS_COMPILE
/* In cross compile mode, we should only allocate thread objects */
/* The instance size refers to the target arch, this should be safe enough */
size *= 2;
#endif
MonoObject *o = mono_gc_alloc_mature (vtable, size);
return object_new_common_tail (o, vtable->klass, error);
}
MonoObjectHandle
mono_object_new_handle_mature (MonoVTable *vtable, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* const klass = vtable->klass;
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_mature (vtable, size);
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_object_new_from_token:
* \param image Context where the type_token is hosted
* \param token a token of the type that we want to create
* \returns A newly created object whose definition is
* looked up using \p token in the \p image image
*/
MonoObject *
mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoClass *klass;
klass = mono_class_get_checked (image, token, error);
mono_error_assert_ok (error);
MonoObjectHandle result = mono_object_new_handle (klass, error);
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_clone:
* \param obj the object to clone
* \returns A newly created object who is a shallow copy of \p obj
*/
MonoObject *
mono_object_clone (MonoObject *obj)
{
ERROR_DECL (error);
MonoObject *o = mono_object_clone_checked (obj, error);
mono_error_cleanup (error);
return o;
}
MonoObject *
mono_object_clone_checked (MonoObject *obj_raw, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoObject, obj);
HANDLE_FUNCTION_RETURN_OBJ (mono_object_clone_handle (obj, error));
}
MonoObjectHandle
mono_object_clone_handle (MonoObjectHandle obj, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable* const vtable = MONO_HANDLE_GETVAL (obj, vtable);
MonoClass* const klass = vtable->klass;
if (m_class_get_rank (klass))
return MONO_HANDLE_CAST (MonoObject, mono_array_clone_in_domain (MONO_HANDLE_CAST (MonoArray, obj), error));
int const size = m_class_get_instance_size (klass);
MonoObjectHandle o = mono_gc_alloc_handle_obj (vtable, size);
if (G_LIKELY (!MONO_HANDLE_IS_NULL (o))) {
/* If the object doesn't contain references this will do a simple memmove. */
mono_gc_wbarrier_object_copy_handle (o, obj);
}
return object_new_handle_common_tail (o, klass, error);
}
/**
* mono_array_full_copy:
* \param src source array to copy
* \param dest destination array
* Copies the content of one array to another with exactly the same type and size.
*/
void
mono_array_full_copy (MonoArray *src, MonoArray *dest)
{
MONO_REQ_GC_UNSAFE_MODE;
uintptr_t size;
MonoClass *klass = mono_object_class (&src->obj);
g_assert (klass == mono_object_class (&dest->obj));
size = mono_array_length_internal (src);
g_assert (size == mono_array_length_internal (dest));
size *= mono_array_element_size (klass);
mono_array_full_copy_unchecked_size (src, dest, klass, size);
}
void
mono_array_full_copy_unchecked_size (MonoArray *src, MonoArray *dest, MonoClass *klass, uintptr_t size)
{
if (mono_gc_is_moving ()) {
MonoClass *element_class = m_class_get_element_class (klass);
if (m_class_is_valuetype (element_class)) {
if (m_class_has_references (element_class))
mono_value_copy_array_internal (dest, 0, mono_array_addr_with_size_fast (src, 0, 0), mono_array_length_internal (src));
else
mono_gc_memmove_atomic (&dest->vector, &src->vector, size);
} else {
mono_array_memcpy_refs_internal (dest, 0, src, 0, mono_array_length_internal (src));
}
} else {
mono_gc_memmove_atomic (&dest->vector, &src->vector, size);
}
}
/**
* mono_array_clone_in_domain:
* \param domain the domain in which the array will be cloned into
* \param array the array to clone
* \param error set on error
* This routine returns a copy of the array that is hosted on the
* specified \c MonoDomain. On failure returns NULL and sets \p error.
*/
MonoArrayHandle
mono_array_clone_in_domain (MonoArrayHandle array_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoArrayHandle result = MONO_HANDLE_NEW (MonoArray, NULL);
uintptr_t size = 0;
MonoClass *klass = mono_handle_class (array_handle);
error_init (error);
/* Pin source array here - if bounds is non-NULL, it's a pointer into the object data */
MonoGCHandle src_handle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, array_handle), TRUE);
MonoArrayBounds *array_bounds = MONO_HANDLE_GETVAL (array_handle, bounds);
MonoArrayHandle o;
if (array_bounds == NULL) {
size = mono_array_handle_length (array_handle);
o = mono_array_new_full_handle (klass, &size, NULL, error);
goto_if_nok (error, leave);
size *= mono_array_element_size (klass);
} else {
guint8 klass_rank = m_class_get_rank (klass);
uintptr_t *sizes = g_newa (uintptr_t, klass_rank);
intptr_t *lower_bounds = g_newa (intptr_t, klass_rank);
size = mono_array_element_size (klass);
for (int i = 0; i < klass_rank; ++i) {
sizes [i] = array_bounds [i].length;
size *= array_bounds [i].length;
lower_bounds [i] = array_bounds [i].lower_bound;
}
o = mono_array_new_full_handle (klass, sizes, lower_bounds, error);
goto_if_nok (error, leave);
}
MonoGCHandle dst_handle;
dst_handle = mono_gchandle_from_handle (MONO_HANDLE_CAST (MonoObject, o), TRUE);
mono_array_full_copy_unchecked_size (MONO_HANDLE_RAW (array_handle), MONO_HANDLE_RAW (o), klass, size);
mono_gchandle_free_internal (dst_handle);
MONO_HANDLE_ASSIGN (result, o);
leave:
mono_gchandle_free_internal (src_handle);
return result;
}
/**
* mono_array_clone:
* \param array the array to clone
* \returns A newly created array who is a shallow copy of \p array
*/
MonoArray*
mono_array_clone (MonoArray *array)
{
MONO_REQ_GC_UNSAFE_MODE;
ERROR_DECL (error);
MonoArray *result = mono_array_clone_checked (array, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_array_clone_checked:
* \param array the array to clone
* \param error set on error
* \returns A newly created array who is a shallow copy of \p array. On
* failure returns NULL and sets \p error.
*/
MonoArray*
mono_array_clone_checked (MonoArray *array_raw, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
/* FIXME: callers of mono_array_clone_checked should use handles */
error_init (error);
MONO_HANDLE_DCL (MonoArray, array);
MonoArrayHandle result = mono_array_clone_in_domain (array, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/* helper macros to check for overflow when calculating the size of arrays */
#ifdef MONO_BIG_ARRAYS
#define MYGUINT64_MAX 0x0000FFFFFFFFFFFFUL
#define MYGUINT_MAX MYGUINT64_MAX
#define CHECK_ADD_OVERFLOW_UN(a,b) \
(G_UNLIKELY ((guint64)(MYGUINT64_MAX) - (guint64)(b) < (guint64)(a)))
#define CHECK_MUL_OVERFLOW_UN(a,b) \
(G_UNLIKELY (((guint64)(a) > 0) && ((guint64)(b) > 0) && \
((guint64)(b) > ((MYGUINT64_MAX) / (guint64)(a)))))
#else
#define MYGUINT32_MAX 4294967295U
#define MYGUINT_MAX MYGUINT32_MAX
#define CHECK_ADD_OVERFLOW_UN(a,b) \
(G_UNLIKELY ((guint32)(MYGUINT32_MAX) - (guint32)(b) < (guint32)(a)))
#define CHECK_MUL_OVERFLOW_UN(a,b) \
(G_UNLIKELY (((guint32)(a) > 0) && ((guint32)(b) > 0) && \
((guint32)(b) > ((MYGUINT32_MAX) / (guint32)(a)))))
#endif
gboolean
mono_array_calc_byte_len (MonoClass *klass, uintptr_t len, uintptr_t *res)
{
MONO_REQ_GC_NEUTRAL_MODE;
uintptr_t byte_len;
byte_len = mono_array_element_size (klass);
if (CHECK_MUL_OVERFLOW_UN (byte_len, len))
return FALSE;
byte_len *= len;
if (CHECK_ADD_OVERFLOW_UN (byte_len, MONO_SIZEOF_MONO_ARRAY))
return FALSE;
byte_len += MONO_SIZEOF_MONO_ARRAY;
*res = byte_len;
return TRUE;
}
/**
* mono_array_new_full:
* \param domain domain where the object is created
* \param array_class array class
* \param lengths lengths for each dimension in the array
* \param lower_bounds lower bounds for each dimension in the array (may be NULL)
* This routine creates a new array object with the given dimensions,
* lower bounds and type.
*/
MonoArray*
mono_array_new_full (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds)
{
ERROR_DECL (error);
MonoArray *array = mono_array_new_full_checked (array_class, lengths, lower_bounds, error);
mono_error_cleanup (error);
return array;
}
MonoArray*
mono_array_new_full_checked (MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
uintptr_t byte_len = 0, len, bounds_size;
MonoObject *o;
MonoArray *array;
MonoArrayBounds *bounds;
MonoVTable *vtable;
int i;
error_init (error);
if (!m_class_is_inited (array_class))
mono_class_init_internal (array_class);
len = 1;
guint8 array_class_rank = m_class_get_rank (array_class);
/* A single dimensional array with a 0 lower bound is the same as an szarray */
if (array_class_rank == 1 && ((m_class_get_byval_arg (array_class)->type == MONO_TYPE_SZARRAY) || (lower_bounds && lower_bounds [0] == 0))) {
len = lengths [0];
if (len > MONO_ARRAY_MAX_INDEX) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
bounds_size = 0;
} else {
bounds_size = sizeof (MonoArrayBounds) * array_class_rank;
for (i = 0; i < array_class_rank; ++i) {
if (lengths [i] > MONO_ARRAY_MAX_INDEX) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
if (CHECK_MUL_OVERFLOW_UN (len, lengths [i])) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
len *= lengths [i];
}
}
if (!mono_array_calc_byte_len (array_class, len, &byte_len)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
if (bounds_size) {
/* align */
if (CHECK_ADD_OVERFLOW_UN (byte_len, 3)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
byte_len = (byte_len + 3) & ~3;
if (CHECK_ADD_OVERFLOW_UN (byte_len, bounds_size)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
byte_len += bounds_size;
}
/*
* Following three lines almost taken from mono_object_new ():
* they need to be kept in sync.
*/
vtable = mono_class_vtable_checked (array_class, error);
return_val_if_nok (error, NULL);
if (bounds_size)
o = (MonoObject *)mono_gc_alloc_array (vtable, byte_len, len, bounds_size);
else
o = (MonoObject *)mono_gc_alloc_vector (vtable, byte_len, len);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT "d bytes", (gsize) byte_len);
return NULL;
}
array = (MonoArray*)o;
bounds = array->bounds;
if (bounds_size) {
for (i = 0; i < array_class_rank; ++i) {
bounds [i].length = lengths [i];
if (lower_bounds)
bounds [i].lower_bound = lower_bounds [i];
}
}
return array;
}
static MonoArray*
mono_array_new_jagged_helper (MonoClass *klass, int n, uintptr_t *lengths, int index, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
MonoArray *ret = mono_array_new_full_checked (klass, &lengths [index], NULL, error);
goto_if_nok (error, exit);
MONO_HANDLE_PIN (ret);
if (index < (n - 1)) {
// We have a new dimension argument. This means the elements in the allocated array
// are also arrays and we allocate each one of them.
MonoClass *element_class = m_class_get_element_class (klass);
g_assert (m_class_get_rank (element_class) == 1);
for (int i = 0; i < lengths [index]; i++) {
MonoArray *o = mono_array_new_jagged_helper (element_class, n, lengths, index + 1, error);
goto_if_nok (error, exit);
mono_array_setref_fast (ret, i, o);
}
}
exit:
HANDLE_FUNCTION_RETURN_VAL (ret);
}
MonoArray *
mono_array_new_jagged_checked (MonoClass *klass, int n, uintptr_t *lengths, MonoError *error)
{
return mono_array_new_jagged_helper (klass, n, lengths, 0, error);
}
/**
* mono_array_new:
* \param domain domain where the object is created
* \param eclass element class
* \param n number of array elements
* This routine creates a new szarray with \p n elements of type \p eclass.
*/
MonoArray *
mono_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n)
{
MonoArray *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_array_new_checked (eclass, n, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_array_new_checked:
* \param eclass element class
* \param n number of array elements
* \param error set on error
* This routine creates a new szarray with \p n elements of type \p eclass.
* On failure returns NULL and sets \p error.
*/
MonoArray *
mono_array_new_checked (MonoClass *eclass, uintptr_t n, MonoError *error)
{
MonoClass *ac;
error_init (error);
ac = mono_class_create_array (eclass, 1);
g_assert (ac);
MonoVTable *vtable = mono_class_vtable_checked (ac, error);
return_val_if_nok (error, NULL);
return mono_array_new_specific_checked (vtable, n, error);
}
/**
* mono_array_new_specific:
* \param vtable a vtable in the appropriate domain for an initialized class
* \param n number of array elements
* This routine is a fast alternative to \c mono_array_new for code which
* can be sure about the domain it operates in.
*/
MonoArray *
mono_array_new_specific (MonoVTable *vtable, uintptr_t n)
{
ERROR_DECL (error);
MonoArray *arr = mono_array_new_specific_checked (vtable, n, error);
mono_error_cleanup (error);
return arr;
}
static MonoArray*
mono_array_new_specific_internal (MonoVTable *vtable, uintptr_t n, gboolean pinned, MonoError *error)
{
MonoArray *o;
uintptr_t byte_len;
error_init (error);
if (G_UNLIKELY (n > MONO_ARRAY_MAX_INDEX)) {
mono_error_set_generic_error (error, "System", "OverflowException", "");
return NULL;
}
if (!mono_array_calc_byte_len (vtable->klass, n, &byte_len)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", MONO_ARRAY_MAX_SIZE);
return NULL;
}
if (pinned)
o = mono_gc_alloc_pinned_vector (vtable, byte_len, n);
else
o = mono_gc_alloc_vector (vtable, byte_len, n);
if (G_UNLIKELY (!o)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT "d bytes", (gsize) byte_len);
return NULL;
}
return o;
}
MonoArray*
mono_array_new_specific_checked (MonoVTable *vtable, uintptr_t n, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_array_new_specific_internal (vtable, n, FALSE, error);
}
MonoArrayHandle
ves_icall_System_GC_AllocPinnedArray (MonoReflectionTypeHandle array_type, gint32 length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass *klass = mono_class_from_mono_type_internal (MONO_HANDLE_GETVAL (array_type, type));
MonoVTable *vtable = mono_class_vtable_checked (klass, error);
goto_if_nok (error, fail);
MonoArray *arr;
arr = mono_array_new_specific_internal (vtable, length, TRUE, error);
goto_if_nok (error, fail);
return MONO_HANDLE_NEW (MonoArray, arr);
fail:
return MONO_HANDLE_NEW (MonoArray, NULL);
}
MonoArrayHandle
mono_array_new_specific_handle (MonoVTable *vtable, uintptr_t n, MonoError *error)
{
// FIXMEcoop invert relationship with mono_array_new_specific_checked
return MONO_HANDLE_NEW (MonoArray, mono_array_new_specific_checked (vtable, n, error));
}
MonoArray*
ves_icall_array_new_specific (MonoVTable *vtable, uintptr_t n)
{
ERROR_DECL (error);
MonoArray *arr = mono_array_new_specific_checked (vtable, n, error);
mono_error_set_pending_exception (error);
return arr;
}
gboolean
mono_string_equal_internal (MonoString *s1, MonoString *s2)
{
int l1 = mono_string_length_internal (s1);
int l2 = mono_string_length_internal (s2);
if (s1 == s2)
return TRUE;
if (l1 != l2)
return FALSE;
return memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), l1 * 2) == 0;
}
guint
mono_string_hash_internal (MonoString *s)
{
const gunichar2 *p = mono_string_chars_internal (s);
int i, len = mono_string_length_internal (s);
guint h = 0;
for (i = 0; i < len; i++) {
h = (h << 5) - h + *p;
p++;
}
return h;
}
/**
* mono_string_empty_wrapper:
*
* Returns: The same empty string instance as the managed string.Empty
*/
MonoString*
mono_string_empty_wrapper (void)
{
MonoDomain *domain = mono_domain_get ();
return mono_string_empty_internal (domain);
}
MonoString*
mono_string_empty_internal (MonoDomain *domain)
{
g_assert (domain);
g_assert (domain->empty_string);
return domain->empty_string;
}
/**
* mono_string_empty:
*
* Returns: The same empty string instance as the managed string.Empty
*/
MonoString*
mono_string_empty (MonoDomain *domain)
{
MONO_EXTERNAL_ONLY (MonoString*, mono_string_empty_internal (domain));
}
MonoStringHandle
mono_string_empty_handle (void)
{
MonoDomain *domain = mono_get_root_domain ();
return MONO_HANDLE_NEW (MonoString, mono_string_empty_internal (domain));
}
/**
* mono_string_new_utf16:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \returns A newly created string object which contains \p text.
*/
MonoString *
mono_string_new_utf16 (MonoDomain *domain, const mono_unichar2 *text, gint32 len)
{
MonoString *res = NULL;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
res = mono_string_new_utf16_checked (text, len, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return res;
}
/**
* mono_string_new_utf16_checked:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \param error written on error.
* \returns A newly created string object which contains \p text.
* On error, returns NULL and sets \p error.
*/
MonoString *
mono_string_new_utf16_checked (const gunichar2 *text, gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString *s;
error_init (error);
s = mono_string_new_size_checked (len, error);
if (s != NULL)
memcpy (mono_string_chars_internal (s), text, len * 2);
return s;
}
/**
* mono_string_new_utf16_handle:
* \param text a pointer to an utf16 string
* \param len the length of the string
* \param error written on error.
* \returns A newly created string object which contains \p text.
* On error, returns NULL and sets \p error.
*/
MonoStringHandle
mono_string_new_utf16_handle (const gunichar2 *text, gint32 len, MonoError *error)
{
return MONO_HANDLE_NEW (MonoString, mono_string_new_utf16_checked (text, len, error));
}
/**
* mono_string_new_utf32_checked:
* \param text a pointer to an utf32 string
* \param len the length of the string
* \param error set on failure.
* \returns A newly created string object which contains \p text. On failure returns NULL and sets \p error.
*/
static MonoString *
mono_string_new_utf32_checked (const mono_unichar4 *text, gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString *s;
mono_unichar2 *utf16_output = NULL;
error_init (error);
utf16_output = g_ucs4_to_utf16 (text, len, NULL, NULL, NULL);
gint32 utf16_len = g_utf16_len (utf16_output);
s = mono_string_new_size_checked (utf16_len, error);
goto_if_nok (error, exit);
memcpy (mono_string_chars_internal (s), utf16_output, utf16_len * 2);
exit:
g_free (utf16_output);
return s;
}
/**
* mono_string_new_utf32:
* \param text a pointer to a UTF-32 string
* \param len the length of the string
* \returns A newly created string object which contains \p text.
*/
MonoString *
mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len)
{
ERROR_DECL (error);
MonoString *result = mono_string_new_utf32_checked (text, len, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_new_size:
* \param text a pointer to a UTF-16 string
* \param len the length of the string
* \returns A newly created string object of \p len
*/
MonoString *
mono_string_new_size (MonoDomain *domain, gint32 len)
{
MonoString *str;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
str = mono_string_new_size_checked (len, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return str;
}
MonoStringHandle
mono_string_new_size_handle (gint32 len, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoStringHandle s;
MonoVTable *vtable;
size_t size;
error_init (error);
/* check for overflow */
if (len < 0 || len > ((SIZE_MAX - G_STRUCT_OFFSET (MonoString, chars) - 8) / 2)) {
mono_error_set_out_of_memory (error, "Could not allocate %i bytes", -1);
return NULL_HANDLE_STRING;
}
size = (G_STRUCT_OFFSET (MonoString, chars) + (((size_t)len + 1) * 2));
g_assert (size > 0);
vtable = mono_class_vtable_checked (mono_defaults.string_class, error);
return_val_if_nok (error, NULL_HANDLE_STRING);
s = mono_gc_alloc_handle_string (vtable, size, len);
if (G_UNLIKELY (MONO_HANDLE_IS_NULL (s)))
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT " bytes", size);
return s;
}
MonoString *
mono_string_new_size_checked (gint32 length, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_OBJ (mono_string_new_size_handle (length, error));
}
/**
* mono_string_new_len:
* \param text a pointer to an utf8 string
* \param length number of bytes in \p text to consider
* \returns A newly created string object which contains \p text.
*/
MonoString*
mono_string_new_len (MonoDomain *domain, const char *text, guint length)
{
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MonoStringHandle result;
MONO_ENTER_GC_UNSAFE;
result = mono_string_new_utf8_len (text, length, error);
MONO_EXIT_GC_UNSAFE;
mono_error_cleanup (error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_string_new_utf8_len:
* \param text a pointer to an utf8 string
* \param length number of bytes in \p text to consider
* \param error set on error
* \returns A newly created string object which contains \p text. On
* failure returns NULL and sets \p error.
*/
MonoStringHandle
mono_string_new_utf8_len (const char *text, guint length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
GError *eg_error = NULL;
MonoStringHandle o = NULL_HANDLE_STRING;
gunichar2 *ut = NULL;
glong items_written;
ut = eg_utf8_to_utf16_with_nuls (text, length, NULL, &items_written, &eg_error);
if (eg_error) {
o = NULL_HANDLE_STRING;
// Like mono_ldstr_utf8:
mono_error_set_argument (error, "string", eg_error->message);
// FIXME? See mono_string_new_checked.
//mono_error_set_execution_engine (error, "String conversion error: %s", eg_error->message);
g_error_free (eg_error);
} else {
o = mono_string_new_utf16_handle (ut, items_written, error);
}
g_free (ut);
return o;
}
MonoString*
mono_string_new_len_checked (const char *text, guint length, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
error_init (error);
HANDLE_FUNCTION_RETURN_OBJ (mono_string_new_utf8_len (text, length, error));
}
static
MonoString*
mono_string_new_internal (const char *text)
{
ERROR_DECL (error);
MonoString *res = NULL;
res = mono_string_new_checked (text, error);
if (!is_ok (error)) {
/* Mono API compatability: assert on Out of Memory errors,
* return NULL otherwise (most likely an invalid UTF-8 byte
* sequence). */
if (mono_error_get_error_code (error) == MONO_ERROR_OUT_OF_MEMORY)
mono_error_assert_ok (error);
else
mono_error_cleanup (error);
}
return res;
}
/**
* mono_string_new:
* \param text a pointer to a UTF-8 string
* \deprecated Use \c mono_string_new_checked in new code.
* This function asserts if it cannot allocate a new string.
* \returns A newly created string object which contains \p text.
*/
MonoString*
mono_string_new (MonoDomain *domain, const char *text)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoString*, mono_string_new_internal (text));
}
/**
* mono_string_new_checked:
* \param text a pointer to an utf8 string
* \param merror set on error
* \returns A newly created string object which contains \p text.
* On error returns NULL and sets \p merror.
*/
MonoString*
mono_string_new_checked (const char *text, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
GError *eg_error = NULL;
MonoString *o = NULL;
gunichar2 *ut;
glong items_written;
int len;
error_init (error);
len = strlen (text);
ut = g_utf8_to_utf16 (text, len, NULL, &items_written, &eg_error);
if (!eg_error)
o = mono_string_new_utf16_checked (ut, items_written, error);
else {
mono_error_set_execution_engine (error, "String conversion error: %s", eg_error->message);
g_error_free (eg_error);
}
g_free (ut);
return o;
}
/**
* mono_string_new_wtf8_len_checked:
* \param text a pointer to an wtf8 string (see https://simonsapin.github.io/wtf-8/)
* \param length number of bytes in \p text to consider
* \param merror set on error
* \returns A newly created string object which contains \p text.
* On error returns NULL and sets \p merror.
*/
MonoString*
mono_string_new_wtf8_len_checked (const char *text, guint length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
GError *eg_error = NULL;
MonoString *o = NULL;
gunichar2 *ut = NULL;
glong items_written;
ut = eg_wtf8_to_utf16 (text, length, NULL, &items_written, &eg_error);
if (!eg_error)
o = mono_string_new_utf16_checked (ut, items_written, error);
else
g_error_free (eg_error);
g_free (ut);
return o;
}
MonoStringHandle
mono_string_new_wrapper_internal_impl (const char *text, MonoError *error)
{
return MONO_HANDLE_NEW (MonoString, mono_string_new_internal (text));
}
/**
* mono_string_new_wrapper:
* \param text pointer to UTF-8 characters.
* Helper function to create a string object from \p text in the current domain.
*/
MonoString*
mono_string_new_wrapper (const char *text)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoString*, mono_string_new_wrapper_internal (text));
}
/**
* mono_value_box:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \returns A newly created object which contains \p value.
*/
MonoObject *
mono_value_box (MonoDomain *domain, MonoClass *klass, gpointer value)
{
MonoObject *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_value_box_checked (klass, value, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_value_box_handle:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \param error set on error
* \returns A newly created object which contains \p value. On failure
* returns NULL and sets \p error.
*/
MonoObjectHandle
mono_value_box_handle (MonoClass *klass, gpointer value, MonoError *error)
{
// FIXMEcoop gpointer value needs more attention
MONO_REQ_GC_UNSAFE_MODE;
MonoVTable *vtable;
error_init (error);
g_assert (m_class_is_valuetype (klass));
g_assert (value != NULL);
if (G_UNLIKELY (m_class_is_byreflike (klass))) {
char *full_name = mono_type_get_full_name (klass);
mono_error_set_not_supported (error, "Cannot box IsByRefLike type %s", full_name);
g_free (full_name);
return NULL_HANDLE;
}
if (mono_class_is_nullable (klass))
return mono_nullable_box_handle (value, klass, error);
vtable = mono_class_vtable_checked (klass, error);
return_val_if_nok (error, NULL_HANDLE);
int size = mono_class_instance_size (klass);
MonoObjectHandle res_handle = mono_object_new_alloc_by_vtable (vtable, error);
return_val_if_nok (error, NULL_HANDLE);
size -= MONO_ABI_SIZEOF (MonoObject);
if (mono_gc_is_moving ()) {
g_assert (size == mono_class_value_size (klass, NULL));
MONO_ENTER_NO_SAFEPOINTS;
gpointer data = mono_handle_get_data_unsafe (res_handle);
mono_gc_wbarrier_value_copy_internal (data, value, 1, klass);
MONO_EXIT_NO_SAFEPOINTS;
} else {
MONO_ENTER_NO_SAFEPOINTS;
gpointer data = mono_handle_get_data_unsafe (res_handle);
#if NO_UNALIGNED_ACCESS
mono_gc_memmove_atomic (data, value, size);
#else
switch (size) {
case 1:
*(guint8*)data = *(guint8 *) value;
break;
case 2:
*(guint16 *)(data) = *(guint16 *) value;
break;
case 4:
*(guint32 *)(data) = *(guint32 *) value;
break;
case 8:
*(guint64 *)(data) = *(guint64 *) value;
break;
default:
mono_gc_memmove_atomic (data, value, size);
}
#endif
MONO_EXIT_NO_SAFEPOINTS;
}
if (m_class_has_finalize (klass))
mono_object_register_finalizer_handle (res_handle);
return res_handle;
}
/**
* mono_value_box_checked:
* \param class the class of the value
* \param value a pointer to the unboxed data
* \param error set on error
* \returns A newly created object which contains \p value. On failure
* returns NULL and sets \p error.
*/
MonoObject *
mono_value_box_checked (MonoClass *klass, gpointer value, MonoError *error)
{
HANDLE_FUNCTION_ENTER ();
HANDLE_FUNCTION_RETURN_OBJ (mono_value_box_handle (klass, value, error));
}
void
mono_value_copy_internal (gpointer dest, gconstpointer src, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
mono_gc_wbarrier_value_copy_internal (dest, src, 1, klass);
}
/**
* mono_value_copy:
* \param dest destination pointer
* \param src source pointer
* \param klass a valuetype class
* Copy a valuetype from \p src to \p dest. This function must be used
* when \p klass contains reference fields.
*/
void
mono_value_copy (gpointer dest, gpointer src, MonoClass *klass)
{
mono_value_copy_internal (dest, src, klass);
}
void
mono_value_copy_array_internal (MonoArray *dest, int dest_idx, gconstpointer src, int count)
{
MONO_REQ_GC_UNSAFE_MODE;
int size = mono_array_element_size (dest->obj.vtable->klass);
char *d = mono_array_addr_with_size_fast (dest, size, dest_idx);
g_assert (size == mono_class_value_size (m_class_get_element_class (mono_object_class (dest)), NULL));
// FIXME remove (gpointer) cast.
mono_gc_wbarrier_value_copy_internal (d, (gpointer)src, count, m_class_get_element_class (mono_object_class (dest)));
}
void
mono_value_copy_array_handle (MonoArrayHandle dest, int dest_idx, gconstpointer src, int count)
{
mono_value_copy_array_internal (MONO_HANDLE_RAW (dest), dest_idx, src, count);
}
/**
* mono_value_copy_array:
* \param dest destination array
* \param dest_idx index in the \p dest array
* \param src source pointer
* \param count number of items
* Copy \p count valuetype items from \p src to the array \p dest at index \p dest_idx.
* This function must be used when \p klass contains references fields.
* Overlap is handled.
*/
void
mono_value_copy_array (MonoArray *dest, int dest_idx, void* src, int count)
{
MONO_EXTERNAL_ONLY_VOID (mono_value_copy_array_internal (dest, dest_idx, src, count));
}
MonoVTable *
mono_object_get_vtable_internal (MonoObject *obj)
{
// This could be called during STW, so untag the vtable if needed.
return mono_gc_get_vtable (obj);
}
MonoVTable*
mono_object_get_vtable (MonoObject *obj)
{
MONO_EXTERNAL_ONLY (MonoVTable*, mono_object_get_vtable_internal (obj));
}
MonoDomain*
mono_object_get_domain_internal (MonoObject *obj)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_object_domain (obj);
}
/**
* mono_object_get_domain:
* \param obj object to query
* \returns the \c MonoDomain where the object is hosted
*/
MonoDomain*
mono_object_get_domain (MonoObject *obj)
{
MonoDomain* ret = NULL;
MONO_ENTER_GC_UNSAFE;
ret = mono_object_get_domain_internal (obj);
MONO_EXIT_GC_UNSAFE;
return ret;
}
/**
* mono_object_get_class:
* \param obj object to query
* Use this function to obtain the \c MonoClass* for a given \c MonoObject.
* \returns the \c MonoClass of the object.
*/
MonoClass*
mono_object_get_class (MonoObject *obj)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoClass*, mono_object_class (obj));
}
guint
mono_object_get_size_internal (MonoObject* o)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoClass* klass = mono_object_class (o);
if (klass == mono_defaults.string_class) {
return MONO_SIZEOF_MONO_STRING + 2 * mono_string_length_internal ((MonoString*) o) + 2;
} else if (o->vtable->rank) {
MonoArray *array = (MonoArray*)o;
size_t size = MONO_SIZEOF_MONO_ARRAY + mono_array_element_size (klass) * mono_array_length_internal (array);
if (array->bounds) {
size += 3;
size &= ~3;
size += sizeof (MonoArrayBounds) * o->vtable->rank;
}
return size;
} else {
return mono_class_instance_size (klass);
}
}
/**
* mono_object_get_size:
* \param o object to query
* \returns the size, in bytes, of \p o
*/
unsigned
mono_object_get_size (MonoObject *o)
{
MONO_EXTERNAL_ONLY (unsigned, mono_object_get_size_internal (o));
}
/**
* mono_object_unbox:
* \param obj object to unbox
* \returns a pointer to the start of the valuetype boxed in this
* object.
*
* This method will assert if the object passed is not a valuetype.
*/
void*
mono_object_unbox (MonoObject *obj)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
}
/**
* mono_object_isinst:
* \param obj an object
* \param klass a pointer to a class
* \returns \p obj if \p obj is derived from \p klass or NULL otherwise.
*/
MonoObject *
mono_object_isinst (MonoObject *obj_raw, MonoClass *klass)
{
HANDLE_FUNCTION_ENTER ();
MonoObjectHandle result;
MONO_ENTER_GC_UNSAFE;
MONO_HANDLE_DCL (MonoObject, obj);
ERROR_DECL (error);
result = mono_object_handle_isinst (obj, klass, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_isinst_checked:
* \param obj an object
* \param klass a pointer to a class
* \param error set on error
* \returns \p obj if \p obj is derived from \p klass or NULL if it isn't.
* On failure returns NULL and sets \p error.
*/
MonoObject *
mono_object_isinst_checked (MonoObject *obj_raw, MonoClass *klass, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
error_init (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = mono_object_handle_isinst (obj, klass, error);
HANDLE_FUNCTION_RETURN_OBJ (result);
}
/**
* mono_object_handle_isinst:
* \param obj an object
* \param klass a pointer to a class
* \param error set on error
* \returns \p obj if \p obj is derived from \p klass or NULL if it isn't.
* On failure returns NULL and sets \p error.
*/
MonoObjectHandle
mono_object_handle_isinst (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
error_init (error);
if (!m_class_is_inited (klass))
mono_class_init_internal (klass);
if (mono_class_is_interface (klass))
return mono_object_handle_isinst_mbyref (obj, klass, error);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (!MONO_HANDLE_IS_NULL (obj) && mono_class_is_assignable_from_internal (klass, mono_handle_class (obj)))
MONO_HANDLE_ASSIGN (result, obj);
return result;
}
/**
* mono_object_isinst_mbyref:
*/
MonoObject *
mono_object_isinst_mbyref (MonoObject *obj_raw, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = mono_object_handle_isinst_mbyref (obj, klass, error);
mono_error_cleanup (error); /* FIXME better API that doesn't swallow the error */
HANDLE_FUNCTION_RETURN_OBJ (result);
}
MonoObjectHandle
mono_object_handle_isinst_mbyref (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
gboolean success = FALSE;
error_init (error);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
success = mono_object_handle_isinst_mbyref_raw (obj, klass, error);
if (success && is_ok (error))
MONO_HANDLE_ASSIGN (result, obj);
leave:
return result;
}
gboolean
mono_object_handle_isinst_mbyref_raw (MonoObjectHandle obj, MonoClass *klass, MonoError *error)
{
error_init (error);
gboolean result = FALSE;
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
MonoVTable *vt;
vt = MONO_HANDLE_GETVAL (obj, vtable);
if (mono_class_is_interface (klass)) {
if (MONO_VTABLE_IMPLEMENTS_INTERFACE (vt, m_class_get_interface_id (klass))) {
result = TRUE;
goto leave;
}
/* casting an array one of the invariant interfaces that must act as such */
if (m_class_is_array_special_interface (klass)) {
if (mono_class_is_assignable_from_internal (klass, vt->klass)) {
result = TRUE;
goto leave;
}
}
/*If the above check fails we are in the slow path of possibly raising an exception. So it's ok to it this way.*/
else if (mono_class_has_variant_generic_params (klass) && mono_class_is_assignable_from_internal (klass, mono_handle_class (obj))) {
result = TRUE;
goto leave;
}
} else {
MonoClass *oklass = vt->klass;
mono_class_setup_supertypes (klass);
if (mono_class_has_parent_fast (oklass, klass)) {
result = TRUE;
goto leave;
}
}
leave:
return result;
}
/**
* mono_object_castclass_mbyref:
* \param obj an object
* \param klass a pointer to a class
* \returns \p obj if \p obj is derived from \p klass, returns NULL otherwise.
*/
MonoObject *
mono_object_castclass_mbyref (MonoObject *obj_raw, MonoClass *klass)
{
MONO_REQ_GC_UNSAFE_MODE;
HANDLE_FUNCTION_ENTER ();
ERROR_DECL (error);
MONO_HANDLE_DCL (MonoObject, obj);
MonoObjectHandle result = MONO_HANDLE_NEW (MonoObject, NULL);
if (MONO_HANDLE_IS_NULL (obj))
goto leave;
MONO_HANDLE_ASSIGN (result, mono_object_handle_isinst_mbyref (obj, klass, error));
mono_error_cleanup (error);
leave:
HANDLE_FUNCTION_RETURN_OBJ (result);
}
static MonoStringHandle
mono_string_get_pinned (MonoStringHandle str, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
/* We only need to make a pinned version of a string if this is a moving GC */
if (!mono_gc_is_moving ())
return str;
const gsize length = mono_string_handle_length (str);
const gsize size = MONO_SIZEOF_MONO_STRING + (length + 1) * sizeof (gunichar2);
MonoStringHandle news = MONO_HANDLE_CAST (MonoString, mono_gc_alloc_handle_pinned_obj (MONO_HANDLE_GETVAL (str, object.vtable), size));
if (!MONO_HANDLE_BOOL (news)) {
mono_error_set_out_of_memory (error, "Could not allocate %" G_GSIZE_FORMAT " bytes", size);
return news;
}
MONO_ENTER_NO_SAFEPOINTS;
memcpy (mono_string_chars_internal (MONO_HANDLE_RAW (news)),
mono_string_chars_internal (MONO_HANDLE_RAW (str)),
length * sizeof (gunichar2));
MONO_EXIT_NO_SAFEPOINTS;
MONO_HANDLE_SETVAL (news, length, int, length);
return news;
}
MonoStringHandle
mono_string_is_interned_lookup (MonoStringHandle str, gboolean insert, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
if (!ldstr_table) {
MonoGHashTable *table = mono_g_hash_table_new_type_internal ((GHashFunc)mono_string_hash_internal, (GCompareFunc)mono_string_equal_internal, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, mono_get_root_domain (), "Domain String Pool Table");
mono_memory_barrier ();
ldstr_table = table;
}
ldstr_lock ();
MonoString *res = (MonoString *)mono_g_hash_table_lookup (ldstr_table, MONO_HANDLE_RAW (str));
ldstr_unlock ();
if (res)
return MONO_HANDLE_NEW (MonoString, res);
if (!insert)
return NULL_HANDLE_STRING;
// Allocate outside the lock.
MonoStringHandle s = mono_string_get_pinned (str, error);
if (!is_ok (error) || !MONO_HANDLE_BOOL (s))
return NULL_HANDLE_STRING;
// Try again inside lock.
ldstr_lock ();
res = (MonoString *)mono_g_hash_table_lookup (ldstr_table, MONO_HANDLE_RAW (str));
if (res)
MONO_HANDLE_ASSIGN_RAW (s, res);
else {
mono_g_hash_table_insert_internal (ldstr_table, MONO_HANDLE_RAW (s), MONO_HANDLE_RAW (s));
#ifdef HOST_WASM
mono_set_string_interned_internal ((MonoObject *)MONO_HANDLE_RAW (s));
#endif
}
ldstr_unlock ();
return s;
}
#ifdef HOST_WASM
/**
* mono_string_instance_is_interned:
* Checks to see if the string instance has its interned flag set.
* \param str String to probe
* \returns TRUE if the string instance is interned, FALSE otherwise.
*/
int
mono_string_instance_is_interned (MonoString *str)
{
return mono_is_string_interned_internal ((MonoObject *)str);
}
#endif
/**
* mono_string_is_interned:
* Searches the interned string table for a string with value equal to the provided string.
* \param str String to probe
* \returns The string located within the intern table, or null.
*/
MonoString*
mono_string_is_interned (MonoString *str_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoString, str);
MONO_ENTER_GC_UNSAFE;
str = mono_string_is_interned_internal (str, error);
MONO_EXIT_GC_UNSAFE;
mono_error_assert_ok (error);
HANDLE_FUNCTION_RETURN_OBJ (str);
}
/**
* mono_string_intern:
* \param o String to intern
* Interns the string passed.
* \returns The interned string.
*/
MonoString*
mono_string_intern (MonoString *str_raw)
{
ERROR_DECL (error);
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL (MonoString, str);
MONO_ENTER_GC_UNSAFE;
str = mono_string_intern_checked (str, error);
MONO_EXIT_GC_UNSAFE;
HANDLE_FUNCTION_RETURN_OBJ (str);
}
/**
* mono_ldstr:
* \param domain the domain where the string will be used.
* \param image a metadata context
* \param idx index into the user string table.
* Implementation for the \c ldstr opcode.
* \returns a loaded string from the \p image / \p idx combination.
*/
MonoString*
mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
{
MonoString *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_ldstr_checked (image, idx, error);
mono_error_cleanup (error);
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_ldstr_checked:
* \param image a metadata context
* \param idx index into the user string table.
* \param error set on error.
* Implementation for the \c ldstr opcode.
* \returns A loaded string from the \p image / \p idx combination.
* On failure returns NULL and sets \p error.
*/
MonoString*
mono_ldstr_checked (MonoImage *image, guint32 idx, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
HANDLE_FUNCTION_ENTER ();
MonoStringHandle str = MONO_HANDLE_NEW (MonoString, NULL);
if (image->dynamic) {
MONO_HANDLE_ASSIGN_RAW (str, (MonoString *)mono_lookup_dynamic_token (image, MONO_TOKEN_STRING | idx, NULL, error));
goto exit;
}
mono_ldstr_metadata_sig (mono_metadata_user_string (image, idx), str, error);
exit:
HANDLE_FUNCTION_RETURN_OBJ (str);
}
MonoStringHandle
mono_ldstr_handle (MonoImage *image, guint32 idx, MonoError *error)
{
// FIXME invert mono_ldstr_handle and mono_ldstr_checked.
return MONO_HANDLE_NEW (MonoString, mono_ldstr_checked (image, idx, error));
}
char*
mono_string_from_blob (const char *str, MonoError *error)
{
gsize len = mono_metadata_decode_blob_size (str, &str) >> 1;
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
gunichar2 *src = (gunichar2*)str;
gunichar2 *copy = g_new (gunichar2, len);
int i;
for (i = 0; i < len; ++i)
copy [i] = GUINT16_FROM_LE (src [i]);
char *res = mono_utf16_to_utf8 (copy, len, error);
g_free (copy);
return res;
#else
return mono_utf16_to_utf8 ((const gunichar2*)str, len, error);
#endif
}
/**
* mono_ldstr_metadata_sig
* \param sig the signature of a metadata string
* \param error set on error
* \returns a \c MonoString for a string stored in the metadata. On
* failure returns NULL and sets \p error.
*/
static void
mono_ldstr_metadata_sig (const char* sig, MonoStringHandleOut string_handle, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MONO_HANDLE_ASSIGN_RAW (string_handle, NULL);
const gsize len = mono_metadata_decode_blob_size (sig, &sig) / sizeof (gunichar2);
// FIXMEcoop excess handle, use mono_string_new_utf16_checked and string_handle parameter
MonoStringHandle o = mono_string_new_utf16_handle ((gunichar2*)sig, len, error);
return_if_nok (error);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
gunichar2 *p = mono_string_chars_internal (MONO_HANDLE_RAW (o));
for (gsize i = 0; i < len; ++i)
p [i] = GUINT16_FROM_LE (p [i]);
#endif
// FIXMEcoop excess handle in mono_string_intern_checked
MONO_HANDLE_ASSIGN_RAW (string_handle, MONO_HANDLE_RAW (mono_string_intern_checked (o, error)));
}
/*
* mono_ldstr_utf8:
*
* Same as mono_ldstr, but return a NULL terminated utf8 string instead
* of an object.
*/
char*
mono_ldstr_utf8 (MonoImage *image, guint32 idx, MonoError *error)
{
const char *str;
size_t len2;
long written = 0;
char *as;
GError *gerror = NULL;
error_init (error);
str = mono_metadata_user_string (image, idx);
len2 = mono_metadata_decode_blob_size (str, &str);
len2 >>= 1;
as = g_utf16_to_utf8 ((gunichar2*)str, len2, NULL, &written, &gerror);
if (gerror) {
mono_error_set_argument (error, "string", gerror->message);
g_error_free (gerror);
return NULL;
}
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (len2 > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (len2);
memcpy (as2, as, written);
g_free (as);
as = as2;
}
return as;
}
/**
* mono_string_to_utf8:
* \param s a \c System.String
* \deprecated Use \c mono_string_to_utf8_checked_internal to avoid having an exception arbitrarily raised.
* \returns the UTF-8 representation for \p s.
* The resulting buffer needs to be freed with \c mono_free().
*/
char *
mono_string_to_utf8 (MonoString *s)
{
char *result;
MONO_ENTER_GC_UNSAFE;
ERROR_DECL (error);
result = mono_string_to_utf8_checked_internal (s, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
result = NULL;
}
MONO_EXIT_GC_UNSAFE;
return result;
}
/**
* mono_utf16_to_utf8len:
*/
char *
mono_utf16_to_utf8len (const gunichar2 *s, gsize slength, gsize *utf8_length, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
long written = 0;
*utf8_length = 0;
char *as;
GError *gerror = NULL;
error_init (error);
if (s == NULL)
return NULL;
if (!slength)
return g_strdup ("");
as = g_utf16_to_utf8 (s, slength, NULL, &written, &gerror);
*utf8_length = written;
if (gerror) {
mono_error_set_argument (error, "string", gerror->message);
g_error_free (gerror);
return NULL;
}
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (slength > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (slength);
memcpy (as2, as, written);
g_free (as);
as = as2;
// FIXME utf8_length is ambiguous here.
// For now it is what strlen would report.
// A lot of code does not deal correctly with embedded nuls.
}
return as;
}
/**
* mono_utf16_to_utf8:
*/
char *
mono_utf16_to_utf8 (const gunichar2 *s, gsize slength, MonoError *error)
{
gsize utf8_length = 0;
return mono_utf16_to_utf8len (s, slength, &utf8_length, error);
}
char *
mono_string_to_utf8_checked_internal (MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (s == NULL)
return NULL;
if (!s->length)
return g_strdup ("");
return mono_utf16_to_utf8 (mono_string_chars_internal (s), s->length, error);
}
char *
mono_string_to_utf8len (MonoStringHandle s, gsize *utf8len, MonoError *error)
{
*utf8len = 0;
if (MONO_HANDLE_IS_NULL (s))
return NULL;
char *utf8;
MONO_ENTER_NO_SAFEPOINTS;
utf8 = mono_utf16_to_utf8len (mono_string_chars_internal (MONO_HANDLE_RAW (s)), mono_string_handle_length (s), utf8len, error);
MONO_EXIT_NO_SAFEPOINTS;
return utf8;
}
/**
* mono_string_to_utf8_checked:
* \param s a \c System.String
* \param error a \c MonoError.
* Converts a \c MonoString to its UTF-8 representation. May fail; check
* \p error to determine whether the conversion was successful.
* The resulting buffer should be freed with \c mono_free().
*/
char*
mono_string_to_utf8_checked (MonoString *string_obj, MonoError *error)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (char*, mono_string_to_utf8_checked_internal (string_obj, error));
}
char *
mono_string_handle_to_utf8 (MonoStringHandle s, MonoError *error)
{
return mono_string_to_utf8_checked_internal (MONO_HANDLE_RAW (s), error);
}
/**
* mono_string_to_utf8_ignore:
* \param s a MonoString
* Converts a \c MonoString to its UTF-8 representation. Will ignore
* invalid surrogate pairs.
* The resulting buffer should be freed with \c mono_free().
*/
char *
mono_string_to_utf8_ignore (MonoString *s)
{
MONO_REQ_GC_UNSAFE_MODE;
long written = 0;
char *as;
if (s == NULL)
return NULL;
if (!s->length)
return g_strdup ("");
as = g_utf16_to_utf8 (mono_string_chars_internal (s), s->length, NULL, &written, NULL);
/* g_utf16_to_utf8 may not be able to complete the conversion (e.g. NULL values were found, #335488) */
if (s->length > written) {
/* allocate the total length and copy the part of the string that has been converted */
char *as2 = (char *)g_malloc0 (s->length);
memcpy (as2, as, written);
g_free (as);
as = as2;
}
return as;
}
mono_unichar2*
mono_string_to_utf16_internal_impl (MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXME This optimization ok to miss before wrapper? Or null is rare?
if (MONO_HANDLE_RAW (s) == NULL)
return NULL;
int const length = mono_string_handle_length (s);
mono_unichar2* const as = (mono_unichar2*)g_malloc ((length + 1) * sizeof (*as));
if (as) {
as [length] = 0;
if (length)
memcpy (as, mono_string_chars_internal (MONO_HANDLE_RAW (s)), length * sizeof (*as));
}
return as;
}
/**
* mono_string_to_utf16:
* \param s a \c MonoString
* \returns a null-terminated array of the UTF-16 chars
* contained in \p s. The result must be freed with \c g_free().
* This is a temporary helper until our string implementation
* is reworked to always include the null-terminating char.
*/
mono_unichar2*
mono_string_to_utf16 (MonoString *string_obj)
{
if (!string_obj)
return NULL;
MONO_EXTERNAL_ONLY (mono_unichar2*, mono_string_to_utf16_internal (string_obj));
}
mono_unichar4*
mono_string_to_utf32_internal_impl (MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
// FIXME This optimization ok to miss before wrapper? Or null is rare?
if (MONO_HANDLE_RAW (s) == NULL)
return NULL;
return g_utf16_to_ucs4 (MONO_HANDLE_RAW (s)->chars, mono_string_handle_length (s), NULL, NULL, NULL);
}
/**
* mono_string_to_utf32:
* \param s a \c MonoString
* \returns a null-terminated array of the UTF-32 (UCS-4) chars
* contained in \p s. The result must be freed with \c g_free().
*/
mono_unichar4*
mono_string_to_utf32 (MonoString *string_obj)
{
MONO_EXTERNAL_ONLY (mono_unichar4*, mono_string_to_utf32_internal (string_obj));
}
/**
* mono_string_from_utf16:
* \param data the UTF-16 string (LPWSTR) to convert
* Converts a NULL-terminated UTF-16 string (LPWSTR) to a \c MonoString.
* \returns a \c MonoString.
*/
MonoString *
mono_string_from_utf16 (gunichar2 *data)
{
ERROR_DECL (error);
MonoString *result = mono_string_from_utf16_checked (data, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_from_utf16_checked:
* \param data the UTF-16 string (LPWSTR) to convert
* \param error set on error
* Converts a NULL-terminated UTF-16 string (LPWSTR) to a \c MonoString.
* \returns a \c MonoString. On failure sets \p error and returns NULL.
*/
MonoString *
mono_string_from_utf16_checked (const gunichar2 *data, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
if (!data)
return NULL;
return mono_string_new_utf16_checked (data, g_utf16_len (data), error);
}
/**
* mono_string_from_utf32:
* \param data the UTF-32 string (LPWSTR) to convert
* Converts a UTF-32 (UCS-4) string to a \c MonoString.
* \returns a \c MonoString.
*/
MonoString *
mono_string_from_utf32 (/*const*/ mono_unichar4 *data)
{
ERROR_DECL (error);
MonoString *result = mono_string_from_utf32_checked (data, error);
mono_error_cleanup (error);
return result;
}
/**
* mono_string_from_utf32_checked:
* \param data the UTF-32 string (LPWSTR) to convert
* \param error set on error
* Converts a UTF-32 (UCS-4) string to a \c MonoString.
* \returns a \c MonoString. On failure returns NULL and sets \p error.
*/
MonoString *
mono_string_from_utf32_checked (const mono_unichar4 *data, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
error_init (error);
MonoString* result = NULL;
mono_unichar2 *utf16_output = NULL;
GError *gerror = NULL;
glong items_written;
int len = 0;
if (!data)
return NULL;
while (data [len]) len++;
utf16_output = g_ucs4_to_utf16 (data, len, NULL, &items_written, &gerror);
if (gerror)
g_error_free (gerror);
result = mono_string_from_utf16_checked (utf16_output, error);
g_free (utf16_output);
return result;
}
static char *
mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
char *r;
char *mp_s;
int len;
r = mono_string_to_utf8_checked_internal (s, error);
if (!is_ok (error))
return NULL;
if (!mp && !image)
return r;
len = strlen (r) + 1;
if (mp)
mp_s = (char *)mono_mempool_alloc (mp, len);
else
mp_s = (char *)mono_image_alloc (image, len);
memcpy (mp_s, r, len);
g_free (r);
return mp_s;
}
/**
* mono_string_to_utf8_image:
* \param s a \c System.String
* Same as \c mono_string_to_utf8, but allocate the string from the image mempool.
*/
char *
mono_string_to_utf8_image (MonoImage *image, MonoStringHandle s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_string_to_utf8_internal (NULL, image, MONO_HANDLE_RAW (s), error); /* FIXME pin the string */
}
/**
* mono_string_to_utf8_mp:
* \param s a \c System.String
* Same as \c mono_string_to_utf8, but allocate the string from a mempool.
*/
char *
mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
return mono_string_to_utf8_internal (mp, NULL, s, error);
}
static MonoRuntimeExceptionHandlingCallbacks eh_callbacks;
void
mono_install_eh_callbacks (MonoRuntimeExceptionHandlingCallbacks *cbs)
{
eh_callbacks = *cbs;
}
MonoRuntimeExceptionHandlingCallbacks *
mono_get_eh_callbacks (void)
{
return &eh_callbacks;
}
void
mono_raise_exception_internal (MonoException *ex)
{
/* raise_exception doesn't return, so the transition to GC Unsafe is unbalanced */
MONO_STACKDATA (stackdata);
mono_threads_enter_gc_unsafe_region_unbalanced_with_info (mono_thread_info_current (), &stackdata);
mono_raise_exception_deprecated (ex);
}
/**
* mono_raise_exception:
* \param ex exception object
* Signal the runtime that the exception \p ex has been raised in unmanaged code.
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_raise_exception (MonoException *ex)
{
MONO_EXTERNAL_ONLY_VOID (mono_raise_exception_internal (ex));
}
/*
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_raise_exception_deprecated (MonoException *ex)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_raise_exception (ex);
}
/**
* mono_reraise_exception:
* \param ex exception object
* Signal the runtime that the exception \p ex has been raised in unmanaged code.
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_reraise_exception (MonoException *ex)
{
mono_reraise_exception_deprecated (ex);
}
/*
* DEPRECATED. DO NOT ADD NEW CALLERS FOR THIS FUNCTION.
*/
void
mono_reraise_exception_deprecated (MonoException *ex)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_reraise_exception (ex);
}
/*
* CTX must point to managed code.
*/
void
mono_raise_exception_with_context (MonoException *ex, MonoContext *ctx)
{
MONO_REQ_GC_UNSAFE_MODE;
eh_callbacks.mono_raise_exception_with_ctx (ex, ctx);
}
/*
* Returns the MonoMethod to call to Capture the ExecutionContext.
*/
MonoMethod*
mono_get_context_capture_method (void)
{
/* older corlib revisions won't have the class (nor the method) */
MonoClass *execution_context = mono_class_try_get_execution_context_class ();
if (!execution_context)
return NULL;
MONO_STATIC_POINTER_INIT (MonoMethod, method)
ERROR_DECL (error);
mono_class_init_internal (execution_context);
method = mono_class_get_method_from_name_checked (execution_context, "Capture", 0, 0, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, method)
return method;
}
/**
* prepare_to_string_method:
* @obj: The object
* @target: Set to @obj or unboxed value if a valuetype
*
* Returns: the ToString override for @obj. If @obj is a valuetype, @target is unboxed otherwise it's @obj.
*/
static MonoMethod *
prepare_to_string_method (MonoObject *obj, void **target)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoMethod *method;
g_assert (target);
g_assert (obj);
*target = obj;
MONO_STATIC_POINTER_INIT (MonoMethod, to_string)
ERROR_DECL (error);
to_string = mono_class_get_method_from_name_checked (mono_get_object_class (), "ToString", 0, METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_PUBLIC, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, to_string)
method = mono_object_get_virtual_method_internal (obj, to_string);
// Unbox value type if needed
if (m_class_is_valuetype (mono_method_get_class (method))) {
*target = mono_object_unbox_internal (obj);
}
return method;
}
/**
* mono_object_to_string:
* \param obj The object
* \param exc Any exception thrown by \c ToString. May be NULL.
* \returns the result of calling \c ToString on an object.
*/
MonoString *
mono_object_to_string (MonoObject *obj, MonoObject **exc)
{
ERROR_DECL (error);
MonoString *s = NULL;
void *target;
MonoMethod *method = prepare_to_string_method (obj, &target);
if (exc) {
s = (MonoString *) mono_runtime_try_invoke (method, target, NULL, exc, error);
if (*exc == NULL && !is_ok (error))
*exc = (MonoObject*) mono_error_convert_to_exception (error);
else
mono_error_cleanup (error);
} else {
s = (MonoString *) mono_runtime_invoke_checked (method, target, NULL, error);
mono_error_raise_exception_deprecated (error); /* OK to throw, external only without a good alternative */
}
return s;
}
/**
* mono_object_try_to_string:
* \param obj The object
* \param exc Any exception thrown by \c ToString(). Must not be NULL.
* \param error Set if method cannot be invoked.
* \returns the result of calling \c ToString() on an object. If the
* method cannot be invoked sets \p error, if it raises an exception sets \p exc,
* and returns NULL.
*/
MonoString *
mono_object_try_to_string (MonoObject *obj, MonoObject **exc, MonoError *error)
{
g_assert (exc);
error_init (error);
void *target;
MonoMethod *method = prepare_to_string_method (obj, &target);
return (MonoString*) mono_runtime_try_invoke (method, target, NULL, exc, error);
}
static char *
get_native_backtrace (MonoException *exc_raw)
{
HANDLE_FUNCTION_ENTER ();
MONO_HANDLE_DCL(MonoException, exc);
char * const trace = mono_exception_handle_get_native_backtrace (exc);
HANDLE_FUNCTION_RETURN_VAL (trace);
}
/**
* mono_print_unhandled_exception:
* \param exc The exception
* Prints the unhandled exception.
*/
void
mono_print_unhandled_exception_internal (MonoObject *exc)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoString * str;
char *message = (char*)"";
gboolean free_message = FALSE;
ERROR_DECL (error);
if (exc == (MonoObject*)mono_object_domain (exc)->out_of_memory_ex) {
message = g_strdup ("OutOfMemoryException");
free_message = TRUE;
} else if (exc == (MonoObject*)mono_object_domain (exc)->stack_overflow_ex) {
message = g_strdup ("StackOverflowException"); //if we OVF, we can't expect to have stack space to JIT Exception::ToString.
free_message = TRUE;
} else {
if (((MonoException*)exc)->native_trace_ips) {
message = get_native_backtrace ((MonoException*)exc);
free_message = TRUE;
} else {
MonoObject *other_exc = NULL;
str = mono_object_try_to_string (exc, &other_exc, error);
if (other_exc == NULL && !is_ok (error))
other_exc = (MonoObject*)mono_error_convert_to_exception (error);
else
mono_error_cleanup (error);
if (other_exc) {
char *original_backtrace = mono_exception_get_managed_backtrace ((MonoException*)exc);
char *nested_backtrace = mono_exception_get_managed_backtrace ((MonoException*)other_exc);
message = g_strdup_printf ("Nested exception detected.\nOriginal Exception: %s\nNested exception:%s\n",
original_backtrace, nested_backtrace);
g_free (original_backtrace);
g_free (nested_backtrace);
free_message = TRUE;
} else if (str) {
message = mono_string_to_utf8_checked_internal (str, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
message = (char *) "";
} else {
free_message = TRUE;
}
}
}
}
/*
* g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
* exc->vtable->klass->name, message);
*/
g_printerr ("\nUnhandled Exception:\n%s\n", message);
if (free_message)
g_free (message);
}
void
mono_print_unhandled_exception (MonoObject *exc)
{
MONO_EXTERNAL_ONLY_VOID (mono_print_unhandled_exception_internal (exc));
}
/**
* mono_delegate_ctor:
* \param this pointer to an uninitialized delegate object
* \param target target object
* \param addr pointer to native code
* \param method method
* \param error set on error.
* Initialize a delegate and sets a specific method, not the one
* associated with \p addr. This is useful when sharing generic code.
* In that case \p addr will most probably not be associated with the
* correct instantiation of the method.
* If \method is NULL, it is looked up using \addr in the JIT info tables.
*/
void
mono_delegate_ctor (MonoObjectHandle this_obj, MonoObjectHandle target, gpointer addr, MonoMethod *method, MonoError *error)
{
MONO_REQ_GC_UNSAFE_MODE;
MonoDelegateHandle delegate = MONO_HANDLE_CAST (MonoDelegate, this_obj);
UnlockedIncrement (&mono_stats.delegate_creations);
MonoClass *klass = mono_handle_class (this_obj);
g_assert (mono_class_has_parent (klass, mono_defaults.multicastdelegate_class));
/* Done by the EE */
callbacks.init_delegate (delegate, target, addr, method, error);
}
/**
* mono_create_ftnptr:
*
* Given a function address, create a function descriptor for it.
* This is only needed on some platforms.
*/
gpointer
mono_create_ftnptr (gpointer addr)
{
return callbacks.create_ftnptr (addr);
}
/*
* mono_get_addr_from_ftnptr:
*
* Given a pointer to a function descriptor, return the function address.
* This is only needed on some platforms.
*/
gpointer
mono_get_addr_from_ftnptr (gpointer descr)
{
return callbacks.get_addr_from_ftnptr (descr);
}
/**
* mono_string_chars:
* \param s a \c MonoString
* \returns a pointer to the UTF-16 characters stored in the \c MonoString
*/
mono_unichar2*
mono_string_chars (MonoString *s)
{
MONO_EXTERNAL_ONLY (mono_unichar2*, mono_string_chars_internal (s));
}
/**
* mono_string_length:
* \param s MonoString
* \returns the length in characters of the string
*/
int
mono_string_length (MonoString *s)
{
MONO_EXTERNAL_ONLY (int, mono_string_length_internal (s));
}
/**
* mono_array_length:
* \param array a \c MonoArray*
* \returns the total number of elements in the array. This works for
* both vectors and multidimensional arrays.
*/
uintptr_t
mono_array_length (MonoArray *array)
{
MONO_EXTERNAL_ONLY (uintptr_t, mono_array_length_internal (array));
}
#ifdef ENABLE_CHECKED_BUILD_GC
/**
* mono_string_handle_length:
* \param s \c MonoString
* \returns the length in characters of the string
*/
int
mono_string_handle_length (MonoStringHandle s)
{
MONO_REQ_GC_UNSAFE_MODE;
return MONO_HANDLE_GETVAL (s, length);
}
#endif
/**
* mono_array_addr_with_size:
* \param array a \c MonoArray*
* \param size size of the array elements
* \param idx index into the array
* Use this function to obtain the address for the \p idx item on the
* \p array containing elements of size \p size.
*
* This method performs no bounds checking or type checking.
* \returns the address of the \p idx element in the array.
*/
char*
mono_array_addr_with_size (MonoArray *array, int size, uintptr_t idx)
{
MONO_EXTERNAL_ONLY (char*, mono_array_addr_with_size_internal (array, size, idx));
}
MonoArray *
mono_glist_to_array (GList *list, MonoClass *eclass, MonoError *error)
{
MonoArray *res;
int len, i;
error_init (error);
if (!list)
return NULL;
len = g_list_length (list);
res = mono_array_new_checked (eclass, len, error);
return_val_if_nok (error, NULL);
for (i = 0; list; list = list->next, i++)
mono_array_set_internal (res, gpointer, i, list->data);
return res;
}
/**
* mono_class_value_size:
* \param klass a class
*
* This function is used for value types, and return the
* space and the alignment to store that kind of value object.
*
* \returns the size of a value of kind \p klass
*/
gint32
mono_class_value_size (MonoClass *klass, guint32 *align)
{
gint32 size;
/* fixme: check disable, because we still have external revereces to
* mscorlib and Dummy Objects
*/
/*g_assert (klass->valuetype);*/
/* this call inits klass if its not inited already */
size = mono_class_instance_size (klass);
if (m_class_has_failure (klass)) {
if (align)
*align = 1;
return 0;
}
size = size - MONO_ABI_SIZEOF (MonoObject);
g_assert (size >= 0);
if (align)
*align = m_class_get_min_align (klass);
return size;
}
/*
* mono_vtype_get_field_addr:
*
* Return the address of the FIELD in the valuetype VTYPE.
*/
gpointer
mono_vtype_get_field_addr (gpointer vtype, MonoClassField *field)
{
return ((char*)vtype) + field->offset - MONO_ABI_SIZEOF (MonoObject);
}
static GString *
quote_escape_and_append_string (char *src_str, GString *target_str)
{
#ifdef HOST_WIN32
char quote_char = '\"';
char escape_chars[] = "\"\\";
#else
char quote_char = '\'';
char escape_chars[] = "\'\\";
#endif
gboolean need_quote = FALSE;
gboolean need_escape = FALSE;
for (char *pos = src_str; *pos; ++pos) {
if (isspace (*pos))
need_quote = TRUE;
if (strchr (escape_chars, *pos))
need_escape = TRUE;
}
if (need_quote)
target_str = g_string_append_c (target_str, quote_char);
if (need_escape) {
for (char *pos = src_str; *pos; ++pos) {
if (strchr (escape_chars, *pos))
target_str = g_string_append_c (target_str, '\\');
target_str = g_string_append_c (target_str, *pos);
}
} else {
target_str = g_string_append (target_str, src_str);
}
if (need_quote)
target_str = g_string_append_c (target_str, quote_char);
return target_str;
}
static GString *
format_cmd_line (int argc, char **argv, gboolean add_host)
{
size_t total_size = 0;
char *host_path = NULL;
GString *cmd_line = NULL;
if (add_host) {
#if !defined(HOST_WIN32) && defined(HAVE_GETPID)
host_path = mono_w32process_get_path (getpid ());
#elif defined(HOST_WIN32)
gunichar2 *host_path_ucs2 = NULL;
guint32 host_path_ucs2_len = 0;
if (mono_get_module_filename (NULL, &host_path_ucs2, &host_path_ucs2_len)) {
host_path = g_utf16_to_utf8 (host_path_ucs2, -1, NULL, NULL, NULL);
g_free (host_path_ucs2);
}
#endif
}
if (host_path)
// quote + string + quote
total_size += strlen (host_path) + 2;
for (int i = 0; i < argc; ++i) {
if (argv [i]) {
if (total_size > 0) {
// add space
total_size++;
}
// quote + string + quote
total_size += strlen (argv [i]) + 2;
}
}
// String will grow if needed, so not over allocating
// to handle case of escaped characters in arguments, if
// that happens string will automatically grow.
cmd_line = g_string_sized_new (total_size + 1);
if (cmd_line) {
if (host_path)
cmd_line = quote_escape_and_append_string (host_path, cmd_line);
for (int i = 0; i < argc; ++i) {
if (argv [i]) {
if (cmd_line->len > 0) {
// add space
cmd_line = g_string_append_c (cmd_line, ' ');
}
cmd_line = quote_escape_and_append_string (argv [i], cmd_line);
}
}
}
g_free (host_path);
return cmd_line;
}
char *
mono_runtime_get_cmd_line (int argc, char **argv)
{
MONO_REQ_GC_NEUTRAL_MODE;
GString *cmd_line = format_cmd_line (num_main_args, main_args, FALSE);
return cmd_line ? g_string_free (cmd_line, FALSE) : NULL;
}
char *
mono_runtime_get_managed_cmd_line (void)
{
MONO_REQ_GC_NEUTRAL_MODE;
GString *cmd_line = format_cmd_line (num_main_args, main_args, TRUE);
return cmd_line ? g_string_free (cmd_line, FALSE) : NULL;
}
#if NEVER_DEFINED
/*
* The following section is purely to declare prototypes and
* document the API, as these C files are processed by our
* tool
*/
/**
* mono_array_set:
* \param array array to alter
* \param element_type A C type name, this macro will use the sizeof(type) to determine the element size
* \param index index into the array
* \param value value to set
* Value Type version: This sets the \p index's element of the \p array
* with elements of size sizeof(type) to the provided \p value.
*
* This macro does not attempt to perform type checking or bounds checking
* and it doesn't execute any write barriers.
*
* Use this to set value types in a \c MonoArray. This shouldn't be used if
* the copied value types contain references. Use \c mono_gc_wbarrier_value_copy
* instead when also copying references.
*/
void mono_array_set(MonoArray *array, Type element_type, uintptr_t index, Value value)
{
}
/**
* mono_array_setref:
* \param array array to alter
* \param index index into the array
* \param value value to set
* Reference Type version. This sets the \p index's element of the
* \p array with elements of size sizeof(type) to the provided \p value.
*
* This macro does not attempt to perform type checking or bounds checking.
*
* Use this to reference types in a \c MonoArray.
*/
void mono_array_setref(MonoArray *array, uintptr_t index, MonoObject *object)
{
}
/**
* mono_array_get:
* \param array array on which to operate on
* \param element_type C element type (example: \c MonoString*, \c int, \c MonoObject*)
* \param index index into the array
*
* Use this macro to retrieve the \p index element of an \p array and
* extract the value assuming that the elements of the array match
* the provided type value.
*
* This method can be used with both arrays holding value types and
* reference types. For reference types, the \p type parameter should
* be a \c MonoObject* or any subclass of it, like \c MonoString*.
*
* This macro does not attempt to perform type checking or bounds checking.
*
* \returns The element at the \p index position in the \p array.
*/
Type mono_array_get_internal (MonoArray *array, Type element_type, uintptr_t index)
{
}
#endif
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/mini/aot-compiler.c | /**
* \file
* mono Ahead of Time compiler
*
* Author:
* Dietmar Maurer ([email protected])
* Zoltan Varga ([email protected])
* Johan Lorensson ([email protected])
*
* (C) 2002 Ximian, Inc.
* Copyright 2003-2011 Novell, Inc
* 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 <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#ifndef HOST_WIN32
#include <sys/time.h>
#else
#include <winsock2.h>
#include <windows.h>
#endif
#include <errno.h>
#include <sys/stat.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-rand.h>
#include <mono/utils/json.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/profiler/aot.h>
#include <mono/utils/w32api.h>
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "seq-points.h"
#include "image-writer.h"
#include "dwarfwriter.h"
#include "mini-gc.h"
#include "mini-llvm.h"
#include "mini-runtime.h"
#include "interp/interp.h"
static MonoMethod*
try_get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_class_get_method_from_name_checked (klass, method_name, param_count, flags, error);
mono_error_assert_ok (error);
return result;
}
// FIXME Consolidate the multiple functions named get_method_nofail.
static MonoMethod*
get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
{
MonoMethod *result = try_get_method_nofail (klass, method_name, param_count, flags);
g_assertf (result, "Expected to find method %s in klass %s", method_name, m_class_get_name (klass));
return result;
}
#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
// Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
// targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
#if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
#define TARGET_X86_64_WIN32_MSVC
#endif
#if defined(TARGET_X86_64_WIN32_MSVC)
#define TARGET_WIN32_MSVC
#endif
// Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
// works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
// compiling for AMD64 (Windows x64 platforms).
#if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
#define EMIT_WIN32_UNWIND_INFO
#endif
#if defined(TARGET_ANDROID) || defined(__linux__)
#define RODATA_REL_SECT ".data.rel.ro"
#else
#define RODATA_REL_SECT ".text"
#endif
#if defined(__linux__)
#define RODATA_SECT ".rodata"
#elif defined(TARGET_MACH)
#define RODATA_SECT ".section __TEXT, __const"
#elif defined(TARGET_WIN32_MSVC)
#define RODATA_SECT ".rdata"
#else
#define RODATA_SECT ".text"
#endif
#define TV_DECLARE(name) gint64 name
#define TV_GETTIME(tv) tv = mono_100ns_ticks ()
#define TV_ELAPSED(start,end) (((end) - (start)) / 10)
#define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
typedef struct {
char *name;
MonoImage *image;
} ImageProfileData;
typedef struct ClassProfileData ClassProfileData;
typedef struct {
int argc;
ClassProfileData **argv;
MonoGenericInst *inst;
} GInstProfileData;
struct ClassProfileData {
ImageProfileData *image;
char *ns, *name;
GInstProfileData *inst;
MonoClass *klass;
};
typedef struct {
ClassProfileData *klass;
int id;
char *name;
int param_count;
char *signature;
GInstProfileData *inst;
MonoMethod *method;
} MethodProfileData;
typedef struct {
GHashTable *images, *classes, *ginsts, *methods;
} ProfileData;
/* predefined values for static readonly fields without needed to run the .cctor */
typedef struct _ReadOnlyValue ReadOnlyValue;
struct _ReadOnlyValue {
ReadOnlyValue *next;
char *name;
int type; /* to be used later for typechecking to prevent user errors */
union {
guint8 i1;
guint16 i2;
guint32 i4;
guint64 i8;
gpointer ptr;
} value;
};
static ReadOnlyValue *readonly_values;
typedef struct MonoAotOptions {
char *outfile;
char *llvm_outfile;
char *data_outfile;
GList *profile_files;
gboolean save_temps;
gboolean write_symbols;
gboolean metadata_only;
gboolean bind_to_runtime_version;
MonoAotMode mode;
gboolean interp;
gboolean no_dlsym;
gboolean static_link;
gboolean asm_only;
gboolean asm_writer;
gboolean nodebug;
gboolean dwarf_debug;
gboolean soft_debug;
gboolean log_generics;
gboolean log_instances;
gboolean gen_msym_dir;
char *gen_msym_dir_path;
gboolean direct_pinvoke;
gboolean direct_icalls;
gboolean direct_extern_calls;
gboolean no_direct_calls;
gboolean use_trampolines_page;
gboolean no_instances;
// We are collecting inflated methods and emitting non-inflated
gboolean dedup;
// The name of the assembly for which the AOT module is going to have all deduped methods moved to.
// When set, we are emitting inflated methods only
char *dedup_include;
gboolean gnu_asm;
gboolean try_llvm;
gboolean llvm;
gboolean llvm_only;
int nthreads;
int ntrampolines;
int nrgctx_trampolines;
int nimt_trampolines;
int ngsharedvt_arg_trampolines;
int nftnptr_arg_trampolines;
int nrgctx_fetch_trampolines;
int nunbox_arbitrary_trampolines;
gboolean print_skipped_methods;
gboolean stats;
gboolean verbose;
gboolean deterministic;
gboolean allow_errors;
char *tool_prefix;
char *ld_flags;
char *ld_name;
char *mtriple;
char *llvm_path;
char *temp_path;
char *instances_logfile_path;
char *logfile;
char *llvm_opts;
char *llvm_llc;
char *llvm_cpu_attr;
gboolean use_current_cpu;
gboolean dump_json;
gboolean profile_only;
gboolean no_opt;
char *clangxx;
char *depfile;
} MonoAotOptions;
typedef enum {
METHOD_CAT_NORMAL,
METHOD_CAT_GSHAREDVT,
METHOD_CAT_INST,
METHOD_CAT_WRAPPER,
METHOD_CAT_NUM
} MethodCategory;
typedef struct MonoAotStats {
int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
gint64 code_size, method_info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size, blob_size;
int methods_without_got_slots, direct_calls, all_calls, llvm_count;
int got_slots, offsets_size;
int method_categories [METHOD_CAT_NUM];
int got_slot_types [MONO_PATCH_INFO_NUM];
int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
int jit_time, gen_time, link_time;
int method_ref_count, method_ref_size;
int class_ref_count, class_ref_size;
int ginst_count, ginst_size;
} MonoAotStats;
typedef struct GotInfo {
GHashTable *patch_to_got_offset;
GHashTable **patch_to_got_offset_by_type;
GPtrArray *got_patches;
} GotInfo;
#ifdef EMIT_WIN32_UNWIND_INFO
typedef struct _UnwindInfoSectionCacheItem {
char *xdata_section_label;
PUNWIND_INFO unwind_info;
gboolean xdata_section_emitted;
} UnwindInfoSectionCacheItem;
#endif
typedef struct MonoAotCompile {
MonoImage *image;
GPtrArray *methods;
GHashTable *method_indexes;
GHashTable *method_depth;
MonoCompile **cfgs;
int cfgs_size;
GHashTable **patch_to_plt_entry;
GHashTable *plt_offset_to_entry;
//GHashTable *patch_to_got_offset;
//GHashTable **patch_to_got_offset_by_type;
//GPtrArray *got_patches;
GotInfo got_info, llvm_got_info;
GHashTable *image_hash;
GHashTable *method_to_cfg;
GHashTable *token_info_hash;
GHashTable *method_to_pinvoke_import;
GHashTable *method_to_external_icall_symbol_name;
GPtrArray *extra_methods;
GPtrArray *image_table;
GPtrArray *globals;
GPtrArray *method_order;
GHashTable *dedup_stats;
GHashTable *dedup_cache;
gboolean dedup_cache_changed;
GHashTable *export_names;
/* Maps MonoClass* -> blob offset */
GHashTable *klass_blob_hash;
/* Maps MonoMethod* -> blob offset */
GHashTable *method_blob_hash;
/* Maps MonoGenericInst* -> blob offset */
GHashTable *ginst_blob_hash;
GHashTable *gsharedvt_in_signatures;
GHashTable *gsharedvt_out_signatures;
guint32 *plt_got_info_offsets;
guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, plt_got_info_offset_base, nshared_got_entries;
/* Number of GOT entries reserved for trampolines */
guint32 num_trampoline_got_entries;
guint32 tramp_page_size;
guint32 table_offsets [MONO_AOT_TABLE_NUM];
guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
MonoAotOptions aot_opts;
guint32 nmethods;
int call_table_entry_size;
guint32 nextra_methods;
guint32 jit_opts;
guint32 simd_opts;
MonoMemPool *mempool;
MonoAotStats stats;
int method_index;
char *static_linking_symbol;
mono_mutex_t mutex;
gboolean gas_line_numbers;
/* Whenever to emit an object file directly from llc */
gboolean llvm_owriter;
gboolean llvm_owriter_supported;
MonoImageWriter *w;
MonoDwarfWriter *dwarf;
FILE *fp;
char *tmpbasename;
char *tmpfname;
char *temp_dir_to_delete;
char *llvm_sfile;
char *llvm_ofile;
GSList *cie_program;
GHashTable *unwind_info_offsets;
GPtrArray *unwind_ops;
guint32 unwind_info_offset;
char *global_prefix;
char *got_symbol;
char *llvm_got_symbol;
char *plt_symbol;
char *llvm_eh_frame_symbol;
GHashTable *method_label_hash;
const char *temp_prefix;
const char *user_symbol_prefix;
const char *llvm_label_prefix;
const char *inst_directive;
int align_pad_value;
guint32 label_generator;
gboolean llvm;
gboolean has_jitted_code;
gboolean is_full_aot;
gboolean dedup_collect_only;
MonoAotFileFlags flags;
MonoDynamicStream blob;
gboolean blob_closed;
GHashTable *typespec_classes;
GString *llc_args;
GString *as_args;
char *assembly_name_sym;
GHashTable *plt_entry_debug_sym_cache;
gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
GHashTable *ginst_hash;
GHashTable *dwarf_ln_filenames;
gboolean global_symbols;
int objc_selector_index, objc_selector_index_2;
GPtrArray *objc_selectors;
GHashTable *objc_selector_to_index;
GList *profile_data;
GHashTable *profile_methods;
GHashTable *blob_hash;
#ifdef EMIT_WIN32_UNWIND_INFO
GList *unwind_info_section_cache;
#endif
FILE *logfile;
FILE *instances_logfile;
FILE *data_outfile;
int datafile_offset;
int gc_name_offset;
// In this mode, we are emitting dedupable methods that we encounter
gboolean dedup_emit_mode;
} MonoAotCompile;
typedef struct {
int plt_offset;
char *symbol, *llvm_symbol, *debug_sym;
MonoJumpInfo *ji;
gboolean jit_used, llvm_used;
} MonoPltEntry;
#define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
#define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
/* This points to the current acfg in LLVM mode */
static MonoAotCompile *llvm_acfg;
static MonoAotCompile *current_acfg;
/* Cache of decoded method external icall symbol names. */
/* Owned by acfg, but kept in this static as well since it is */
/* accessed by code paths not having access to acfg. */
static GHashTable *method_to_external_icall_symbol_name;
// 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 PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
#include "patch-info.h"
#undef PATCH_INFO
} opstr = {
#define PATCH_INFO(a,b) b,
#include "patch-info.h"
#undef PATCH_INFO
};
static const gint16 opidx [] = {
#define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
#include "patch-info.h"
#undef PATCH_INFO
};
static G_GNUC_UNUSED const char*
get_patch_name (int info)
{
return (const char*)&opstr + opidx [info];
}
static int
emit_aot_image (MonoAotCompile *acfg);
static void
mono_flush_method_cache (MonoAotCompile *acfg);
static void
mono_read_method_cache (MonoAotCompile *acfg);
static guint32
get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
static char*
get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
static void
add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
static void
add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
static void
encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf);
static gboolean
ignore_cfg (MonoCompile *cfg)
{
return !cfg || cfg->skip;
}
static void
aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
{
FILE *output;
va_list args;
if (acfg->logfile)
output = acfg->logfile;
else
output = stdout;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
}
static void
aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
{
FILE *output;
va_list args;
if (acfg->logfile)
output = acfg->logfile;
else
output = stderr;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
}
static void
report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
{
FILE *output;
va_list args;
if (is_ok (error))
return;
if (acfg->logfile)
output = acfg->logfile;
else
output = stderr;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
mono_error_cleanup (error);
if (acfg->is_full_aot && !acfg->aot_opts.allow_errors && fatal) {
fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
exit (1);
}
}
/* Wrappers around the image writer functions */
#define MAX_SYMBOL_SIZE 256
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static const char *
mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
{
gsize needed_size = length;
g_assert (NULL != symbol);
g_assert (NULL != mangled_symbol);
g_assert (0 != length);
if (symbol && '_' != symbol [0]) {
needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
} else {
needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
}
g_assert (0 <= needed_size && needed_size < length);
return mangled_symbol;
}
static char *
mangle_symbol_alloc (const char * symbol)
{
g_assert (NULL != symbol);
if (symbol && '_' != symbol [0]) {
return g_strdup_printf ("_%s", symbol);
}
else {
return g_strdup_printf ("%s", symbol);
}
}
#endif
static void
emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
{
mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
}
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static void
emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
{
const char * mangled_symbol_name = name;
char * mangled_symbol_name_alloc = NULL;
if (TRUE == func) {
mangled_symbol_name_alloc = mangle_symbol_alloc (name);
mangled_symbol_name = mangled_symbol_name_alloc;
}
if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
}
mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
if (NULL != mangled_symbol_name_alloc) {
g_free (mangled_symbol_name_alloc);
}
}
#else
static void
emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
{
mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
}
#endif
static void
emit_label (MonoAotCompile *acfg, const char *name)
{
mono_img_writer_emit_label (acfg->w, name);
}
static void
emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
{
mono_img_writer_emit_bytes (acfg->w, buf, size);
}
static void
emit_string (MonoAotCompile *acfg, const char *value)
{
mono_img_writer_emit_string (acfg->w, value);
}
static void
emit_line (MonoAotCompile *acfg)
{
mono_img_writer_emit_line (acfg->w);
}
static void
emit_alignment (MonoAotCompile *acfg, int size)
{
mono_img_writer_emit_alignment (acfg->w, size);
}
static void
emit_alignment_code (MonoAotCompile *acfg, int size)
{
if (acfg->align_pad_value)
mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
else
mono_img_writer_emit_alignment (acfg->w, size);
}
static void
emit_padding (MonoAotCompile *acfg, int size)
{
int i;
guint8 buf [16];
if (acfg->align_pad_value) {
for (i = 0; i < 16; ++i)
buf [i] = acfg->align_pad_value;
} else {
memset (buf, 0, sizeof (buf));
}
for (i = 0; i < size; i += 16) {
if (size - i < 16)
emit_bytes (acfg, buf, size - i);
else
emit_bytes (acfg, buf, 16);
}
}
static void
emit_pointer (MonoAotCompile *acfg, const char *target)
{
mono_img_writer_emit_pointer (acfg->w, target);
}
static void
emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
{
if (prefix [0] != '\0') {
char *s = g_strdup_printf ("%s%s", prefix, target);
mono_img_writer_emit_pointer (acfg->w, s);
g_free (s);
} else {
mono_img_writer_emit_pointer (acfg->w, target);
}
}
static void
emit_int16 (MonoAotCompile *acfg, int value)
{
mono_img_writer_emit_int16 (acfg->w, value);
}
static void
emit_int32 (MonoAotCompile *acfg, int value)
{
mono_img_writer_emit_int32 (acfg->w, value);
}
static void
emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
{
mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
}
static void
emit_zero_bytes (MonoAotCompile *acfg, int num)
{
mono_img_writer_emit_zero_bytes (acfg->w, num);
}
static void
emit_byte (MonoAotCompile *acfg, guint8 val)
{
mono_img_writer_emit_byte (acfg->w, val);
}
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static G_GNUC_UNUSED void
emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
{
const char * mangled_symbol_name = name;
char * mangled_symbol_name_alloc = NULL;
mangled_symbol_name_alloc = mangle_symbol_alloc (name);
mangled_symbol_name = mangled_symbol_name_alloc;
if (0 != g_strcasecmp (name, mangled_symbol_name)) {
mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
}
mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
if (NULL != mangled_symbol_name_alloc) {
g_free (mangled_symbol_name_alloc);
}
}
#else
static G_GNUC_UNUSED void
emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
{
mono_img_writer_emit_global (acfg->w, name, func);
}
#endif
#ifdef TARGET_WIN32_MSVC
static gboolean
link_shared_library (MonoAotCompile *acfg)
{
return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
}
#endif
static gboolean
add_to_global_symbol_table (MonoAotCompile *acfg)
{
#ifdef TARGET_WIN32_MSVC
return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
#else
return acfg->aot_opts.no_dlsym;
#endif
}
static void
emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
{
if (add_to_global_symbol_table (acfg))
g_ptr_array_add (acfg->globals, g_strdup (name));
if (acfg->aot_opts.no_dlsym) {
mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
} else {
emit_global_inner (acfg, name, func);
}
}
static void
emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
{
mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
}
/* Emit a symbol which is referenced by the MonoAotFileInfo structure */
static void
emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
{
char symbol [MAX_SYMBOL_SIZE];
if (acfg->llvm) {
emit_label (acfg, name);
/* LLVM generated code references this */
int n = snprintf (symbol, MAX_SYMBOL_SIZE, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
if (n >= MAX_SYMBOL_SIZE)
symbol[MAX_SYMBOL_SIZE - 1] = 0;
emit_label (acfg, symbol);
#ifndef TARGET_WIN32_MSVC
emit_global_inner (acfg, symbol, FALSE);
#else
emit_global_inner (acfg, symbol, func);
#endif
} else {
emit_label (acfg, name);
}
}
static void
emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
{
if (acfg->llvm) {
mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
return;
}
mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
#ifdef TARGET_MACH
/* On apple, all symbols need to be aligned to avoid warnings from ld */
emit_alignment (acfg, 4);
#endif
mono_img_writer_emit_label (acfg->w, name);
mono_img_writer_emit_string (acfg->w, value);
}
static G_GNUC_UNUSED void
emit_uleb128 (MonoAotCompile *acfg, guint32 value)
{
do {
guint8 b = value & 0x7f;
value >>= 7;
if (value != 0) /* more bytes to come */
b |= 0x80;
emit_byte (acfg, b);
} while (value);
}
static G_GNUC_UNUSED void
emit_sleb128 (MonoAotCompile *acfg, gint64 value)
{
gboolean more = 1;
gboolean negative = (value < 0);
guint32 size = 64;
guint8 byte;
while (more) {
byte = value & 0x7f;
value >>= 7;
/* the following is unnecessary if the
* implementation of >>= uses an arithmetic rather
* than logical shift for a signed left operand
*/
if (negative)
/* sign extend */
value |= - ((gint64)1 <<(size - 7));
/* sign bit of byte is second high order bit (0x40) */
if ((value == 0 && !(byte & 0x40)) ||
(value == -1 && (byte & 0x40)))
more = 0;
else
byte |= 0x80;
emit_byte (acfg, byte);
}
}
static G_GNUC_UNUSED void
encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
do {
guint8 b = value & 0x7f;
value >>= 7;
if (value != 0) /* more bytes to come */
b |= 0x80;
*p ++ = b;
} while (value);
*endbuf = p;
}
static G_GNUC_UNUSED void
encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
{
gboolean more = 1;
gboolean negative = (value < 0);
guint32 size = 32;
guint8 byte;
guint8 *p = buf;
while (more) {
byte = value & 0x7f;
value >>= 7;
/* the following is unnecessary if the
* implementation of >>= uses an arithmetic rather
* than logical shift for a signed left operand
*/
if (negative)
/* sign extend */
value |= - (1 <<(size - 7));
/* sign bit of byte is second high order bit (0x40) */
if ((value == 0 && !(byte & 0x40)) ||
(value == -1 && (byte & 0x40)))
more = 0;
else
byte |= 0x80;
*p ++= byte;
}
*endbuf = p;
}
static void
encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
{
// FIXME: Big-endian
buf [0] = (val >> 0) & 0xff;
buf [1] = (val >> 8) & 0xff;
buf [2] = (val >> 16) & 0xff;
buf [3] = (val >> 24) & 0xff;
*endbuf = buf + 4;
}
static void
encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
{
buf [0] = (val >> 0) & 0xff;
buf [1] = (val >> 8) & 0xff;
*endbuf = buf + 2;
}
static void
encode_string (const char *s, guint8 *buf, guint8 **endbuf)
{
int len = strlen (s);
memcpy (buf, s, len + 1);
*endbuf = buf + len + 1;
}
static void
emit_unset_mode (MonoAotCompile *acfg)
{
mono_img_writer_emit_unset_mode (acfg->w);
}
static G_GNUC_UNUSED void
emit_set_thumb_mode (MonoAotCompile *acfg)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, ".code 16\n");
}
static G_GNUC_UNUSED void
emit_set_arm_mode (MonoAotCompile *acfg)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, ".code 32\n");
}
static void
emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
{
#ifdef TARGET_ARM64
int i;
g_assert (size % 4 == 0);
emit_unset_mode (acfg);
for (i = 0; i < size; i += 4)
fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
#else
emit_bytes (acfg, buf, size);
#endif
}
/* ARCHITECTURE SPECIFIC CODE */
#if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
#define EMIT_DWARF_INFO 1
#endif
#ifdef TARGET_WIN32_MSVC
#undef EMIT_DWARF_INFO
#define EMIT_WIN32_CODEVIEW_INFO
#endif
#ifdef EMIT_WIN32_UNWIND_INFO
static UnwindInfoSectionCacheItem *
get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
static void
free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
static void
emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
static void
emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
#endif
static void
arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
{
#ifdef EMIT_WIN32_UNWIND_INFO
free_unwind_info_section_cache_win32 (acfg);
#endif
}
static void
arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
#ifdef EMIT_WIN32_UNWIND_INFO
gboolean own_unwind_ops = FALSE;
if (!unwind_ops) {
unwind_ops = mono_unwind_get_cie_program ();
own_unwind_ops = TRUE;
}
emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
if (own_unwind_ops)
mono_free_unwind_info (unwind_ops);
#endif
}
#if defined(TARGET_ARM)
#define AOT_FUNC_ALIGNMENT 4
#else
#define AOT_FUNC_ALIGNMENT 16
#endif
#if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
#define PPC_LD_OP "ld"
#define PPC_LDX_OP "ldx"
#else
#define PPC_LD_OP "lwz"
#define PPC_LDX_OP "lwzx"
#endif
#ifdef TARGET_X86_64_WIN32_MSVC
#define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
#elif TARGET_AMD64
#define AOT_TARGET_STR "AMD64"
#endif
#ifdef TARGET_ARM
#ifdef TARGET_MACH
#define AOT_TARGET_STR "ARM (MACH)"
#else
#define AOT_TARGET_STR "ARM (!MACH)"
#endif
#endif
#ifdef TARGET_ARM64
#ifdef TARGET_MACH
#define AOT_TARGET_STR "ARM64 (MACH)"
#else
#define AOT_TARGET_STR "ARM64 (!MACH)"
#endif
#endif
#ifdef TARGET_POWERPC64
#ifdef MONO_ARCH_ILP32
#define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
#else
#define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
#endif
#else
#ifdef TARGET_POWERPC
#ifdef MONO_ARCH_ILP32
#define AOT_TARGET_STR "POWERPC (mono ilp32)"
#else
#define AOT_TARGET_STR "POWERPC (!mono ilp32)"
#endif
#endif
#endif
#ifdef TARGET_RISCV32
#define AOT_TARGET_STR "RISCV32"
#endif
#ifdef TARGET_RISCV64
#define AOT_TARGET_STR "RISCV64"
#endif
#ifdef TARGET_X86
#ifdef TARGET_WIN32
#define AOT_TARGET_STR "X86 (WIN32)"
#else
#define AOT_TARGET_STR "X86"
#endif
#endif
#ifndef AOT_TARGET_STR
#define AOT_TARGET_STR ""
#endif
static void
arch_init (MonoAotCompile *acfg)
{
acfg->llc_args = g_string_new ("");
acfg->as_args = g_string_new ("");
acfg->llvm_owriter_supported = TRUE;
/*
* The prefix LLVM likes to put in front of symbol names on darwin.
* The mach-os specs require this for globals, but LLVM puts them in front of all
* symbols. We need to handle this, since we need to refer to LLVM generated
* symbols.
*/
acfg->llvm_label_prefix = "";
acfg->user_symbol_prefix = "";
#if TARGET_X86 || TARGET_AMD64
const gboolean has_custom_args = !!acfg->aot_opts.llvm_llc || acfg->aot_opts.use_current_cpu;
#endif
#if defined(TARGET_X86)
g_string_append_printf (acfg->llc_args, " -march=x86 %s", has_custom_args ? "" : "-mcpu=generic");
#endif
#if defined(TARGET_AMD64)
g_string_append_printf (acfg->llc_args, " -march=x86-64 %s", has_custom_args ? "" : "-mcpu=generic");
/* NOP */
acfg->align_pad_value = 0x90;
#ifdef MONO_ARCH_CODE_EXEC_ONLY
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY);
#endif
#endif
g_string_append (acfg->llc_args, " -enable-implicit-null-checks -disable-fault-maps");
if (mono_use_fast_math) {
// same parameters are passed to opt and LLVM JIT
g_string_append (acfg->llc_args, " -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math");
}
#ifdef TARGET_ARM
if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
g_string_append (acfg->llc_args, "-mattr=+v6");
} else {
if (!acfg->aot_opts.mtriple) {
g_string_append (acfg->llc_args, " -march=arm");
} else {
/* arch will be defined via mtriple, e.g. armv7s-ios or thumb. */
if (strstr (acfg->aot_opts.mtriple, "ios")) {
g_string_append (acfg->llc_args, " -mattr=+v7");
g_string_append (acfg->llc_args, " -exception-model=dwarf -frame-pointer=all");
}
}
#if defined(ARM_FPU_VFP_HARD)
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
g_string_append (acfg->as_args, " -mfpu=vfp3");
#elif defined(ARM_FPU_VFP)
#if defined(TARGET_ARM)
// +d16 triggers a warning on arm
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon");
#else
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
#endif
g_string_append (acfg->as_args, " -mfpu=vfp3");
#else
g_string_append (acfg->llc_args, " -mattr=+soft-float");
#endif
}
if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
acfg->thumb_mixed = TRUE;
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#endif
#ifdef TARGET_ARM64
g_string_append (acfg->llc_args, " -march=aarch64");
acfg->inst_directive = ".inst";
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#endif
#ifdef TARGET_MACH
acfg->user_symbol_prefix = "_";
acfg->llvm_label_prefix = "_";
acfg->inst_directive = ".word";
acfg->need_no_dead_strip = TRUE;
acfg->aot_opts.gnu_asm = TRUE;
#endif
#if defined(__linux__) && !defined(TARGET_ARM)
acfg->need_pt_gnu_stack = TRUE;
#endif
#ifdef TARGET_RISCV
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#ifdef TARGET_RISCV64
g_string_append (acfg->as_args, " -march=rv64i ");
#ifdef RISCV_FPABI_DOUBLE
g_string_append (acfg->as_args, " -mabi=lp64d");
#else
g_string_append (acfg->as_args, " -mabi=lp64");
#endif
#else
g_string_append (acfg->as_args, " -march=rv32i ");
#ifdef RISCV_FPABI_DOUBLE
g_string_append (acfg->as_args, " -mabi=ilp32d ");
#else
g_string_append (acfg->as_args, " -mabi=ilp32 ");
#endif
#endif
#endif
#ifdef MONOTOUCH
acfg->global_symbols = TRUE;
#endif
#ifdef TARGET_ANDROID
acfg->llvm_owriter_supported = FALSE;
#endif
}
#ifdef TARGET_ARM64
/* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
/* Must emit 12 bytes of instructions */
static void
arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
{
int offset;
g_assert (acfg->fp);
emit_unset_mode (acfg);
/* r16==ip0 */
offset = (int)(got_slot * TARGET_SIZEOF_VOID_P);
#ifdef TARGET_MACH
/* clang's integrated assembler */
fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
#ifdef MONO_ARCH_ILP32
fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF+%d\n", acfg->got_symbol, offset & 0xfff);
fprintf (acfg->fp, "ldr w%d, [x16, #%d]\n", dreg, 0);
#else
fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
#endif
#else
/* Linux GAS */
fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
#endif
}
static void
arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
{
int reg;
g_assert (acfg->fp);
emit_unset_mode (acfg);
/* ldr rt, target */
reg = arm_get_ldr_lit_reg (code);
fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
*code_size = 12;
}
static void
arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
g_assert (acfg->fp);
emit_unset_mode (acfg);
if (ji && ji->relocation == MONO_R_ARM64_B) {
fprintf (acfg->fp, "b %s\n", target);
} else {
if (ji)
g_assert (ji->relocation == MONO_R_ARM64_BL);
fprintf (acfg->fp, "bl %s\n", target);
}
*call_size = 4;
}
static void
arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
{
int reg;
/* ldr rt, target */
reg = arm_get_ldr_lit_reg (code);
arm64_emit_load_got_slot (acfg, reg, got_slot);
*code_size = 12;
}
static void
arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
{
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
/* Used by mono_aot_get_plt_info_offset () */
fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
}
static void
arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
{
guint8 buf [256];
guint8 *code;
int imm;
/* The common code */
code = buf;
imm = pagesize;
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Trampoline argument */
arm_ldrp (code, arg_reg, ARMREG_IP0, 0);
/* Address */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* Emit it */
emit_code_bytes (acfg, buf, code - buf);
*size = code - buf;
}
static void
arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
{
guint8 buf [256];
guint8 *code;
int i, count;
count = (pagesize - common_tramp_size) / specific_tramp_size;
for (i = 0; i < count; ++i) {
code = buf;
arm_adrx (code, ARMREG_IP0, code);
/* Branch to the generic code */
arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
#ifndef MONO_ARCH_ILP32
/* This has to be 2 pointers long */
arm_nop (code);
arm_nop (code);
#endif
g_assert (code - buf == specific_tramp_size);
emit_code_bytes (acfg, buf, code - buf);
}
}
static void
arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
{
guint8 buf [128];
guint8 *code;
guint8 *labels [16];
int common_tramp_size;
int specific_tramp_size = 2 * TARGET_SIZEOF_VOID_P;
int imm, pagesize;
char symbol [128];
if (!acfg->aot_opts.use_trampolines_page)
return;
#ifdef TARGET_MACH
/* Have to match the target pagesize */
pagesize = 16384;
#else
pagesize = mono_pagesize ();
#endif
acfg->tramp_page_size = pagesize;
/* The specific trampolines */
sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* The common code */
arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The rgctx trampolines */
/* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* The common code */
arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The gsharedvt arg trampolines */
/* These are the same as the specific trampolines */
sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* Unbox arbitrary trampolines */
sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm = pagesize;
/* Unbox this arg */
arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Address */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* Emit it */
emit_code_bytes (acfg, buf, code - buf);
common_tramp_size = code - buf;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The IMT trampolines */
sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm = pagesize;
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Trampoline argument */
arm_ldrp (code, ARMREG_IP1, ARMREG_IP0, 0);
/* Same as arch_emit_imt_trampoline () */
labels [0] = code;
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, 0);
arm_cmpp (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
labels [1] = code;
arm_bcc (code, ARMCOND_EQ, 0);
/* End-of-loop check */
labels [2] = code;
arm_cbzx (code, ARMREG_IP0, 0);
/* Loop footer */
arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * TARGET_SIZEOF_VOID_P);
arm_b (code, labels [0]);
/* Match */
mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
/* Load vtable slot addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
/* Load vtable slot */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* No match */
mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
/* Load fail addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
emit_code_bytes (acfg, buf, code - buf);
common_tramp_size = code - buf;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
}
static void
arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Load argument from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
/* Load generic trampoline address from first GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
static void
arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
fprintf (acfg->fp, "b %s\n", call_target);
}
static void
arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
/* Load argument from first GOT slot */
arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
/* Load generic trampoline address from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
static void
arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
guint8 buf [128];
guint8 *code, *labels [16];
/* Load parameter from GOT slot into ip1 */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
code = buf;
labels [0] = code;
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, 0);
arm_cmpp (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
labels [1] = code;
arm_bcc (code, ARMCOND_EQ, 0);
/* End-of-loop check */
labels [2] = code;
arm_cbzx (code, ARMREG_IP0, 0);
/* Loop footer */
arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
arm_b (code, labels [0]);
/* Match */
mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
/* Load vtable slot addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
/* Load vtable slot */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* No match */
mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
/* Load fail addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
emit_code_bytes (acfg, buf, code - buf);
*tramp_size = code - buf + (3 * 4);
}
static void
arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Similar to the specific trampolines, but the address is in the second slot */
/* Load argument from first GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
/* Load generic trampoline address from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_direct_call:
*
* Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
* calling code.
*/
static void
arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
/* Need to make sure this is exactly 5 bytes long */
emit_unset_mode (acfg);
fprintf (acfg->fp, "call %s\n", target);
*call_size = 5;
#elif defined(TARGET_ARM)
emit_unset_mode (acfg);
if (thumb)
fprintf (acfg->fp, "blx %s\n", target);
else
fprintf (acfg->fp, "bl %s\n", target);
*call_size = 4;
#elif defined(TARGET_ARM64)
arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
#elif defined(TARGET_POWERPC)
emit_unset_mode (acfg);
fprintf (acfg->fp, "bl %s\n", target);
*call_size = 4;
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_label_address (MonoAotCompile *acfg, const char *target, gboolean external_call, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
#if defined(TARGET_ARM) && defined(TARGET_ANDROID)
/* binutils ld does not support branch islands on arm32 */
if (!thumb) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "ldr pc,=%s\n", target);
fprintf (acfg->fp, ".ltorg\n");
*call_size = 8;
} else
#endif
arch_emit_direct_call (acfg, target, external_call, thumb, ji, call_size);
}
#endif
/*
* PPC32 design:
* - we use an approach similar to the x86 abi: reserve a register (r30) to hold
* the GOT pointer.
* - The full-aot trampolines need access to the GOT of mscorlib, so we store
* in in the 2. slot of every GOT, and require every method to place the GOT
* address in r30, even when it doesn't access the GOT otherwise. This way,
* the trampolines can compute the mscorlib GOT address by loading 4(r30).
*/
/*
* PPC64 design:
* PPC64 uses function descriptors which greatly complicate all code, since
* these are used very inconsistently in the runtime. Some functions like
* mono_compile_method () return ftn descriptors, while others like the
* trampoline creation functions do not.
* We assume that all GOT slots contain function descriptors, and create
* descriptors in aot-runtime.c when needed.
* The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
* from function descriptors, we could do the same, but it would require
* rewriting all the ppc/aot code to handle function descriptors properly.
* So instead, we use the same approach as on PPC32.
* This is a horrible mess, but fixing it would probably lead to an even bigger
* one.
*/
/*
* X86 design:
* - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
*/
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_got_offset:
*
* The memory pointed to by CODE should hold native code for computing the GOT
* address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
* between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
*/
static void
arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
{
#if defined(TARGET_POWERPC64)
emit_unset_mode (acfg);
/*
* The ppc32 code doesn't seem to work on ppc64, the assembler complains about
* unsupported relocations. So we store the got address into the .Lgot_addr
* symbol which is in the text segment, compute its address, and load it.
*/
fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
fprintf (acfg->fp, "add 30, 30, 0\n");
fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
acfg->label_generator ++;
*code_size = 16;
#elif defined(TARGET_POWERPC)
emit_unset_mode (acfg);
fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
acfg->label_generator ++;
*code_size = 8;
#else
guint32 offset = mono_arch_get_patch_offset (code);
emit_bytes (acfg, code, offset);
emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
*code_size = offset + 4;
#endif
}
/*
* arch_emit_got_access:
*
* The memory pointed to by CODE should hold native code for loading a GOT
* slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
* GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
*/
static void
arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
{
#ifdef TARGET_AMD64
/* mov reg, got+offset(%rip) */
if (acfg->llvm) {
/* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
int dreg;
int rex_r;
/* Decode reg, see amd64_mov_reg_membase () */
rex_r = code [0] & AMD64_REX_R;
g_assert (code [0] == 0x49 + rex_r);
g_assert (code [1] == 0x8b);
dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
*code_size = 7;
} else {
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
*code_size = mono_arch_get_patch_offset (code) + 4;
}
#elif defined(TARGET_X86)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
*code_size = mono_arch_get_patch_offset (code) + 4;
#elif defined(TARGET_ARM)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
*code_size = mono_arch_get_patch_offset (code) + 4;
#elif defined(TARGET_ARM64)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
arm64_emit_got_access (acfg, code, got_slot, code_size);
#elif defined(TARGET_POWERPC)
{
guint8 buf [32];
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
code = buf;
ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
*code_size = code - buf;
}
#else
g_assert_not_reached ();
#endif
}
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_objc_selector_ref:
*
* Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
*/
static void
arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
{
#if defined(TARGET_ARM)
char symbol1 [MAX_SYMBOL_SIZE];
char symbol2 [MAX_SYMBOL_SIZE];
int lindex = acfg->objc_selector_index_2 ++;
/* Emit ldr.imm/b */
emit_bytes (acfg, code, 8);
sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
emit_label (acfg, symbol1);
mono_img_writer_emit_unset_mode (acfg->w);
fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
*code_size = 12;
#elif defined(TARGET_ARM64)
arm64_emit_objc_selector_ref (acfg, code, index, code_size);
#else
g_assert_not_reached ();
#endif
}
#endif
#ifdef MONO_ARCH_CODE_EXEC_ONLY
#if defined(TARGET_AMD64)
/* Keep in sync with tramp-amd64.c, aot_arch_get_plt_entry_index. */
#define PLT_ENTRY_OFFSET_REG AMD64_RAX
#endif
#endif
/*
* arch_emit_plt_entry:
*
* Emit code for the PLT entry.
* The plt entry should look like this on architectures where code is read/execute:
* <indirect jump to GOT_SYMBOL + OFFSET>
* <INFO_OFFSET embedded into the instruction stream>
* The plt entry should look like this on architectures where code is execute only:
* mov RAX, PLT entry offset
* <indirect jump to GOT_SYMBOL + OFFSET>
*/
static void
arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, guint32 plt_index, int offset, int info_offset)
{
#if defined(TARGET_X86)
/* jmp *<offset>(%ebx) */
emit_byte (acfg, 0xff);
emit_byte (acfg, 0xa3);
emit_int32 (acfg, offset);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
#elif defined(TARGET_AMD64)
#ifdef MONO_ARCH_CODE_EXEC_ONLY
guint8 buf [16];
guint8 *code = buf;
/* Emit smallest possible imm size 1, 2 or 4 bytes based on total number of PLT entries. */
if (acfg->plt_offset <= (guint32)0xFF) {
amd64_emit_rex(code, sizeof (guint8), 0, 0, PLT_ENTRY_OFFSET_REG);
*(code)++ = (unsigned char)0xb0 + (PLT_ENTRY_OFFSET_REG & 0x7);
x86_imm_emit8 (code, (guint8)(plt_index));
} else if (acfg->plt_offset <= (guint32)0xFFFF) {
x86_prefix(code, X86_OPERAND_PREFIX);
amd64_emit_rex(code, sizeof (guint16), 0, 0, PLT_ENTRY_OFFSET_REG);
*(code)++ = (unsigned char)0xb8 + (PLT_ENTRY_OFFSET_REG & 0x7);
x86_imm_emit16 (code, (guint16)(plt_index));
} else {
amd64_mov_reg_imm_size (code, PLT_ENTRY_OFFSET_REG, plt_index, sizeof(plt_index));
}
emit_bytes (acfg, buf, code - buf);
acfg->stats.plt_size += code - buf;
emit_unset_mode (acfg);
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
acfg->stats.plt_size += 6;
#else
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
acfg->stats.plt_size += 10;
#endif
#elif defined(TARGET_ARM)
guint8 buf [256];
guint8 *code;
code = buf;
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
#elif defined(TARGET_ARM64)
arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
#elif defined(TARGET_POWERPC)
/* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
emit_unset_mode (acfg);
fprintf (acfg->fp, "lis 11, %d@h\n", offset);
fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
fprintf (acfg->fp, "add 11, 11, 30\n");
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
fprintf (acfg->fp, "bctr\n");
emit_int32 (acfg, info_offset);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_llvm_plt_entry:
*
* Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
* This is only needed on arm to handle thumb interop.
*/
static void
arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int plt_index, int offset, int info_offset)
{
#if defined(TARGET_ARM)
/* LLVM calls the PLT entries using bl, so these have to be thumb2 */
/* The caller already transitioned to thumb */
/* The code below should be 12 bytes long */
/* clang has trouble encoding these instructions, so emit the binary */
#if 0
fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
/* thumb can't encode ld pc, [pc, ip] */
fprintf (acfg->fp, "add ip, pc, ip\n");
fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
fprintf (acfg->fp, "bx ip\n");
#endif
emit_set_thumb_mode (acfg);
fprintf (acfg->fp, ".4byte 0xc008f8df\n");
fprintf (acfg->fp, ".2byte 0x44fc\n");
fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
fprintf (acfg->fp, ".2byte 0x4760\n");
emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
emit_int32 (acfg, info_offset);
emit_unset_mode (acfg);
emit_set_arm_mode (acfg);
#else
g_assert_not_reached ();
#endif
}
/* Save unwind_info in the module and emit the offset to the information at symbol */
static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
{
guint32 uw_offset, encoded_len;
guint8 *encoded;
emit_section_change (acfg, RODATA_SECT, 0);
emit_global (acfg, symbol, FALSE);
emit_label (acfg, symbol);
encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
g_free (encoded);
emit_int32 (acfg, uw_offset);
}
/*
* arch_emit_specific_trampoline_pages:
*
* Emits a page full of trampolines: each trampoline uses its own address to
* lookup both the generic trampoline code and the data argument.
* This page can be remapped in process multiple times so we can get an
* unlimited number of trampolines.
* Specifically this implementation uses the following trick: two memory pages
* are allocated, with the first containing the data and the second containing the trampolines.
* To reduce trampoline size, each trampoline jumps at the start of the page where a common
* implementation does all the lifting.
* Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
* on the arm 32 bit system.
*/
static void
arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
{
#if defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
int i;
int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
GSList *unwind_ops = NULL;
#define COMMON_TRAMP_SIZE 16
int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
int imm8, rot_amount;
char symbol [128];
if (!acfg->aot_opts.use_trampolines_page)
return;
acfg->tramp_page_size = pagesize;
sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* emit the generic code first, the trampoline address + 8 is in the lr register */
code = buf;
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_PUSH (code, 0x5fff);
ARM_BL (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the rgctx trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the values
* We again fit the generic trampiline in 16 bytes.
*/
sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/*
* gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
*/
sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the target addr.
* We again fit the generic trampoline in 16 bytes.
*/
sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the imt trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the values
*/
#define IMT_TRAMP_SIZE 72
sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
/* Need at least two free registers, plus a slot for storing the pc */
ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
/* The IMT method is in v5, r0 has the imt array address */
loop_start = code;
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
imt_found_check = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* End-of-loop check */
ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
loop_end_check = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* Loop footer */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
loop_branch_back = code;
ARM_B (code, 0);
arm_patch (loop_branch_back, loop_start);
/* Match */
arm_patch (imt_found_check, code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
/* Save it to the third stack slot */
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
/* Restore the registers and branch */
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* No match */
arm_patch (loop_end_check, code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
ARM_NOP (code);
/* Emit it */
g_assert (code - buf == IMT_TRAMP_SIZE);
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
/* Unwind info for specifc trampolines */
sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
/* We unwind to the original caller, from the stack, since lr is clobbered */
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for rgctx trampolines */
sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for gsharedvt trampolines */
sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for unbox arbitrary trampolines */
sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for imt trampolines */
sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
#elif defined(TARGET_ARM64)
arm64_emit_specific_trampoline_pages (acfg);
#endif
}
/*
* arch_emit_specific_trampoline:
*
* Emit code for a specific trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the generic trampoline address and the trampoline
* argument. TRAMP_SIZE is set to the size of the emitted trampoline.
*/
static void
arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/*
* The trampolines created here are variations of the specific
* trampolines created in mono_arch_create_specific_trampoline (). The
* differences are:
* - the generic trampoline address is taken from a got slot.
* - the offset of the got slot where the trampoline argument is stored
* is embedded in the instruction stream, and the generic trampoline
* can load the argument by loading the offset, adding it to the
* address of the trampoline to get the address of the got slot, and
* loading the argument from there.
* - all the trampolines should be of the same length.
*/
#if defined(TARGET_AMD64)
/* This should be exactly 8 bytes long */
*tramp_size = 8;
/* call *<offset>(%rip) */
if (acfg->llvm) {
emit_byte (acfg, '\x41');
emit_unset_mode (acfg);
fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
emit_zero_bytes (acfg, 1);
} else {
emit_byte (acfg, '\x41');
emit_byte (acfg, '\xff');
emit_byte (acfg, '\x15');
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
emit_zero_bytes (acfg, 1);
}
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* This should be exactly 20 bytes long */
*tramp_size = 20;
code = buf;
ARM_PUSH (code, 0x5fff);
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
/* Load the value from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
/* Branch to it */
ARM_BLX_REG (code, ARMREG_R1);
g_assert (code - buf == 16);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
/*
* Only one offset is needed, since the second one would be equal to the
* first one.
*/
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
//emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
#elif defined(TARGET_ARM64)
arm64_emit_specific_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code;
*tramp_size = 4;
code = buf;
/*
* PPC has no ip relative addressing, so we need to compute the address
* of the mscorlib got. That is slow and complex, so instead, we store it
* in the second got slot of every aot image. The caller already computed
* the address of its got and placed it into r30.
*/
emit_unset_mode (acfg);
/* Load mscorlib got address */
fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
/* Load generic trampoline address */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
/* Load trampoline argument */
/* On ppc, we pass it normally to the generic trampoline */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
/* Branch to generic trampoline */
fprintf (acfg->fp, "bctr\n");
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
*tramp_size = 10 * 4;
#else
*tramp_size = 9 * 4;
#endif
#elif defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
/* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Push trampoline argument */
x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
/* Load generic trampoline address */
x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to generic trampoline */
x86_jump_reg (code, X86_ECX);
emit_bytes (acfg, buf, code - buf);
*tramp_size = 17;
g_assert (code - buf == *tramp_size);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_unbox_trampoline:
*
* Emit code for the unbox trampoline for METHOD used in the full-aot case.
* CALL_TARGET is the symbol pointing to the native code of METHOD.
*
* See mono_aot_get_unbox_trampoline.
*/
static void
arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
{
#if defined(TARGET_AMD64)
guint8 buf [32];
guint8 *code;
int this_reg;
this_reg = mono_arch_get_this_arg_reg (NULL);
code = buf;
amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump <method> */
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "jmp %s\n", call_target);
} else {
emit_byte (acfg, '\xe9');
emit_symbol_diff (acfg, call_target, ".", -4);
}
#elif defined(TARGET_X86)
guint8 buf [32];
guint8 *code;
int this_pos = 4;
code = buf;
x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump <method> */
emit_byte (acfg, '\xe9');
emit_symbol_diff (acfg, call_target, ".", -4);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
if (acfg->thumb_mixed && cfg->compile_llvm) {
fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
fprintf (acfg->fp, "b %s\n", call_target);
fprintf (acfg->fp, ".arm\n");
fprintf (acfg->fp, ".align 2\n");
return;
}
code = buf;
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump to method */
if (acfg->thumb_mixed && cfg->compile_llvm)
fprintf (acfg->fp, "\n\tbx %s\n", call_target);
else
fprintf (acfg->fp, "\n\tb %s\n", call_target);
#elif defined(TARGET_ARM64)
arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
#elif defined(TARGET_POWERPC)
int this_pos = 3;
fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
fprintf (acfg->fp, "\n\tb %s\n", call_target);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_static_rgctx_trampoline:
*
* Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the rgctx argument, and the method to jump to.
* TRAMP_SIZE is set to the size of the emitted trampoline.
* These kinds of trampolines cannot be enumerated statically, since there could
* be one trampoline per method instantiation, so we emit the same code for all
* trampolines, and parameterize them using two GOT slots.
*/
static void
arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_AMD64)
/* This should be exactly 13 bytes long */
*tramp_size = 13;
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
} else {
/* mov <OFFSET>(%rip), %r10 */
emit_byte (acfg, '\x4d');
emit_byte (acfg, '\x8b');
emit_byte (acfg, '\x15');
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
/* jmp *<offset>(%rip) */
emit_byte (acfg, '\xff');
emit_byte (acfg, '\x25');
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
}
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* This should be exactly 24 bytes long */
*tramp_size = 24;
code = buf;
/* Load rgctx value */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
/* Load branch addr + branch */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
g_assert (code - buf == 16);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
#elif defined(TARGET_ARM64)
arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code;
*tramp_size = 4;
code = buf;
/*
* PPC has no ip relative addressing, so we need to compute the address
* of the mscorlib got. That is slow and complex, so instead, we store it
* in the second got slot of every aot image. The caller already computed
* the address of its got and placed it into r30.
*/
emit_unset_mode (acfg);
/* Load mscorlib got address */
fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
/* Load rgctx */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
/* Load target address */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
/* Branch to the target address */
fprintf (acfg->fp, "bctr\n");
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
*tramp_size = 11 * 4;
#else
*tramp_size = 9 * 4;
#endif
#elif defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to the target address */
x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
emit_bytes (acfg, buf, code - buf);
*tramp_size = 15;
g_assert (code - buf == *tramp_size);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_imt_trampoline:
*
* Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
* points to an array of pointer pairs. The pairs of the form [key, ptr], where
* key is the IMT key, and ptr holds the address of a memory location holding
* the address to branch to if the IMT arg matches the key. The array is
* terminated by a pair whose key is NULL, and whose ptr is the address of the
* fail_tramp.
* TRAMP_SIZE is set to the size of the emitted trampoline.
*/
static void
arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_AMD64)
guint8 *buf, *code;
guint8 *labels [16];
guint8 mov_buf[3];
guint8 *mov_buf_ptr = mov_buf;
const int kSizeOfMove = 7;
code = buf = (guint8 *)g_malloc (256);
/* FIXME: Optimize this, i.e. use binary search etc. */
/* Maybe move the body into a separate function (slower, but much smaller) */
/* MONO_ARCH_IMT_SCRATCH_REG is a free register */
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
}
labels [0] = code;
amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
labels [1] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Check key */
amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
labels [2] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Loop footer */
amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
amd64_jump_code (code, labels [0]);
/* Match */
mono_amd64_patch (labels [2], code);
amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
/* No match */
mono_amd64_patch (labels [1], code);
/* Load fail tramp */
amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
/* Check if there is a fail tramp */
amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
labels [3] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Jump to fail tramp */
amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
/* Fail */
mono_amd64_patch (labels [3], code);
x86_breakpoint (code);
if (!acfg->llvm) {
/* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
*(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
}
emit_bytes (acfg, buf, code - buf);
*tramp_size = code - buf + kSizeOfMove;
g_free (buf);
#elif defined(TARGET_X86)
guint8 *buf, *code;
guint8 *labels [16];
code = buf = g_malloc (256);
/* Allocate a temporary stack slot */
x86_push_reg (code, X86_EAX);
/* Save EAX */
x86_push_reg (code, X86_EAX);
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
labels [0] = code;
x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
labels [1] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Check key */
x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
labels [2] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Loop footer */
x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
x86_jump_code (code, labels [0]);
/* Match */
mono_x86_patch (labels [2], code);
x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
/* Save the target address to the temporary stack location */
x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
/* Restore EAX */
x86_pop_reg (code, X86_EAX);
/* Jump to the target address */
x86_ret (code);
/* No match */
mono_x86_patch (labels [1], code);
/* Load fail tramp */
x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
labels [3] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Jump to fail tramp */
x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
x86_pop_reg (code, X86_EAX);
x86_ret (code);
/* Fail */
mono_x86_patch (labels [3], code);
x86_breakpoint (code);
emit_bytes (acfg, buf, code - buf);
*tramp_size = code - buf;
g_free (buf);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code, *code2, *labels [16];
code = buf;
/* The IMT method is in v5 */
/* Need at least two free registers, plus a slot for storing the pc */
ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
labels [0] = code;
/* Load the parameter from the GOT */
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
labels [1] = code;
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
labels [2] = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* End-of-loop check */
ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
labels [3] = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* Loop footer */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
labels [4] = code;
ARM_B (code, 0);
arm_patch (labels [4], labels [1]);
/* Match */
arm_patch (labels [2], code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
/* Save it to the third stack slot */
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
/* Restore the registers and branch */
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* No match */
arm_patch (labels [3], code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* Fixup offset */
code2 = labels [0];
ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
*tramp_size = code - buf + 4;
#elif defined(TARGET_ARM64)
arm64_emit_imt_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code, *labels [16];
code = buf;
/* Load the mscorlib got address */
ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
/* Load the parameter from the GOT */
ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
/* Load and check key */
labels [1] = code;
ppc_ldptr (code, ppc_r0, 0, ppc_r12);
ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
labels [2] = code;
ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
/* End-of-loop check */
ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
labels [3] = code;
ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
/* Loop footer */
ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
labels [4] = code;
ppc_b (code, 0);
mono_ppc_patch (labels [4], labels [1]);
/* Match */
mono_ppc_patch (labels [2], code);
ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
/* r12 now contains the value of the vtable slot */
/* this is not a function descriptor on ppc64 */
ppc_ldptr (code, ppc_r12, 0, ppc_r12);
ppc_mtctr (code, ppc_r12);
ppc_bcctr (code, PPC_BR_ALWAYS, 0);
/* Fail */
mono_ppc_patch (labels [3], code);
/* FIXME: */
ppc_break (code);
*tramp_size = code - buf;
emit_bytes (acfg, buf, code - buf);
#else
g_assert_not_reached ();
#endif
}
#if defined (TARGET_AMD64)
static void
amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
{
g_assert (acfg->fp);
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
}
#endif
/*
* arch_emit_gsharedvt_arg_trampoline:
*
* Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the argument, and the code to jump to.
* TRAMP_SIZE is set to the size of the emitted trampoline.
* These kinds of trampolines cannot be enumerated statically, since there could
* be one trampoline per method instantiation, so we emit the same code for all
* trampolines, and parameterize them using two GOT slots.
*/
static void
arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to the target address */
x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
emit_bytes (acfg, buf, code - buf);
*tramp_size = 15;
g_assert (code - buf == *tramp_size);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
/* Similar to arch_emit_specific_trampoline () */
*tramp_size = 24;
code = buf;
ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
/* Load the arg value from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
/* Load the addr from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
/* Branch to it */
ARM_BX (code, ARMREG_R1);
g_assert (code - buf == 20);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
#elif defined(TARGET_ARM64)
arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
#elif defined (TARGET_AMD64)
amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
fprintf (acfg->fp, "jmp *%%r11\n");
*tramp_size = 0x11;
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
*tramp_size = 32;
code = buf;
/* Load target address and push it on stack */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
ARM_PUSH (code, 1 << ARMREG_IP);
/* Load argument in ARMREG_IP */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
/* Branch */
ARM_POP (code, 1 << ARMREG_PC);
g_assert (code - buf == 24);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_ARM64)
emit_unset_mode (acfg);
fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
fprintf (acfg->fp, "br x17\n");
*tramp_size = 5 * 4;
#elif defined (TARGET_AMD64)
guint8 buf [32];
guint8 *code;
int this_reg;
this_reg = mono_arch_get_this_arg_reg (NULL);
code = buf;
amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
fprintf (acfg->fp, "jmp *%%rax\n");
*tramp_size = 13;
#elif defined (TARGET_ARM)
guint8 buf [32];
guint8 *code, *label;
code = buf;
/* Unbox */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
label = code;
/* Calculate GOT slot */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
/* Load target addr into PC*/
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
g_assert (code - buf == 12);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
*tramp_size = 4 * 4;
#else
g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
#endif
}
/* END OF ARCH SPECIFIC CODE */
static guint32
mono_get_field_token (MonoClassField *field)
{
MonoClass *klass = m_field_get_parent (field);
int i;
int fcount = mono_class_get_field_count (klass);
MonoClassField *klass_fields = m_class_get_fields (klass);
for (i = 0; i < fcount; ++i) {
if (field == &klass_fields [i])
return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
}
g_assert_not_reached ();
return 0;
}
static void
encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
//printf ("ENCODE: %d 0x%x.\n", value, value);
/*
* Same encoding as the one used in the metadata, extended to handle values
* greater than 0x1fffffff.
*/
if ((value >= 0) && (value <= 127))
*p++ = value;
else if ((value >= 0) && (value <= 16383)) {
p [0] = 0x80 | (value >> 8);
p [1] = value & 0xff;
p += 2;
} else if ((value >= 0) && (value <= 0x1fffffff)) {
p [0] = (value >> 24) | 0xc0;
p [1] = (value >> 16) & 0xff;
p [2] = (value >> 8) & 0xff;
p [3] = value & 0xff;
p += 4;
}
else {
p [0] = 0xff;
p [1] = (value >> 24) & 0xff;
p [2] = (value >> 16) & 0xff;
p [3] = (value >> 8) & 0xff;
p [4] = value & 0xff;
p += 5;
}
if (endbuf)
*endbuf = p;
}
static void
stream_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = (char *)g_malloc (4096);
/* So offsets are > 0 */
sh->data [0] = 0;
sh->index ++;
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
}
static guint32
add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
return idx;
}
/*
* add_to_blob:
*
* Add data to the binary blob inside the aot image. Returns the offset inside the
* blob where the data was stored.
*/
static guint32
add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
{
g_assert (!acfg->blob_closed);
if (acfg->blob.alloc_size == 0)
stream_init (&acfg->blob);
acfg->stats.blob_size += data_len;
return add_stream_data (&acfg->blob, (char*)data, data_len);
}
typedef struct {
guint8 *data;
int len, align;
guint32 offset;
} BlobItem;
static guint
blob_item_hash (gconstpointer key)
{
BlobItem *item = (BlobItem*)key;
guint i, a;
for (i = a = 0; i < item->len; ++i)
a ^= (((guint)item->data [i]) << (i & 0xf));
return a;
}
static gboolean
blob_item_equal (gconstpointer a, gconstpointer b)
{
BlobItem *item1 = (BlobItem*)a;
BlobItem *item2 = (BlobItem*)b;
if (item1->len != item2->len || item1->align != item2->align)
return FALSE;
return memcmp (item1->data, item2->data, item1->len) == 0;
}
static void
blob_item_free (gpointer val)
{
BlobItem *item = (BlobItem*)val;
g_free (item->data);
g_free (item);
}
static guint32
add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
{
char buf [4] = {0};
guint32 count;
if (acfg->blob.alloc_size == 0)
stream_init (&acfg->blob);
count = acfg->blob.index % align;
BlobItem tmp;
tmp.data = (guint8*)data;
tmp.len = data_len;
tmp.align = align;
if (!acfg->blob_hash)
acfg->blob_hash = g_hash_table_new_full (blob_item_hash, blob_item_equal, NULL, blob_item_free);
BlobItem *cached = g_hash_table_lookup (acfg->blob_hash, &tmp);
if (cached)
return cached->offset;
/* we assume the stream data will be aligned */
if (count)
add_stream_data (&acfg->blob, buf, 4 - count);
guint32 offset = add_stream_data (&acfg->blob, (char*)data, data_len);
BlobItem *item = g_new0 (BlobItem, 1);
item->data = g_malloc (data_len);
memcpy (item->data, data, data_len);
item->len = data_len;
item->align = align;
item->offset = offset;
g_hash_table_insert (acfg->blob_hash, item, item);
return offset;
}
/* Emit a table of data into the aot image */
static void
emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
{
if (acfg->data_outfile) {
acfg->table_offsets [(int)table] = acfg->datafile_offset;
fwrite (data,1, size, acfg->data_outfile);
acfg->datafile_offset += size;
// align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
int align = 8 - size % 8;
acfg->datafile_offset += align;
guint8 align_buf [16];
memset (&align_buf, 0, sizeof (align_buf));
fwrite (align_buf, align, 1, acfg->data_outfile);
} else if (acfg->llvm) {
mono_llvm_emit_aot_data (symbol, data, size);
} else {
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
emit_bytes (acfg, data, size);
}
}
/*
* emit_offset_table:
*
* Emit a table of increasing offsets in a compact form using differential encoding.
* There is an index entry for each GROUP_SIZE number of entries. The greater the
* group size, the more compact the table becomes, but the slower it becomes to compute
* a given entry. Returns the size of the table.
*/
static guint32
emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
{
gint32 current_offset;
int i, buf_size, ngroups, index_entry_size;
guint8 *p, *buf;
guint8 *data_p, *data_buf;
guint32 *index_offsets;
ngroups = (noffsets + (group_size - 1)) / group_size;
index_offsets = g_new0 (guint32, ngroups);
buf_size = noffsets * 4;
p = buf = (guint8 *)g_malloc0 (buf_size);
current_offset = 0;
for (i = 0; i < noffsets; ++i) {
//printf ("D: %d -> %d\n", i, offsets [i]);
if ((i % group_size) == 0) {
index_offsets [i / group_size] = p - buf;
/* Emit the full value for these entries */
encode_value (offsets [i], p, &p);
} else {
/* The offsets are allowed to be non-increasing */
//g_assert (offsets [i] >= current_offset);
encode_value (offsets [i] - current_offset, p, &p);
}
current_offset = offsets [i];
}
data_buf = buf;
data_p = p;
if (ngroups && index_offsets [ngroups - 1] < 65000)
index_entry_size = 2;
else
index_entry_size = 4;
buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
p = buf = (guint8 *)g_malloc0 (buf_size);
/* Emit the header */
encode_int (noffsets, p, &p);
encode_int (group_size, p, &p);
encode_int (ngroups, p, &p);
encode_int (index_entry_size, p, &p);
/* Emit the index */
for (i = 0; i < ngroups; ++i) {
if (index_entry_size == 2)
encode_int16 (index_offsets [i], p, &p);
else
encode_int (index_offsets [i], p, &p);
}
/* Emit the data */
memcpy (p, data_buf, data_p - data_buf);
p += data_p - data_buf;
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, table, symbol, buf, p - buf);
g_free (buf);
g_free (data_buf);
return (int)(p - buf);
}
static guint32
get_image_index (MonoAotCompile *cfg, MonoImage *image)
{
guint32 index;
index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
if (index)
return index - 1;
else {
index = g_hash_table_size (cfg->image_hash);
g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
g_ptr_array_add (cfg->image_table, image);
return index;
}
}
static guint32
find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
{
int i;
int len = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
/* FIXME: Search referenced images as well */
if (!acfg->typespec_classes) {
acfg->typespec_classes = g_hash_table_new (NULL, NULL);
for (i = 0; i < len; i++) {
ERROR_DECL (error);
int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
continue;
}
g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
}
}
return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
}
static void
encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
static void
encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
static void
encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
static void
encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
static guint32
get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
static void
encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
/*
* The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
* information.
*/
if (mono_class_is_ginst (klass)) {
guint32 token;
g_assert (m_class_get_type_token (klass));
/* Find a typespec for a class if possible */
token = find_typespec_for_class (acfg, klass);
if (token) {
encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
encode_value (token, p, &p);
} else {
MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
static int count = 0;
guint8 *p1 = p;
encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
encode_klass_ref (acfg, gclass, p, &p);
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
count += p - p1;
}
} else if (m_class_get_type_token (klass)) {
int iindex = get_image_index (acfg, m_class_get_image (klass));
g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
if (iindex == 0) {
encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
} else {
encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
}
} else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
encode_value (par->gshared_constraint ? 1 : 0, p, &p);
if (par->gshared_constraint) {
MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
encode_type (acfg, par->gshared_constraint, p, &p);
encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
} else {
encode_value (m_class_get_byval_arg (klass)->type, p, &p);
encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
encode_value (container->is_anonymous ? 0 : 1, p, &p);
if (!container->is_anonymous) {
encode_value (container->is_method, p, &p);
if (container->is_method)
encode_method_ref (acfg, container->owner.method, p, &p);
else
encode_klass_ref (acfg, container->owner.klass, p, &p);
}
}
} else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
} else {
/* Array class */
g_assert (m_class_get_rank (klass) > 0);
encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
encode_value (m_class_get_rank (klass), p, &p);
encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
}
acfg->stats.class_ref_count++;
acfg->stats.class_ref_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
{
guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
guint8 *buf2, *p;
if (!offset) {
buf2 = (guint8 *)g_malloc (1024);
p = buf2;
encode_klass_ref_inner (acfg, klass, p, &p);
g_assert (p - buf2 < 1024);
offset = add_to_blob (acfg, buf2, p - buf2);
g_free (buf2);
g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
/*
* encode_klass_ref:
*
* Encode a reference to KLASS. We use our home-grown encoding instead of the
* standard metadata encoding.
*/
static void
encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
{
gboolean shared = FALSE;
/*
* The encoding of generic instances is large so emit them only once.
*/
if (mono_class_is_ginst (klass)) {
guint32 token;
g_assert (m_class_get_type_token (klass));
/* Find a typespec for a class if possible */
token = find_typespec_for_class (acfg, klass);
if (!token)
shared = TRUE;
} else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
shared = TRUE;
}
if (shared) {
guint8 *p;
guint32 offset = get_shared_klass_ref (acfg, klass);
p = buf;
encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
encode_value (offset, p, &p);
*endbuf = p;
return;
}
encode_klass_ref_inner (acfg, klass, buf, endbuf);
}
static void
encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
{
guint32 token = mono_get_field_token (field);
guint8 *p = buf;
encode_klass_ref (cfg, m_field_get_parent (field), p, &p);
g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
*endbuf = p;
}
static void
encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
int i;
encode_value (inst->type_argc, p, &p);
for (i = 0; i < inst->type_argc; ++i)
encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
acfg->stats.ginst_count++;
acfg->stats.ginst_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
{
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
if (!offset) {
guint8 *buf2, *p2;
int len;
len = 1024 + (ginst->type_argc * 32);
buf2 = (guint8 *)g_malloc (len);
p2 = buf2;
encode_ginst (acfg, ginst, p2, &p2);
g_assert (p2 - buf2 < len);
offset = add_to_blob (acfg, buf2, p2 - buf2);
g_free (buf2);
g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
static void
encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
MonoGenericInst *inst;
guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
g_assert (flags);
encode_value (flags, p, &p);
inst = context->class_inst;
if (inst) {
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
}
inst = context->method_inst;
if (inst) {
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
}
*endbuf = p;
}
static void
encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
if (t->has_cmods) {
int count = mono_type_custom_modifier_count (t);
*p = MONO_TYPE_CMOD_REQD;
++p;
encode_value (count, p, &p);
for (int i = 0; i < count; ++i) {
ERROR_DECL (error);
gboolean required;
MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
mono_error_assert_ok (error);
encode_value (required, p, &p);
encode_type (acfg, cmod_type, p, &p);
}
}
/* t->attrs can be ignored */
//g_assert (t->attrs == 0);
if (t->pinned) {
*p = MONO_TYPE_PINNED;
++p;
}
if (m_type_is_byref (t)) {
*p = MONO_TYPE_BYREF;
++p;
}
*p = t->type;
p ++;
switch (t->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:
encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
break;
case MONO_TYPE_SZARRAY:
encode_klass_ref (acfg, t->data.klass, p, &p);
break;
case MONO_TYPE_PTR:
encode_type (acfg, t->data.type, p, &p);
break;
case MONO_TYPE_FNPTR:
encode_signature (acfg, t->data.method, p, &p);
break;
case MONO_TYPE_GENERICINST: {
MonoClass *gclass = t->data.generic_class->container_class;
MonoGenericInst *inst = t->data.generic_class->context.class_inst;
encode_klass_ref (acfg, gclass, p, &p);
encode_ginst (acfg, inst, p, &p);
break;
}
case MONO_TYPE_ARRAY: {
MonoArrayType *array = t->data.array;
int i;
encode_klass_ref (acfg, array->eklass, p, &p);
encode_value (array->rank, p, &p);
encode_value (array->numsizes, p, &p);
for (i = 0; i < array->numsizes; ++i)
encode_value (array->sizes [i], p, &p);
encode_value (array->numlobounds, p, &p);
for (i = 0; i < array->numlobounds; ++i)
encode_value (array->lobounds [i], p, &p);
break;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
break;
default:
g_assert_not_reached ();
}
*endbuf = p;
}
static void
encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
guint32 flags = 0;
int i;
/* Similar to the metadata encoding */
if (sig->generic_param_count)
flags |= 0x10;
if (sig->hasthis)
flags |= 0x20;
if (sig->explicit_this)
flags |= 0x40;
if (sig->pinvoke)
flags |= 0x80;
flags |= (sig->call_convention & 0x0F);
*p = flags;
++p;
if (sig->generic_param_count)
encode_value (sig->generic_param_count, p, &p);
encode_value (sig->param_count, p, &p);
encode_type (acfg, sig->ret, p, &p);
for (i = 0; i < sig->param_count; ++i) {
if (sig->sentinelpos == i) {
*p = MONO_TYPE_SENTINEL;
++p;
}
encode_type (acfg, sig->params [i], p, &p);
}
*endbuf = p;
}
#define MAX_IMAGE_INDEX 250
static void
encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
{
guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
guint32 token = method->token;
MonoJumpInfoToken *ji;
guint8 *p = buf;
/*
* The encoding for most methods is as follows:
* - image index encoded as a leb128
* - token index encoded as a leb128
* Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
* types of method encodings.
*/
/* Mark methods which can't use aot trampolines because they need the further
* processing in mono_magic_trampoline () which requires a MonoMethod*.
*/
if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
if (method->wrapper_type) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
encode_value (method->wrapper_type, p, &p);
switch (method->wrapper_type) {
case MONO_WRAPPER_ALLOC: {
/* The GC name is saved once in MonoAotFileInfo */
g_assert (info->d.alloc.alloc_type != -1);
encode_value (info->d.alloc.alloc_type, p, &p);
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
g_assert (info);
break;
}
case MONO_WRAPPER_STELEMREF: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
encode_value (info->d.virtual_stelemref.kind, p, &p);
break;
}
case MONO_WRAPPER_OTHER: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
encode_klass_ref (acfg, method->klass, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
encode_signature (acfg, info->d.interp_in.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
encode_value (info->d.icall.jit_icall_id, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
encode_value (info->d.aot_init.subtype, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_LLVM_FUNC)
encode_value (info->d.llvm_func.subtype, p, &p);
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
encode_value (info->d.icall.jit_icall_id, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_INDIRECT) {
encode_klass_ref (acfg, info->d.native_func.klass, p, &p);
encode_signature (acfg, info->d.native_func.sig, p, &p);
} else {
g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m;
m = mono_marshal_method_from_wrapper (method);
g_assert (m);
g_assert (m != method);
encode_method_ref (acfg, m, p, &p);
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
encode_value (info->d.element_addr.rank, p, &p);
encode_value (info->d.element_addr.elem_size, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
encode_klass_ref (acfg, info->d.generic_array_helper.klass, p, &p);
encode_method_ref (acfg, info->d.generic_array_helper.method, p, &p);
int len = strlen (info->d.generic_array_helper.name);
guint32 idx = add_to_blob (acfg, (guint8*)info->d.generic_array_helper.name, len + 1);
encode_value (idx, p, &p);
} else {
g_assert_not_reached ();
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
g_assert (info);
encode_value (info->subtype, p, &p);
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
if (method->is_inflated) {
/* These wrappers are identified by their class */
encode_value (1, p, &p);
encode_klass_ref (acfg, method->klass, p, &p);
} else {
MonoMethodSignature *sig = mono_method_signature_internal (method);
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
encode_value (0, p, &p);
if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
encode_value (info ? info->subtype : 0, p, &p);
encode_signature (acfg, sig, p, &p);
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
g_assert (info);
encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
MonoClass *klass = info->d.native_to_managed.klass;
if (!klass) {
encode_value (0, p, &p);
} else {
encode_value (1, p, &p);
encode_klass_ref (acfg, klass, p, &p);
}
break;
}
default:
g_assert_not_reached ();
}
} else if (mono_method_signature_internal (method)->is_inflated) {
/*
* This is a generic method, find the original token which referenced it and
* encode that.
* Obtain the token from information recorded by the JIT.
*/
ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
if (ji) {
image_index = get_image_index (acfg, ji->image);
g_assert (image_index < MAX_IMAGE_INDEX);
token = ji->token;
encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (token, p, &p);
} else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
/* Already emitted as part of an rgctx fetch */
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
offset --;
encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
encode_value (offset, p, &p);
} else {
MonoMethod *declaring;
MonoGenericContext *context = mono_method_get_context (method);
g_assert (method->is_inflated);
declaring = ((MonoMethodInflated*)method)->declaring;
/*
* This might be a non-generic method of a generic instance, which
* doesn't have a token since the reference is generated by the JIT
* like Nullable:Box/Unbox, or by generic sharing.
*/
encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
/* Encode the klass */
encode_klass_ref (acfg, method->klass, p, &p);
/* Encode the method */
image_index = get_image_index (acfg, m_class_get_image (method->klass));
g_assert (image_index < MAX_IMAGE_INDEX);
g_assert (declaring->token);
token = declaring->token;
g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
encode_value (image_index, p, &p);
encode_value (mono_metadata_token_index (token), p, &p);
encode_generic_context (acfg, context, p, &p);
}
} else if (token == 0) {
/* This might be a method of a constructed type like int[,].Set */
/* Obtain the token from information recorded by the JIT */
ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
if (ji) {
image_index = get_image_index (acfg, ji->image);
g_assert (image_index < MAX_IMAGE_INDEX);
token = ji->token;
encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (token, p, &p);
} else {
/* Array methods */
g_assert (m_class_get_rank (method->klass));
/* Encode directly */
encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
encode_klass_ref (acfg, method->klass, p, &p);
if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
encode_value (0, p, &p);
else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
encode_value (1, p, &p);
else if (!strcmp (method->name, "Get"))
encode_value (2, p, &p);
else if (!strcmp (method->name, "Address"))
encode_value (3, p, &p);
else if (!strcmp (method->name, "Set"))
encode_value (4, p, &p);
else
g_assert_not_reached ();
}
} else {
g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
if (image_index >= MONO_AOT_METHODREF_MIN) {
encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (mono_metadata_token_index (token), p, &p);
} else {
encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
}
}
acfg->stats.method_ref_count++;
acfg->stats.method_ref_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
{
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
if (!offset) {
guint8 *buf2, *p2;
buf2 = (guint8 *)g_malloc (1024);
p2 = buf2;
encode_method_ref (acfg, method, p2, &p2);
g_assert (p2 - buf2 < 1024);
offset = add_to_blob (acfg, buf2, p2 - buf2);
g_free (buf2);
g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
static gint
compare_patches (gconstpointer a, gconstpointer b)
{
int i, j;
i = (*(MonoJumpInfo**)a)->ip.i;
j = (*(MonoJumpInfo**)b)->ip.i;
if (i < j)
return -1;
else
if (i > j)
return 1;
else
return 0;
}
static G_GNUC_UNUSED char*
patch_to_string (MonoJumpInfo *patch_info)
{
GString *str;
str = g_string_new ("");
g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
switch (patch_info->type) {
case MONO_PATCH_INFO_VTABLE:
mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
break;
default:
break;
}
g_string_append_printf (str, ")");
return g_string_free (str, FALSE);
}
/*
* is_plt_patch:
*
* Return whenever PATCH_INFO refers to a direct call, and thus requires a
* PLT entry.
*/
static gboolean
is_plt_patch (MonoJumpInfo *patch_info)
{
switch (patch_info->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return TRUE;
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
default:
return FALSE;
}
}
/*
* get_plt_symbol:
*
* Return the symbol identifying the plt entry PLT_OFFSET.
*/
static char*
get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
{
#ifdef TARGET_MACH
/*
* The Apple linker reorganizes object files, so it doesn't like branches to local
* labels, since those have no relocations.
*/
return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
#else
return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
#endif
}
/*
* get_plt_entry:
*
* Return a PLT entry which belongs to the method identified by PATCH_INFO.
*/
static MonoPltEntry*
get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
{
MonoPltEntry *res;
gboolean synchronized = FALSE;
static int synchronized_symbol_idx;
if (!is_plt_patch (patch_info))
return NULL;
if (!acfg->patch_to_plt_entry [patch_info->type])
acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
/*
* Allocate a separate PLT slot for each such patch, since some plt
* entries will refer to the method itself, and some will refer to the
* wrapper.
*/
res = NULL;
synchronized = TRUE;
}
if (!res) {
MonoJumpInfo *new_ji;
new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
res->plt_offset = acfg->plt_offset;
res->ji = new_ji;
res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
if (acfg->aot_opts.write_symbols)
res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
if (synchronized) {
/* Avoid duplicate symbols because we don't cache */
res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
if (res->debug_sym)
res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
synchronized_symbol_idx ++;
}
if (res->debug_sym)
res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
else
res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
/* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
char *tmp = res->llvm_symbol;
res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
g_free (tmp);
}
g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
//g_assert (mono_patch_info_equal (patch_info, new_ji));
//mono_print_ji (patch_info); printf ("\n");
//g_hash_table_print_stats (acfg->patch_to_plt_entry);
acfg->plt_offset ++;
}
return res;
}
static guint32
lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
{
guint32 got_offset;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
if (got_offset)
return got_offset - 1;
g_assert_not_reached ();
}
/**
* get_got_offset:
*
* Returns the offset of the GOT slot where the runtime object resulting from resolving
* JI could be found if it exists, otherwise allocates a new one.
*/
static guint32
get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
{
guint32 got_offset;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
if (got_offset)
return got_offset - 1;
if (llvm) {
got_offset = acfg->llvm_got_offset;
acfg->llvm_got_offset ++;
} else {
got_offset = acfg->got_offset;
acfg->got_offset ++;
}
acfg->stats.got_slots ++;
acfg->stats.got_slot_types [ji->type] ++;
g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
g_ptr_array_add (info->got_patches, ji);
return got_offset;
}
/* Add a method to the list of methods which need to be emitted */
static void
add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
{
g_assert (method);
if (!g_hash_table_lookup (acfg->method_indexes, method)) {
g_ptr_array_add (acfg->methods, method);
g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
acfg->nmethods = acfg->methods->len + 1;
while (acfg->nmethods >= acfg->cfgs_size) {
MonoCompile **new_cfgs;
int new_size;
new_size = acfg->cfgs_size ? acfg->cfgs_size * 2 : 128;
new_cfgs = g_new0 (MonoCompile*, new_size);
memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
g_free (acfg->cfgs);
acfg->cfgs = new_cfgs;
acfg->cfgs_size = new_size;
}
}
if (method->wrapper_type || extra) {
int token = mono_metadata_token_index (method->token) - 1;
if (token < 0)
acfg->nextra_methods++;
g_ptr_array_add (acfg->extra_methods, method);
}
}
static gboolean
prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
{
/* One instantiation with valuetypes is generated for each async method */
if (m_class_get_image (method->klass) == mono_defaults.corlib && (!strcmp (m_class_get_name (method->klass), "AsyncMethodBuilderCore") || !strcmp (m_class_get_name (method->klass), "AsyncVoidMethodBuilder")))
return TRUE;
else
return FALSE;
}
static guint32
get_method_index (MonoAotCompile *acfg, MonoMethod *method)
{
int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
g_assert (index);
return index - 1;
}
static int
add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
{
int index;
index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
if (index)
return index - 1;
index = acfg->method_index;
add_method_with_index (acfg, method, index, extra);
g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
acfg->method_index ++;
return index;
}
static int
add_method (MonoAotCompile *acfg, MonoMethod *method)
{
return add_method_full (acfg, method, FALSE, 0);
}
static void
mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
{
g_assert (acfg->dedup_stats);
char *name = mono_aot_get_mangled_method_name (method);
g_assert (name);
// For stats
char *stats_name = g_strdup (name);
g_assert (acfg->dedup_cache);
if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
// This AOTCompile owns this method
// We do this to decide whether to write it to disk
// during a dedup run (first phase, where we skip).
//
// If never changed, then maybe can avoid a recompile
// of the cache.
//
// Files not read in during last phase.
acfg->dedup_cache_changed = TRUE;
// owns name
g_hash_table_insert (acfg->dedup_cache, name, method);
} else {
// owns name
g_free (name);
}
guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
count++;
g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
}
static void
add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
{
ERROR_DECL (error);
if (method->is_generic && acfg->aot_opts.profile_only) {
// Add the fully shared version to its home image
// This has already been added just need to add it to profile_methods so its not skipped
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
g_hash_table_insert (acfg->profile_methods, method, method);
return;
}
if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
MonoMethod *orig = method;
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
if (!is_ok (error)) {
/* vtype constraint */
mono_error_cleanup (error);
return;
}
/* Add it to profile_methods so its not skipped later */
if (acfg->aot_opts.profile_only && g_hash_table_lookup (acfg->profile_methods, orig))
g_hash_table_insert (acfg->profile_methods, method, method);
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
/* Use the gsharedvt version */
method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
}
if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
mono_dedup_cache_method (acfg, method);
if (!acfg->dedup_emit_mode)
return;
}
if (acfg->aot_opts.log_generics)
aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
add_method_full (acfg, method, TRUE, depth);
}
static void
add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
{
add_extra_method_with_depth (acfg, method, 0);
}
static void
add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
{
if (!callinfo->sig)
return;
g_assert (callinfo->name && callinfo->func);
add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
}
#if ENABLE_LLVM
static void
add_lazy_init_wrappers (MonoAotCompile *acfg)
{
for (int i = 0; i < AOT_INIT_METHOD_NUM; ++i)
add_method (acfg, mono_marshal_get_aot_init_wrapper ((MonoAotInitSubtype)i));
}
#endif
static MonoMethod*
get_runtime_invoke_sig (MonoMethodSignature *sig)
{
MonoMethodBuilder *mb;
MonoMethod *m;
mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
m = mono_mb_create_method (mb, sig, 16);
MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
mono_mb_free (mb);
return invoke;
}
static MonoMethod*
get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
{
return mono_marshal_get_runtime_invoke (method, virtual_);
}
static gboolean
can_marshal_struct (MonoClass *klass)
{
MonoClassField *field;
gboolean can_marshal = TRUE;
gpointer iter = NULL;
MonoMarshalType *info;
int i;
if (mono_class_is_auto_layout (klass))
return FALSE;
info = mono_marshal_load_type_info (klass);
/* Only allow a few field types to avoid asserts in the marshalling code */
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
switch (field->type->type) {
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
break;
case MONO_TYPE_VALUETYPE:
if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
can_marshal = FALSE;
break;
case MONO_TYPE_SZARRAY: {
gboolean has_mspec = FALSE;
if (info) {
for (i = 0; i < info->num_fields; ++i) {
if (info->fields [i].field == field && info->fields [i].mspec)
has_mspec = TRUE;
}
}
if (!has_mspec)
can_marshal = FALSE;
break;
}
default:
can_marshal = FALSE;
break;
}
}
/* Special cases */
/* Its hard to compute whenever these can be marshalled or not */
if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
return TRUE;
return can_marshal;
}
static void
create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
{
/* Create a vtype instantiation */
MonoGenericContext shared_context;
MonoType **args;
MonoGenericInst *inst;
MonoGenericContainer *container;
MonoClass **constraints;
int i;
memset (ctx, 0, sizeof (MonoGenericContext));
if (mono_class_is_gtd (method->klass)) {
shared_context = mono_class_get_generic_container (method->klass)->context;
inst = shared_context.class_inst;
args = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
args [i] = mono_get_int_type ();
}
ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
}
if (method->is_generic) {
container = mono_method_get_generic_container (method);
g_assert (!container->is_anonymous && container->is_method);
shared_context = container->context;
inst = shared_context.method_inst;
args = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < container->type_argc; ++i) {
MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
gboolean ref_only = FALSE;
if (info && info->constraints) {
constraints = info->constraints;
while (*constraints) {
MonoClass *cklass = *constraints;
if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
/* Inflaring the method with our vtype would not be valid */
ref_only = TRUE;
constraints ++;
}
}
if (ref_only)
args [i] = mono_get_object_type ();
else
args [i] = mono_get_int_type ();
}
ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
}
}
static void
add_gc_wrappers (MonoAotCompile *acfg)
{
MonoMethod *m;
/* Managed Allocators */
int nallocators = mono_gc_get_managed_allocator_types ();
for (int i = 0; i < nallocators; ++i) {
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
add_method (acfg, m);
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
add_method (acfg, m);
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
add_method (acfg, m);
}
/* write barriers */
if (mono_gc_is_moving ()) {
add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
}
}
static gboolean
contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
{
for (int i = 0; i < cattr->num_attrs; ++i) {
MonoCustomAttrEntry *attr = &cattr->attrs [i];
if (!attr->ctor)
return FALSE;
if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
return FALSE;
if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
return FALSE;
}
return TRUE;
}
gboolean
mono_aot_can_specialize (MonoMethod *method)
{
if (!method)
return FALSE;
if (method->wrapper_type != MONO_WRAPPER_NONE)
return FALSE;
// If it's not private, we can't specialize
if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
return FALSE;
// If it has the attribute disabling the specialization, we can't specialize
//
// Set by linker, indicates that the method can be found through reflection
// and that call-site specialization shouldn't be done.
//
// Important that this attribute is used for *nothing else*
//
// If future authors make use of it (to disable more optimizations),
// change this place to use a new attribute.
ERROR_DECL (cattr_error);
MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
if (!is_ok (cattr_error)) {
mono_error_cleanup (cattr_error);
goto cleanup_false;
} else if (cattr && contains_disable_reflection_attribute (cattr)) {
goto cleanup_true;
}
cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
if (!is_ok (cattr_error)) {
mono_error_cleanup (cattr_error);
goto cleanup_false;
} else if (cattr && contains_disable_reflection_attribute (cattr)) {
goto cleanup_true;
} else {
goto cleanup_false;
}
cleanup_false:
if (cattr)
mono_custom_attrs_free (cattr);
return FALSE;
cleanup_true:
if (cattr)
mono_custom_attrs_free (cattr);
return TRUE;
}
static gboolean
always_aot (MonoMethod *method)
{
/*
* Calls to these methods do not go through the normal call processing code so
* calling code cannot enter the interpreter. So always aot them even in profile guided aot mode.
*/
if (method->klass == mono_get_string_class () && (strstr (method->name, "memcpy") || strstr (method->name, "bzero")))
return TRUE;
if (method->string_ctor)
return TRUE;
return FALSE;
}
gboolean
mono_aot_can_enter_interp (MonoMethod *method)
{
MonoAotCompile *acfg = current_acfg;
g_assert (acfg);
if (always_aot (method))
return FALSE;
if (acfg->aot_opts.profile_only && !g_hash_table_lookup (acfg->profile_methods, method))
return TRUE;
return FALSE;
}
static void
add_wrappers (MonoAotCompile *acfg)
{
MonoMethod *method, *m;
int i, j;
MonoMethodSignature *sig, *csig;
guint32 token;
/*
* FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
* so there is only one wrapper of a given type, or inlining their contents into their
* callers.
*/
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
gboolean skip = FALSE;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT))
skip = TRUE;
/* Skip methods which can not be handled by get_runtime_invoke () */
sig = mono_method_signature_internal (method);
if (!sig)
continue;
if ((sig->ret->type == MONO_TYPE_PTR) ||
(sig->ret->type == MONO_TYPE_TYPEDBYREF))
skip = TRUE;
if (mono_class_is_open_constructed_type (sig->ret) || m_class_is_byreflike (mono_class_from_mono_type_internal (sig->ret)))
skip = TRUE;
for (j = 0; j < sig->param_count; j++) {
if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
skip = TRUE;
if (mono_class_is_open_constructed_type (sig->params [j]))
skip = TRUE;
}
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
{
MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
gboolean has_nullable = FALSE;
for (j = 0; j < sig->param_count; j++) {
if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
has_nullable = TRUE;
}
if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
/* Supported by the dynamic runtime-invoke wrapper */
skip = TRUE;
}
if (info)
mono_arch_dyn_call_free (info);
}
#endif
if (acfg->aot_opts.llvm_only)
/* Supported by the gsharedvt based runtime-invoke wrapper */
skip = TRUE;
if (!skip) {
//printf ("%s\n", mono_method_full_name (method, TRUE));
add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
}
}
if (mono_is_corlib_image (acfg->image->assembly->image)) {
/* Runtime invoke wrappers */
MonoType *void_type = mono_get_void_type ();
MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
/* void runtime-invoke () [.cctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->ret = void_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke () [Finalize] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->hasthis = 1;
csig->ret = void_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string, string) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
csig->params [1] = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* string runtime-invoke () [Exception.ToString ()] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->hasthis = 1;
csig->ret = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string, Exception) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
add_method (acfg, get_runtime_invoke_sig (csig));
/* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
csig->hasthis = 1;
csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
csig->params [0] = string_type;
csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
add_method (acfg, get_runtime_invoke_sig (csig));
/* runtime-invoke used by finalizers */
add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
/* This is used by mono_runtime_capture_context () */
method = mono_get_context_capture_method ();
if (method)
add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (!acfg->aot_opts.llvm_only)
add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
#endif
/* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
if (acfg->aot_opts.llvm_only) {
int variants;
/* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
for (variants = 0; variants < 4; ++variants) {
for (i = 0; i < 40; ++i) {
sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
g_free (sig);
}
}
}
/* stelemref */
add_method (acfg, mono_marshal_get_stelemref ());
add_gc_wrappers (acfg);
/* Stelemref wrappers */
{
MonoMethod **wrappers;
int nwrappers;
wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
for (i = 0; i < nwrappers; ++i)
add_method (acfg, wrappers [i]);
g_free (wrappers);
}
/* castclass_with_check wrapper */
add_method (acfg, mono_marshal_get_castclass_with_cache ());
/* isinst_with_check wrapper */
add_method (acfg, mono_marshal_get_isinst_with_cache ());
/* JIT icall wrappers */
/* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
if (acfg->aot_opts.llvm_only) {
/* String ctors are called directly on llvmonly */
for (int i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (method && method->string_ctor) {
MonoMethod *w = get_runtime_invoke (acfg, method, FALSE);
add_method (acfg, w);
}
}
}
}
/*
* remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
* we use the original method instead at runtime.
* Since full-aot doesn't support remoting, this is not a problem.
*/
#if 0
/* remoting-invoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethodSignature *sig;
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
sig = mono_method_signature_internal (method);
if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
m = mono_marshal_get_remoting_invoke_with_check (method);
add_method (acfg, m);
}
}
#endif
/* delegate-invoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
continue;
if (!mono_class_is_gtd (klass)) {
method = mono_get_delegate_invoke_internal (klass);
m = mono_marshal_get_delegate_invoke (method, NULL);
add_method (acfg, m);
method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
if (method)
add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
if (method)
add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
MonoCustomAttrInfo *cattr;
cattr = mono_custom_attrs_from_class_checked (klass, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
g_assert (!cattr);
continue;
}
if (cattr) {
int j;
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && (!strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoNativeFunctionWrapperAttribute") || !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedFunctionPointerAttribute")))
break;
if (j < cattr->num_attrs) {
MonoMethod *invoke;
MonoMethod *wrapper;
MonoMethod *del_invoke;
/* Add wrappers needed by mono_ftnptr_to_delegate () */
invoke = mono_get_delegate_invoke_internal (klass);
wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
add_method (acfg, wrapper);
add_method (acfg, del_invoke);
}
mono_custom_attrs_free (cattr);
}
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *inst, *gshared;
/*
* Emit gsharedvt versions of the generic delegate-invoke wrappers
*/
/* Invoke */
method = mono_get_delegate_invoke_internal (klass);
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_invoke (inst, NULL);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
/* begin-invoke */
method = mono_get_delegate_begin_invoke_internal (klass);
if (method) {
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_begin_invoke (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
/* end-invoke */
method = mono_get_delegate_end_invoke_internal (klass);
if (method) {
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_end_invoke (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
}
}
/* array access wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_SPEC | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
MonoMethod *m, *wrapper;
/* Add runtime-invoke wrappers too */
m = get_method_nofail (klass, "Get", -1, 0);
g_assert (m);
wrapper = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, wrapper);
if (!acfg->aot_opts.llvm_only)
add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
m = get_method_nofail (klass, "Set", -1, 0);
g_assert (m);
wrapper = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, wrapper);
if (!acfg->aot_opts.llvm_only)
add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
}
}
/* Synchronized wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
if (method->is_generic) {
// FIXME:
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *inst, *gshared, *m;
/*
* Create a generic wrapper for a generic instance, and AOT that.
*/
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_synchronized_wrapper (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_method (acfg, gshared);
} else {
add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
}
}
}
/* pinvoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
}
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (acfg->aot_opts.llvm_only) {
/* The wrappers have a different signature (hasthis is not set) so need to add this too */
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
}
}
}
/* native-to-managed wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
MonoCustomAttrInfo *cattr;
int j;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
/*
* Only generate native-to-managed wrappers for methods which have an
* attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
* name to avoid defining a new assembly to contain it.
*/
cattr = mono_custom_attrs_from_method_checked (method, error);
if (!is_ok (error)) {
char *name = mono_method_get_full_name (method);
report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
g_free (name);
}
if (cattr) {
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
const char *p = (const char*)e->data;
const char *named;
int slen, num_named, named_type;
char *n;
MonoType *t;
MonoClass *klass;
char *export_name = NULL;
MonoMethod *wrapper;
/* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See https://docs.microsoft.com/xamarin/ios/internals/limitations#reverse-callbacks",
mono_method_full_name (method, TRUE));
exit (1);
}
g_assert (sig->param_count == 1);
g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
/*
* Decode the cattr manually since we can't create objects
* during aot compilation.
*/
/* Skip prolog */
p += 2;
/* From load_cattr_value () in reflection.c */
slen = mono_metadata_decode_value (p, &p);
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name_checked (n, mono_alc_get_ambient (), acfg->image, error);
g_assert (t);
mono_error_assert_ok (error);
g_free (n);
klass = mono_class_from_mono_type_internal (t);
g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
p += slen;
num_named = read16 (p);
p += 2;
g_assert (num_named < 2);
if (num_named == 1) {
int name_len;
char *name;
/* parse ExportSymbol attribute */
named = p;
named_type = *named;
named += 1;
/* data_type = *named; */
named += 1;
name_len = mono_metadata_decode_blob_size (named, &named);
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
g_assert (named_type == 0x54);
g_assert (!strcmp (name, "ExportSymbol"));
/* load_cattr_value (), string case */
MONO_DISABLE_WARNING (4310) // cast truncates constant value
g_assert (*named != (char)0xFF);
MONO_RESTORE_WARNING
slen = mono_metadata_decode_value (named, &named);
export_name = (char *)g_malloc (slen + 1);
memcpy (export_name, named, slen);
export_name [slen] = 0;
named += slen;
}
wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
mono_error_assert_ok (error);
add_method (acfg, wrapper);
if (export_name)
g_hash_table_insert (acfg->export_names, wrapper, export_name);
}
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && mono_is_corlib_image (m_class_get_image (cattr->attrs [j].ctor->klass)) && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedCallersOnlyAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
const char *named;
int slen;
char *export_name = NULL;
MonoMethod *wrapper;
if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [UnmanagedCallers].",
mono_method_full_name (method, TRUE));
exit (1);
}
gpointer *typed_args = NULL;
gpointer *named_args = NULL;
CattrNamedArg *named_arg_info = NULL;
int num_named_args = 0;
mono_reflection_create_custom_attr_data_args_noalloc (acfg->image, e->ctor, e->data, e->data_size, &typed_args, &named_args, &num_named_args, &named_arg_info, error);
mono_error_assert_ok (error);
for (j = 0; j < num_named_args; ++j) {
if (named_arg_info [j].field && !strcmp (named_arg_info [j].field->name, "EntryPoint")) {
named = named_args [j];
slen = mono_metadata_decode_value (named, &named);
export_name = (char *)g_malloc (slen + 1);
memcpy (export_name, named, slen);
export_name [slen] = 0;
}
}
g_free (named_args);
g_free (named_arg_info);
wrapper = mono_marshal_get_managed_wrapper (method, NULL, 0, error);
mono_error_assert_ok (error);
add_method (acfg, wrapper);
if (export_name)
g_hash_table_insert (acfg->export_names, wrapper, export_name);
}
g_free (cattr);
}
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
}
}
/* StructureToPtr/PtrToStructure wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
!(m_class_get_nested_in (klass) && strstr (m_class_get_name (m_class_get_nested_in (klass)), "<PrivateImplementationDetails>") == m_class_get_name (m_class_get_nested_in (klass)))) {
add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
}
}
}
static gboolean
has_type_vars (MonoClass *klass)
{
if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
return TRUE;
if (m_class_get_rank (klass))
return has_type_vars (m_class_get_element_class (klass));
if (mono_class_is_ginst (klass)) {
MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
if (context->class_inst) {
int i;
for (i = 0; i < context->class_inst->type_argc; ++i)
if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
return TRUE;
}
}
if (mono_class_is_gtd (klass))
return TRUE;
return FALSE;
}
static gboolean
is_vt_inst (MonoGenericInst *inst)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
return TRUE;
}
return FALSE;
}
static gboolean
is_vt_inst_no_enum (MonoGenericInst *inst)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t))
return TRUE;
}
return FALSE;
}
static gboolean
method_has_type_vars (MonoMethod *method)
{
if (has_type_vars (method->klass))
return TRUE;
if (method->is_inflated) {
MonoGenericContext *context = mono_method_get_context (method);
if (context->method_inst) {
int i;
for (i = 0; i < context->method_inst->type_argc; ++i)
if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
return TRUE;
}
}
return FALSE;
}
static
gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
{
return opts->mode == MONO_AOT_MODE_FULL;
}
static
gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
{
return opts->interp;
}
static
gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
{
return opts->mode == MONO_AOT_MODE_HYBRID;
}
static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
static void
add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
{
/* This might lead to a huge code blowup so only do it if neccesary */
if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
return;
add_generic_class_with_depth (acfg, klass, 0, ref);
}
static gboolean
check_type_depth (MonoType *t, int depth)
{
int i;
if (depth > 8)
return TRUE;
switch (t->type) {
case MONO_TYPE_GENERICINST: {
MonoGenericClass *gklass = t->data.generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
if (ginst) {
for (i = 0; i < ginst->type_argc; ++i) {
if (check_type_depth (ginst->type_argv [i], depth + 1))
return TRUE;
}
}
break;
}
default:
break;
}
return FALSE;
}
static void
add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
static gboolean
inst_has_vtypes (MonoGenericInst *inst)
{
for (int i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t))
return TRUE;
}
return FALSE;
}
/*
* add_generic_class:
*
* Add all methods of a generic class.
*/
static void
add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
{
MonoMethod *method;
MonoClassField *field;
gpointer iter;
gboolean use_gsharedvt = FALSE;
gboolean use_gsharedvt_for_array = FALSE;
if (!acfg->ginst_hash)
acfg->ginst_hash = g_hash_table_new (NULL, NULL);
mono_class_init_internal (klass);
if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
return;
if (has_type_vars (klass))
return;
if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
return;
if (mono_class_has_failure (klass))
return;
if (!acfg->ginst_hash)
acfg->ginst_hash = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (acfg->ginst_hash, klass))
return;
if (check_type_depth (m_class_get_byval_arg (klass), 0))
return;
if (acfg->aot_opts.log_generics) {
char *s = mono_type_full_name (m_class_get_byval_arg (klass));
aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
g_free (s);
}
g_hash_table_insert (acfg->ginst_hash, klass, klass);
/*
* Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
* Enable this only for some classes since gsharedvt might not support all methods.
*/
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && m_class_get_image (klass) == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
(!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
use_gsharedvt = TRUE;
#ifdef TARGET_WASM
/*
* Use gsharedvt for instances with vtype arguments.
* WASM only since other platforms depend on the
* previous behavior.
*/
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst_no_enum (mono_class_get_generic_class (klass)->context.class_inst)) {
use_gsharedvt = TRUE;
use_gsharedvt_for_array = TRUE;
}
#endif
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
/*
* This is partial sharing, and we can't handle it yet
*/
continue;
}
if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
/* Already added */
add_types_from_method_header (acfg, method);
continue;
}
if (method->is_generic)
/* FIXME: */
continue;
/*
* FIXME: Instances which are referenced by these methods are not added,
* for example Array.Resize<int> for List<int>.Add ().
*/
add_extra_method_with_depth (acfg, method, depth + 1);
}
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if (field->type->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
}
if (m_class_is_delegate (klass)) {
method = mono_get_delegate_invoke_internal (klass);
method = mono_marshal_get_delegate_invoke (method, NULL);
if (acfg->aot_opts.log_generics)
aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
add_method (acfg, method);
}
/* Add superclasses */
if (m_class_get_parent (klass))
add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
const char *klass_name = m_class_get_name (klass);
const char *klass_name_space = m_class_get_name_space (klass);
const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
/*
* For ICollection<T>, add instances of the helper methods
* in Array, since a T[] could be cast to ICollection<T>.
*/
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
(!strcmp(klass_name, "ICollection`1") || !strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IList`1") || !strcmp (klass_name, "IEnumerator`1") || !strcmp (klass_name, "IReadOnlyList`1"))) {
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
gpointer iter;
char *name_prefix;
if (!strcmp (klass_name, "IEnumerator`1"))
name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
else
name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
iter = NULL;
while ((method = mono_class_get_methods (array_class, &iter))) {
if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, use_gsharedvt_for_array))
add_extra_method_with_depth (acfg, m, depth);
}
}
g_free (name_prefix);
}
/* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
ERROR_DECL (error);
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *icomparable, *gcomparer, *icomparable_inst;
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
MonoClass *gcomparer_inst;
gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
}
}
/* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
ERROR_DECL (error);
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *iface, *gcomparer, *iface_inst;
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
g_assert (iface);
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
MonoClass *gcomparer_inst;
ERROR_DECL (error);
gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
}
}
/* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
MonoClass *enum_comparer;
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoGenericContext ctx;
if (m_class_is_enumtype (tclass)) {
MonoClass *enum_comparer_inst;
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
}
}
/* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
MonoClass *comparer;
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoGenericContext ctx;
if (m_class_is_enumtype (tclass)) {
MonoClass *comparer_inst;
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
}
}
}
static void
add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
{
int i;
MonoGenericContext ctx;
if (acfg->aot_opts.no_instances)
return;
memset (&ctx, 0, sizeof (ctx));
for (i = 0; i < ninsts; ++i) {
ERROR_DECL (error);
MonoClass *generic_inst;
MonoType *args [ ] = { insts [i] };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, generic_inst, force, "");
}
}
static void
add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
{
ERROR_DECL (error);
MonoMethodHeader *header;
MonoMethodSignature *sig;
int j, depth;
depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
sig = mono_method_signature_internal (method);
if (sig) {
for (j = 0; j < sig->param_count; ++j)
if (sig->params [j]->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
}
header = mono_method_get_header_checked (method, error);
if (header) {
for (j = 0; j < header->num_locals; ++j)
if (header->locals [j]->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
mono_metadata_free_mh (header);
} else {
mono_error_cleanup (error); /* FIXME report the error */
}
}
/*
* add_generic_instances:
*
* Add instances referenced by the METHODSPEC/TYPESPEC table.
*/
static void
add_generic_instances (MonoAotCompile *acfg)
{
int i;
guint32 token;
MonoMethod *method;
MonoGenericContext *context;
if (acfg->aot_opts.no_instances)
return;
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHODSPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_SPEC | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (!method) {
aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
continue;
}
if (m_class_get_image (method->klass) != acfg->image)
continue;
context = mono_method_get_context (method);
if (context && ((context->class_inst && context->class_inst->is_open)))
continue;
/*
* For open methods, create an instantiation which can be passed to the JIT.
* FIXME: Handle class_inst as well.
*/
if (context && context->method_inst && context->method_inst->is_open) {
ERROR_DECL (error);
MonoGenericContext shared_context;
MonoGenericInst *inst;
MonoType **type_argv;
int i;
MonoMethod *declaring_method;
gboolean supported = TRUE;
/* Check that the context doesn't contain open constructed types */
if (context->class_inst) {
inst = context->class_inst;
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
continue;
if (mono_class_is_open_constructed_type (inst->type_argv [i]))
supported = FALSE;
}
}
if (context->method_inst) {
inst = context->method_inst;
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
continue;
if (mono_class_is_open_constructed_type (inst->type_argv [i]))
supported = FALSE;
}
}
if (!supported)
continue;
memset (&shared_context, 0, sizeof (MonoGenericContext));
inst = context->class_inst;
if (inst) {
type_argv = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
type_argv [i] = mono_get_object_type ();
else
type_argv [i] = inst->type_argv [i];
}
shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
g_free (type_argv);
}
inst = context->method_inst;
if (inst) {
type_argv = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
type_argv [i] = mono_get_object_type ();
else
type_argv [i] = inst->type_argv [i];
}
shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
g_free (type_argv);
}
if (method->is_generic || mono_class_is_gtd (method->klass))
declaring_method = method;
else
declaring_method = mono_method_get_declaring_generic_method (method);
method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
/*
* If the method is fully sharable, it was already added in place of its
* generic definition.
*/
if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
continue;
/*
* FIXME: Partially shared methods are not shared here, so we end up with
* many identical methods.
*/
add_extra_method (acfg, method);
}
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_SPEC | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass || m_class_get_rank (klass)) {
mono_error_cleanup (error);
continue;
}
add_generic_class (acfg, klass, FALSE, "typespec");
}
/* Add types of args/locals */
for (i = 0; i < acfg->methods->len; ++i) {
method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
add_types_from_method_header (acfg, method);
}
if (acfg->image == mono_defaults.corlib) {
MonoClass *klass;
MonoType *insts [256];
int ninsts = 0;
MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
MonoType *int32_type = mono_get_int32_type ();
MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
MonoType *object_type = mono_get_object_type ();
insts [ninsts ++] = byte_type;
insts [ninsts ++] = sbyte_type;
insts [ninsts ++] = int16_type;
insts [ninsts ++] = uint16_type;
insts [ninsts ++] = int32_type;
insts [ninsts ++] = uint32_type;
insts [ninsts ++] = int64_type;
insts [ninsts ++] = uint64_type;
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
/* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
/* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
{
MonoClass *k, *enum_comparer;
MonoType *insts [16];
int ninsts;
const char *enum_names [] = { "I8Enum", "I16Enum", "I32Enum", "I64Enum", "UI8Enum", "UI16Enum", "UI32Enum", "UI64Enum" };
ninsts = 0;
for (int i = 0; i < G_N_ELEMENTS (enum_names); ++i) {
k = mono_class_try_load_from_name (acfg->image, "Mono", enum_names [i]);
g_assert (k);
insts [ninsts ++] = m_class_get_byval_arg (k);
}
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
add_instances_of (acfg, enum_comparer, insts, ninsts, TRUE);
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumComparer`1");
add_instances_of (acfg, enum_comparer, insts, ninsts, TRUE);
}
/* Add instances of the array generic interfaces for primitive types */
/* This will add instances of the InternalArray_ helper methods in Array too */
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System", "SZGenericArrayEnumerator`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
/*
* Add a managed-to-native wrapper of Array.GetGenericValue_icall<object>, which is
* used for all instances of GetGenericValue_icall by the AOT runtime.
*/
{
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *get_method;
MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValue_icall", 3, 0, error);
mono_error_assert_ok (error);
if (get_method) {
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { object_type };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
mono_error_assert_ok (error); /* FIXME don't swallow the error */
}
}
/* object[] accessor wrappers. */
for (i = 1; i < 4; ++i) {
MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
MonoMethod *m;
m = get_method_nofail (obj_array_class, "Get", i, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
m = get_method_nofail (obj_array_class, "Address", i, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
}
}
}
static char *
decode_direct_icall_symbol_name_attribute (MonoMethod *method)
{
ERROR_DECL (error);
int j = 0;
char *symbol_name = NULL;
MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
if (is_ok(error) && cattr) {
for (j = 0; j < cattr->num_attrs; j++)
if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
/*
* Decode the cattr manually since we can't create objects
* during aot compilation.
*/
/* Skip prolog */
const char *p = ((const char*)e->data) + 2;
int slen = mono_metadata_decode_value (p, &p);
symbol_name = (char *)g_memdup (p, slen + 1);
if (symbol_name)
symbol_name [slen] = 0;
}
}
}
return symbol_name;
}
static const char*
lookup_external_icall_symbol_name_aot (MonoMethod *method)
{
g_assert (method_to_external_icall_symbol_name);
gpointer key, value;
if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
return (const char*)value;
char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
return symbol_name;
}
static const char*
lookup_icall_symbol_name_aot (MonoMethod *method)
{
const char * symbol_name = mono_lookup_icall_symbol (method);
if (!symbol_name)
symbol_name = lookup_external_icall_symbol_name_aot (method);
return symbol_name;
}
gboolean
mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
{
gboolean enable_icall = FALSE;
if (cfg->compile_aot)
enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
else
enable_icall = FALSE;
return enable_icall;
}
/*
* method_is_externally_callable:
*
* Return whenever METHOD can be directly called from other AOT images
* without going through a PLT.
*/
static gboolean
method_is_externally_callable (MonoAotCompile *acfg, MonoMethod *method)
{
// FIXME: Unify
if (acfg->aot_opts.llvm_only) {
if (!acfg->aot_opts.static_link)
return FALSE;
if (method->wrapper_type == MONO_WRAPPER_ALLOC)
return TRUE;
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
return TRUE;
if (method->string_ctor)
return FALSE;
if (method->wrapper_type)
return FALSE;
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
return FALSE;
if (method->is_inflated)
return FALSE;
if (!((mono_class_get_flags (method->klass) & TYPE_ATTRIBUTE_PUBLIC) && (method->flags & METHOD_ATTRIBUTE_PUBLIC)))
return FALSE;
/* Can't enable this as the callee might fail llvm compilation */
//return TRUE;
return FALSE;
} else {
if (!acfg->aot_opts.direct_extern_calls)
return FALSE;
if (!acfg->llvm)
return FALSE;
if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)
return FALSE;
if (method->wrapper_type == MONO_WRAPPER_ALLOC)
return FALSE;
if (method->string_ctor)
return FALSE;
if (method->wrapper_type)
return FALSE;
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
return FALSE;
if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
return FALSE;
if (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)
return FALSE;
if (method->is_inflated)
return FALSE;
if (!((mono_class_get_flags (method->klass) & TYPE_ATTRIBUTE_PUBLIC) && (method->flags & METHOD_ATTRIBUTE_PUBLIC)))
return FALSE;
return TRUE;
}
}
/*
* is_direct_callable:
*
* Return whenever the method identified by JI is directly callable without
* going through the PLT.
*/
static gboolean
is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
{
if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
if (callee_cfg) {
gboolean direct_callable = TRUE;
if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
direct_callable = FALSE;
if (direct_callable && !acfg->llvm && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
direct_callable = FALSE;
if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
direct_callable = FALSE;
//
// FIXME: Support inflated methods, it asserts in mini_llvm_init_gshared_method_this () because the method is not in
// amodule->extra_methods.
//
if (direct_callable && callee_cfg->method->is_inflated)
direct_callable = FALSE;
if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
// FIXME: Maybe call the wrapper directly ?
direct_callable = FALSE;
if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
/* Disable this so all calls go through load_method (), see the
* mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
* mono_debugger_agent_init ().
*/
direct_callable = FALSE;
}
if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
/* sgen does some initialization when the allocator method is created */
direct_callable = FALSE;
if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
/* we don't know at compile time whether sgen is concurrent or not */
direct_callable = FALSE;
if (direct_callable)
return TRUE;
}
} else if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) != acfg->image)) {
/* Cross assembly calls */
return method_is_externally_callable (acfg, patch_info->data.method);
} else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
if (acfg->aot_opts.direct_pinvoke)
return TRUE;
} else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
if (acfg->aot_opts.direct_icalls)
return TRUE;
return FALSE;
}
return FALSE;
}
#ifdef MONO_ARCH_AOT_SUPPORTED
static const char *
get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
{
MonoImage *image = m_class_get_image (method->klass);
MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
MonoTableInfo *tables = image->tables;
MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
guint32 im_cols [MONO_IMPLMAP_SIZE];
char *import;
import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
if (import != NULL)
return import;
if (piinfo->implmap_idx == 0 || mono_metadata_table_bounds_check (image, MONO_TABLE_IMPLMAP, piinfo->implmap_idx))
return NULL;
mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
int module_idx = im_cols [MONO_IMPLMAP_SCOPE];
if (module_idx == 0 || mono_metadata_table_bounds_check (image, MONO_TABLE_MODULEREF, module_idx))
return NULL;
import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
return import;
}
#else
static const char *
get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
{
return NULL;
}
#endif
static gint
compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
{
if (a->native_offset == b->native_offset)
return a->il_offset - b->il_offset;
else
return a->native_offset - b->native_offset;
}
/*
* compute_line_numbers:
*
* Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
* entry.
*/
static MonoDebugSourceLocation**
compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
{
MonoDebugMethodInfo *minfo;
MonoDebugLineNumberEntry *ln_array;
MonoDebugSourceLocation *loc;
int i, prev_line, prev_il_offset;
int *native_to_il_offset = NULL;
MonoDebugSourceLocation **res;
gboolean first;
minfo = mono_debug_lookup_method (method);
if (!minfo)
return NULL;
// FIXME: This seems to happen when two methods have the same cfg->method_to_register
if (debug_info->code_size != code_size)
return NULL;
g_assert (code_size);
/* Compute the native->IL offset mapping */
ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
mono_qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
native_to_il_offset = g_new0 (int, code_size + 1);
for (i = 0; i < debug_info->num_line_numbers; ++i) {
int j;
MonoDebugLineNumberEntry *lne = &ln_array [i];
if (i == 0) {
for (j = 0; j < lne->native_offset; ++j)
native_to_il_offset [j] = -1;
}
if (i < debug_info->num_line_numbers - 1) {
MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
for (j = lne->native_offset; j < lne_next->native_offset; ++j)
native_to_il_offset [j] = lne->il_offset;
} else {
for (j = lne->native_offset; j < code_size; ++j)
native_to_il_offset [j] = lne->il_offset;
}
}
g_free (ln_array);
/* Compute the native->line number mapping */
res = g_new0 (MonoDebugSourceLocation*, code_size);
prev_il_offset = -1;
prev_line = -1;
first = TRUE;
for (i = 0; i < code_size; ++i) {
int il_offset = native_to_il_offset [i];
if (il_offset == -1 || il_offset == prev_il_offset)
continue;
prev_il_offset = il_offset;
loc = mono_debug_method_lookup_location (minfo, il_offset);
if (!(loc && loc->source_file))
continue;
if (loc->row == prev_line) {
mono_debug_free_source_location (loc);
continue;
}
prev_line = loc->row;
//printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
if (first)
/* This will cover the prolog too */
res [0] = loc;
else
res [i] = loc;
first = FALSE;
}
return res;
}
static int
get_file_index (MonoAotCompile *acfg, const char *source_file)
{
int findex;
// FIXME: Free these
if (!acfg->dwarf_ln_filenames)
acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
if (!findex) {
findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
emit_unset_mode (acfg);
fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
}
return findex;
}
#ifdef TARGET_ARM64
#define INST_LEN 4
#else
#define INST_LEN 1
#endif
static gboolean
never_direct_pinvoke (const char *pinvoke_symbol)
{
#if defined(TARGET_IOS) || defined (TARGET_TVOS) || defined (TARGET_OSX) || defined (TARGET_WATCHOS)
/* XI must be able to override the functions that start with objc_msgSend.
* (there are a few variants with the same prefix) */
return !strncmp (pinvoke_symbol, "objc_msgSend", 12);
#else
return FALSE;
#endif
}
/*
* emit_and_reloc_code:
*
* Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
* is true, calls are made through the GOT too. This is used for emitting trampolines
* in full-aot mode, since calls made from trampolines couldn't go through the PLT,
* since trampolines are needed to make PLT work.
*/
static void
emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
{
int i, pindex, start_index;
GPtrArray *patches;
MonoJumpInfo *patch_info;
MonoDebugSourceLocation **locs = NULL;
gboolean skip, prologue_end = FALSE;
#ifdef MONO_ARCH_AOT_SUPPORTED
gboolean direct_call, external_call;
guint32 got_slot;
const char *direct_call_target = 0;
const char *direct_pinvoke;
#endif
if (acfg->gas_line_numbers && method && debug_info) {
locs = compute_line_numbers (method, code_len, debug_info);
if (!locs) {
int findex = get_file_index (acfg, "<unknown>");
emit_unset_mode (acfg);
fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
}
}
/* Collect and sort relocations */
patches = g_ptr_array_new ();
for (patch_info = relocs; patch_info; patch_info = patch_info->next)
g_ptr_array_add (patches, patch_info);
g_ptr_array_sort (patches, compare_patches);
start_index = 0;
for (i = 0; i < code_len; i += INST_LEN) {
patch_info = NULL;
for (pindex = start_index; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->ip.i >= i)
break;
}
if (locs && locs [i]) {
MonoDebugSourceLocation *loc = locs [i];
int findex;
const char *options;
findex = get_file_index (acfg, loc->source_file);
emit_unset_mode (acfg);
if (!prologue_end)
options = " prologue_end";
else
options = "";
prologue_end = TRUE;
fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
mono_debug_free_source_location (loc);
}
skip = FALSE;
#ifdef MONO_ARCH_AOT_SUPPORTED
if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
start_index = pindex;
switch (patch_info->type) {
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_GOT_OFFSET: {
int code_size;
arch_emit_got_offset (acfg, code + i, &code_size);
i += code_size - INST_LEN;
skip = TRUE;
patch_info->type = MONO_PATCH_INFO_NONE;
break;
}
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
int code_size, index;
char *selector = (char *)patch_info->data.target;
if (!acfg->objc_selector_to_index)
acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
if (!acfg->objc_selectors)
acfg->objc_selectors = g_ptr_array_new ();
index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
if (index)
index --;
else {
index = acfg->objc_selector_index;
g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
acfg->objc_selector_index ++;
}
arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
i += code_size - INST_LEN;
skip = TRUE;
patch_info->type = MONO_PATCH_INFO_NONE;
break;
}
default: {
/*
* If this patch is a call, try emitting a direct call instead of
* through a PLT entry. This is possible if the called method is in
* the same assembly and requires no initialization.
*/
direct_call = FALSE;
external_call = FALSE;
if (patch_info->type == MONO_PATCH_INFO_METHOD) {
MonoMethod *cmethod = patch_info->data.method;
if (cmethod->wrapper_type == MONO_WRAPPER_OTHER && mono_marshal_get_wrapper_info (cmethod)->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
WrapperInfo *info = mono_marshal_get_wrapper_info (cmethod);
/*
* This is a call from a JITted method to the init wrapper emitted by LLVM.
*/
g_assert (acfg->aot_opts.llvm && acfg->aot_opts.direct_extern_calls);
const char *init_name = mono_marshal_get_aot_init_wrapper_name (info->d.aot_init.subtype);
char *symbol = g_strdup_printf ("%s%s_%s", acfg->user_symbol_prefix, acfg->global_prefix, init_name);
direct_call = TRUE;
direct_call_target = symbol;
patch_info->type = MONO_PATCH_INFO_NONE;
} else if ((m_class_get_image (patch_info->data.method->klass) == acfg->image) && !got_only && is_direct_callable (acfg, method, patch_info)) {
MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, cmethod);
// Don't compile inflated methods if we're doing dedup
if (acfg->aot_opts.dedup && !mono_aot_can_dedup (cmethod)) {
char *name = mono_aot_get_mangled_method_name (cmethod);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
g_free (name);
direct_call = TRUE;
direct_call_target = callee_cfg->asm_symbol;
patch_info->type = MONO_PATCH_INFO_NONE;
acfg->stats.direct_calls ++;
}
}
acfg->stats.all_calls ++;
} else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
if (!got_only && is_direct_callable (acfg, method, patch_info)) {
if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
else
direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
if (direct_pinvoke && !never_direct_pinvoke (direct_pinvoke)) {
direct_call = TRUE;
g_assert (strlen (direct_pinvoke) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
}
}
} else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
if (!got_only && sym && acfg->aot_opts.direct_icalls) {
/* Call to a C function implementing a jit icall */
direct_call = TRUE;
external_call = TRUE;
g_assert (strlen (sym) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
}
} else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
const char * const sym = info->c_symbol;
if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
/* Call to a jit icall without a wrapper */
direct_call = TRUE;
external_call = TRUE;
g_assert (strlen (sym) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
}
}
if (direct_call) {
patch_info->type = MONO_PATCH_INFO_NONE;
acfg->stats.direct_calls ++;
}
if (!got_only && !direct_call) {
MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
if (plt_entry) {
/* This patch has a PLT entry, so we must emit a call to the PLT entry */
direct_call = TRUE;
direct_call_target = plt_entry->symbol;
/* Nullify the patch */
patch_info->type = MONO_PATCH_INFO_NONE;
plt_entry->jit_used = TRUE;
}
}
if (direct_call) {
int call_size;
arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
i += call_size - INST_LEN;
} else {
int code_size;
got_slot = get_got_offset (acfg, FALSE, patch_info);
arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
i += code_size - INST_LEN;
}
skip = TRUE;
}
}
}
#endif /* MONO_ARCH_AOT_SUPPORTED */
if (!skip) {
/* Find next patch */
patch_info = NULL;
for (pindex = start_index; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->ip.i >= i)
break;
}
/* Try to emit multiple bytes at once */
if (pindex < patches->len && patch_info->ip.i > i) {
int limit;
for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
if (locs && locs [limit])
break;
}
emit_code_bytes (acfg, code + i, limit - i);
i = limit - INST_LEN;
} else {
emit_code_bytes (acfg, code + i, INST_LEN);
}
}
}
g_ptr_array_free (patches, TRUE);
g_free (locs);
}
/*
* sanitize_symbol:
*
* Return a modified version of S which only includes characters permissible in symbols.
*/
static char*
sanitize_symbol (MonoAotCompile *acfg, char *s)
{
gboolean process = FALSE;
int i, len;
GString *gs;
char *res;
if (!s)
return s;
len = strlen (s);
for (i = 0; i < len; ++i)
if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
process = TRUE;
if (!process)
return s;
gs = g_string_sized_new (len);
for (i = 0; i < len; ++i) {
guint8 c = s [i];
if (c <= 0x7f && (isalnum (c) || c == '_')) {
g_string_append_c (gs, c);
} else if (c > 0x7f) {
/* multi-byte utf8 */
g_string_append_printf (gs, "_0x%x", c);
i ++;
c = s [i];
while (c >> 6 == 0x2) {
g_string_append_printf (gs, "%x", c);
i ++;
c = s [i];
}
g_string_append_printf (gs, "_");
i --;
} else {
g_string_append_c (gs, '_');
}
}
res = mono_mempool_strdup (acfg->mempool, gs->str);
g_string_free (gs, TRUE);
return res;
}
static char*
get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
{
char *name1, *name2, *cached;
int i, j, len, count;
MonoMethod *cached_method;
name1 = mono_method_full_name (method, TRUE);
#ifdef TARGET_MACH
// This is so that we don't accidentally create a local symbol (which starts with 'L')
if ((!prefix || !*prefix) && name1 [0] == 'L')
prefix = "_";
#endif
#if defined(TARGET_WIN32) && defined(TARGET_X86)
char adjustedPrefix [MAX_SYMBOL_SIZE];
prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
#endif
len = strlen (name1);
name2 = (char *) g_malloc (strlen (prefix) + len + 16);
memcpy (name2, prefix, strlen (prefix));
j = strlen (prefix);
for (i = 0; i < len; ++i) {
if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
name2 [j ++] = '_';
} else if (isalnum (name1 [i])) {
name2 [j ++] = name1 [i];
} else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
i += 2;
} else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
name2 [j ++] = '_';
i++;
} else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
} else
name2 [j ++] = '_';
}
name2 [j] = '\0';
g_free (name1);
count = 0;
while (TRUE) {
cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
if (!(cached_method && cached_method != method))
break;
sprintf (name2 + j, "_%d", count);
count ++;
}
cached = g_strdup (name2);
g_hash_table_insert (cache, cached, method);
return name2;
}
static void
emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
{
MonoMethod *method;
int method_index;
guint8 *code;
char *debug_sym = NULL;
char *symbol = NULL;
int func_alignment = AOT_FUNC_ALIGNMENT;
char *export_name;
g_assert (!ignore_cfg (cfg));
method = cfg->orig_method;
code = cfg->native_code;
method_index = get_method_index (acfg, method);
symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
/* Make the labels local */
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, func_alignment);
if (acfg->global_symbols && acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
emit_label (acfg, cfg->asm_symbol);
if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
/*
* Write a C style symbol for every method, this has two uses:
* - it works on platforms where the dwarf debugging info is not
* yet supported.
* - it allows the setting of breakpoints of aot-ed methods.
*/
// Enable to force dedup to link these symbols and forbid compiling
// in duplicated code. This is an "assert when linking if broken" trick.
#if 0
if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))
debug_sym = mono_aot_get_mangled_method_name (method);
else
#endif
debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
cfg->asm_debug_symbol = g_strdup (debug_sym);
if (acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
// Enable to force dedup to link these symbols and forbid compiling
// in duplicated code. This is an "assert when linking if broken" trick.
#if 0
if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))
emit_global_inner (acfg, debug_sym, TRUE);
else
#endif
emit_local_symbol (acfg, debug_sym, symbol, TRUE);
emit_label (acfg, debug_sym);
}
export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
if (export_name) {
/* Emit a global symbol for the method */
emit_global_inner (acfg, export_name, TRUE);
emit_label (acfg, export_name);
}
if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
acfg->stats.code_size += cfg->code_len;
acfg->cfgs [method_index]->got_offset = acfg->got_offset;
MonoDebugMethodJitInfo *jit_debug_info = mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ());
emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, jit_debug_info);
mono_debug_free_method_jit_info (jit_debug_info);
emit_line (acfg);
if (acfg->aot_opts.write_symbols) {
if (debug_sym)
emit_symbol_size (acfg, debug_sym, ".");
else
emit_symbol_size (acfg, cfg->asm_symbol, ".");
g_free (debug_sym);
}
emit_label (acfg, symbol);
arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
g_free (symbol);
}
/**
* encode_patch:
*
* Encode PATCH_INFO into its disk representation.
*/
static void
encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
switch (patch_info->type) {
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_IMAGE:
encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
break;
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
break;
case MONO_PATCH_INFO_SWITCH: {
gpointer *table = (gpointer *)patch_info->data.table->table;
int k;
encode_value (patch_info->data.table->table_size, p, &p);
for (k = 0; k < patch_info->data.table->table_size; k++)
encode_value ((int)(gssize)table [k], p, &p);
break;
}
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
encode_method_ref (acfg, patch_info->data.method, p, &p);
break;
case MONO_PATCH_INFO_AOT_JIT_INFO:
case MONO_PATCH_INFO_CASTCLASS_CACHE:
encode_value (patch_info->data.index, p, &p);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
encode_value (patch_info->data.jit_icall_id, p, &p);
break;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
encode_value (patch_info->data.uindex, p, &p);
break;
case MONO_PATCH_INFO_LDSTR_LIT: {
guint32 len = strlen (patch_info->data.name);
encode_value (len, p, &p);
memcpy (p, patch_info->data.name, len + 1);
p += len + 1;
break;
}
case MONO_PATCH_INFO_LDSTR: {
guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
guint32 token = patch_info->data.token->token;
g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
encode_value (image_index, p, &p);
encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
break;
}
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_DECLSEC:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
encode_value (patch_info->data.token->token, p, &p);
encode_value (patch_info->data.token->has_context, p, &p);
if (patch_info->data.token->has_context)
encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
break;
case MONO_PATCH_INFO_EXC_NAME: {
MonoClass *ex_class;
ex_class =
mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
"System", (const char *)patch_info->data.target);
encode_klass_ref (acfg, ex_class, p, &p);
break;
}
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT:
encode_value (*((guint32 *)patch_info->data.target), p, &p);
break;
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT:
encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
break;
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
encode_klass_ref (acfg, patch_info->data.klass, p, &p);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
if (patch_info->data.del_tramp->method) {
encode_value (1, p, &p);
encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
} else {
encode_value (0, p, &p);
}
encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
break;
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
encode_field_info (acfg, patch_info->data.field, p, &p);
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
break;
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
guint32 offset;
/*
* entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
* reference the same klass/method, so encode it only once.
* For patches which refer to got entries, this sharing is done by get_got_offset, but
* these are not got entries.
*/
if (entry->in_mrgctx) {
offset = get_shared_method_ref (acfg, entry->d.method);
} else {
offset = get_shared_klass_ref (acfg, entry->d.klass);
}
encode_value (offset, p, &p);
g_assert ((int)entry->info_type < 256);
g_assert (entry->data->type < 256);
encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
encode_patch (acfg, entry->data, p, &p);
break;
}
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_AOT_MODULE:
break;
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
int i;
encode_method_ref (acfg, info->method, p, &p);
encode_value (info->num_entries, p, &p);
for (i = 0; i < info->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
encode_value (template_->info_type, p, &p);
switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
case MONO_PATCH_INFO_CLASS:
encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
break;
case MONO_PATCH_INFO_FIELD:
encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
break;
case MONO_PATCH_INFO_METHOD:
encode_method_ref (acfg, (MonoMethod*)template_->data, p, &p);
break;
default:
g_assert_not_reached ();
break;
}
}
break;
}
case MONO_PATCH_INFO_VIRT_METHOD:
encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
break;
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
break;
default:
g_error ("unable to handle jump info %d", patch_info->type);
}
*endbuf = p;
}
static void
encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
guint32 pindex, offset;
MonoJumpInfo *patch_info;
encode_value (n_patches, p, &p);
for (pindex = 0; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
/* Nothing to do */
continue;
/* This shouldn't allocate a new offset */
offset = lookup_got_offset (acfg, llvm, patch_info);
encode_value (offset, p, &p);
}
*endbuf = p;
}
static void
emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
{
MonoMethod *method;
int pindex, buf_size, n_patches;
GPtrArray *patches;
MonoJumpInfo *patch_info;
guint8 *p, *buf;
guint32 offset;
gboolean needs_ctx = FALSE;
method = cfg->orig_method;
(void)get_method_index (acfg, method);
/* Sort relocations */
patches = g_ptr_array_new ();
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
g_ptr_array_add (patches, patch_info);
if (!acfg->aot_opts.llvm_only)
g_ptr_array_sort (patches, compare_patches);
/**********************/
/* Encode method info */
/**********************/
guint32 *got_offsets = g_new0 (guint32, patches->len);
n_patches = 0;
for (pindex = 0; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
(patch_info->type == MONO_PATCH_INFO_NONE)) {
patch_info->type = MONO_PATCH_INFO_NONE;
/* Nothing to do */
continue;
}
if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
/* Stored in a GOT slot initialized at module load time */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
/* Stored in a GOT slot initialized at module load time */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
/* Calls are made through the PLT */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
needs_ctx = TRUE;
/* This shouldn't allocate a new offset */
offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
if (offset >= acfg->nshared_got_entries)
got_offsets [n_patches ++] = offset;
}
if (n_patches)
g_assert (cfg->has_got_slots);
buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
p = buf = (guint8 *)g_malloc (buf_size);
MonoGenericContext *ctx = mono_method_get_context (cfg->method);
guint8 flags = 0;
if (mono_class_get_cctor (method->klass))
flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
if (n_patches)
flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
if (needs_ctx && ctx)
flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
if (cfg->interp_entry_only)
flags |= MONO_AOT_METHOD_FLAG_INTERP_ENTRY_ONLY;
/* Saved into another table so it can be accessed without having access to this data */
cfg->aot_method_flags = flags;
encode_int (cfg->method_index, p, &p);
if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
encode_klass_ref (acfg, method->klass, p, &p);
if (needs_ctx && ctx)
encode_generic_context (acfg, ctx, p, &p);
if (n_patches) {
encode_value (n_patches, p, &p);
for (int i = 0; i < n_patches; ++i)
encode_value (got_offsets [i], p, &p);
}
g_ptr_array_free (patches, TRUE);
g_free (got_offsets);
acfg->stats.method_info_size += p - buf;
g_assert (p - buf < buf_size);
if (cfg->compile_llvm) {
char *symbol = g_strdup_printf ("info_%s", cfg->llvm_method_name);
cfg->llvm_info_var = mono_llvm_emit_aot_data_aligned (symbol, buf, p - buf, 1);
g_free (symbol);
/* aot-runtime.c will use this to check whenever this is an llvm method */
cfg->method_info_offset = 0;
} else {
cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
}
g_free (buf);
}
static guint32
get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
{
guint32 cache_index;
guint32 offset;
/* Reuse the unwind module to canonize and store unwind info entries */
cache_index = mono_cache_unwind_info (encoded, encoded_len);
/* Use +/- 1 to distinguish 0s from missing entries */
offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
if (offset)
return offset - 1;
else {
guint8 buf [16];
guint8 *p;
/*
* It would be easier to use assembler symbols, but the caller needs an
* offset now.
*/
offset = acfg->unwind_info_offset;
g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
p = buf;
encode_value (encoded_len, p, &p);
acfg->unwind_info_offset += encoded_len + (p - buf);
return offset;
}
}
static void
emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
{
int i, k, buf_size;
guint32 debug_info_size, seq_points_size;
guint8 *code;
MonoMethodHeader *header;
guint8 *p, *buf, *debug_info;
MonoJitInfo *jinfo = cfg->jit_info;
guint32 flags;
gboolean use_unwind_ops = FALSE;
MonoSeqPointInfo *seq_points;
code = cfg->native_code;
header = cfg->header;
if (!acfg->aot_opts.nodebug) {
mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
} else {
debug_info = NULL;
debug_info_size = 0;
}
seq_points = cfg->seq_point_info;
seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
buf_size += table->num_holes * 16;
}
p = buf = (guint8 *)g_malloc (buf_size);
use_unwind_ops = cfg->unwind_ops != NULL;
flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
encode_value (flags, p, &p);
if (use_unwind_ops) {
guint32 encoded_len;
guint8 *encoded;
guint32 unwind_desc;
encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
encode_value (unwind_desc, p, &p);
g_free (encoded);
} else {
encode_value (jinfo->unwind_info, p, &p);
}
/*Encode the number of holes before the number of clauses to make decoding easier*/
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
encode_value (table->num_holes, p, &p);
}
if (jinfo->has_arch_eh_info) {
/*
* In AOT mode, the code length is calculated from the address of the previous method,
* which could include alignment padding, so calculating the start of the epilog as
* code_len - epilog_size is correct any more. Save the real code len as a workaround.
*/
encode_value (jinfo->code_size, p, &p);
}
/* Exception table */
if (cfg->compile_llvm) {
/*
* When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
* since the information is only available to llc. Instead, we let llc save the data
* into the LSDA, and read it from there at runtime.
*/
/* The assembly might be CIL stripped so emit the data ourselves */
if (header->num_clauses)
encode_value (header->num_clauses, p, &p);
for (k = 0; k < header->num_clauses; ++k) {
MonoExceptionClause *clause;
clause = &header->clauses [k];
encode_value (clause->flags, p, &p);
if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
if (clause->data.catch_class) {
guint8 *buf2, *p2;
int len;
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
} else {
encode_value (0, p, &p);
}
}
/* Emit the IL ranges too, since they might not be available at runtime */
encode_value (clause->try_offset, p, &p);
encode_value (clause->try_len, p, &p);
encode_value (clause->handler_offset, p, &p);
encode_value (clause->handler_len, p, &p);
/* Emit a list of nesting clauses */
for (i = 0; i < header->num_clauses; ++i) {
gint32 cindex1 = k;
MonoExceptionClause *clause1 = &header->clauses [cindex1];
gint32 cindex2 = i;
MonoExceptionClause *clause2 = &header->clauses [cindex2];
if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
encode_value (i, p, &p);
}
encode_value (-1, p, &p);
}
} else {
if (jinfo->num_clauses)
encode_value (jinfo->num_clauses, p, &p);
for (k = 0; k < jinfo->num_clauses; ++k) {
MonoJitExceptionInfo *ei = &jinfo->clauses [k];
encode_value (ei->flags, p, &p);
#ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
/* Not used for catch clauses */
if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
encode_value (ei->exvar_offset, p, &p);
#else
encode_value (ei->exvar_offset, p, &p);
#endif
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
else {
if (ei->data.catch_class) {
guint8 *buf2, *p2;
int len;
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
} else {
encode_value (0, p, &p);
}
}
encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
}
}
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
for (i = 0; i < table->num_holes; ++i) {
MonoTryBlockHoleJitInfo *hole = &table->holes [i];
encode_value (hole->clause, p, &p);
encode_value (hole->length, p, &p);
encode_value (hole->offset, p, &p);
}
}
if (jinfo->has_arch_eh_info) {
MonoArchEHJitInfo *eh_info;
eh_info = mono_jit_info_get_arch_eh_info (jinfo);
encode_value (eh_info->stack_size, p, &p);
encode_value (eh_info->epilog_size, p, &p);
}
if (jinfo->has_generic_jit_info) {
MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
guint8 *buf2, *p2;
int len;
encode_value (gi->nlocs, p, &p);
if (gi->nlocs) {
for (i = 0; i < gi->nlocs; ++i) {
MonoDwarfLocListEntry *entry = &gi->locations [i];
encode_value (entry->is_reg ? 1 : 0, p, &p);
encode_value (entry->reg, p, &p);
if (!entry->is_reg)
encode_value (entry->offset, p, &p);
if (i == 0)
g_assert (entry->from == 0);
else
encode_value (entry->from, p, &p);
encode_value (entry->to, p, &p);
}
} else {
if (!cfg->compile_llvm) {
encode_value (gi->has_this ? 1 : 0, p, &p);
encode_value (gi->this_reg, p, &p);
encode_value (gi->this_offset, p, &p);
}
}
/*
* Need to encode jinfo->method too, since it is not equal to 'method'
* when using generic sharing.
*/
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_method_ref (acfg, jinfo->d.method, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
if (gsctx && gsctx->is_gsharedvt) {
encode_value (1, p, &p);
} else {
encode_value (0, p, &p);
}
}
if (seq_points_size)
p += mono_seq_point_info_write (seq_points, p);
g_assert (debug_info_size < buf_size);
encode_value (debug_info_size, p, &p);
if (debug_info_size) {
memcpy (p, debug_info, debug_info_size);
p += debug_info_size;
g_free (debug_info);
}
/* GC Map */
if (cfg->gc_map) {
encode_value (cfg->gc_map_size, p, &p);
/* The GC map requires 4 bytes of alignment */
while ((gsize)p % 4)
p ++;
memcpy (p, cfg->gc_map, cfg->gc_map_size);
p += cfg->gc_map_size;
}
acfg->stats.ex_info_size += p - buf;
g_assert (p - buf < buf_size);
/* Emit info */
/* The GC Map requires 4 byte alignment */
cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
g_free (buf);
}
static guint32
emit_klass_info (MonoAotCompile *acfg, guint32 token)
{
ERROR_DECL (error);
MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
guint8 *p, *buf;
int i, buf_size, res;
gboolean no_special_static, cant_encode;
gpointer iter = NULL;
if (!klass) {
mono_error_cleanup (error);
buf_size = 16;
p = buf = (guint8 *)g_malloc (buf_size);
/* Mark as unusable */
encode_value (-1, p, &p);
res = add_to_blob (acfg, buf, p - buf);
g_free (buf);
return res;
}
buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
p = buf = (guint8 *)g_malloc (buf_size);
g_assert (klass);
mono_class_init_internal (klass);
mono_class_get_nested_types (klass, &iter);
g_assert (m_class_is_nested_classes_inited (klass));
mono_class_setup_vtable (klass);
/*
* Emit all the information which is required for creating vtables so
* the runtime does not need to create the MonoMethod structures which
* take up a lot of space.
*/
no_special_static = !mono_class_has_special_static_fields (klass);
/* Check whenever we have enough info to encode the vtable */
cant_encode = FALSE;
MonoMethod **klass_vtable = m_class_get_vtable (klass);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm = klass_vtable [i];
if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
cant_encode = TRUE;
}
mono_class_has_finalizer (klass);
if (mono_class_has_failure (klass))
cant_encode = TRUE;
if (mono_class_is_gtd (klass) || cant_encode) {
encode_value (-1, p, &p);
} else {
gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
encode_value (m_class_get_vtable_size (klass), p, &p);
encode_value ((m_class_has_weak_fields (klass) << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (m_class_has_static_refs (klass) << 6) | (m_class_has_references (klass) << 5) | ((m_class_is_blittable (klass) << 4) | (has_nested ? 1 : 0) << 3) | (m_class_has_cctor (klass) << 2) | (m_class_has_finalize (klass) << 1) | m_class_is_ghcimpl (klass), p, &p);
if (m_class_has_cctor (klass))
encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
if (m_class_has_finalize (klass))
encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
encode_value (m_class_get_instance_size (klass), p, &p);
encode_value (mono_class_data_size (klass), p, &p);
encode_value (m_class_get_packing_size (klass), p, &p);
encode_value (m_class_get_min_align (klass), p, &p);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm = klass_vtable [i];
if (cm)
encode_method_ref (acfg, cm, p, &p);
else
encode_value (0, p, &p);
}
}
acfg->stats.class_info_size += p - buf;
g_assert (p - buf < buf_size);
res = add_to_blob (acfg, buf, p - buf);
g_free (buf);
return res;
}
static char*
get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
{
char *debug_sym = NULL;
char *prefix;
if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
/* Need to add a prefix to create unique symbols */
prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
} else {
#if defined(TARGET_WIN32) && defined(TARGET_X86)
prefix = mangle_symbol_alloc ("plt_");
#else
prefix = g_strdup ("plt_");
#endif
}
switch (ji->type) {
case MONO_PATCH_INFO_METHOD:
debug_sym = get_debug_sym (ji->data.method, prefix, cache);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
break;
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
char *s = get_debug_sym (ji->data.method, "", cache);
debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
g_free (s);
break;
}
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, (gulong)ji->data.uindex);
break;
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
default:
break;
}
g_free (prefix);
return sanitize_symbol (acfg, debug_sym);
}
/*
* Calls made from AOTed code are routed through a table of jumps similar to the
* ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
* control to the AOT runtime through a trampoline.
*/
static void
emit_plt (MonoAotCompile *acfg)
{
int i;
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->plt_offset == 1);
return;
}
emit_line (acfg);
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 16);
emit_info_symbol (acfg, "plt", TRUE);
emit_label (acfg, acfg->plt_symbol);
for (i = 0; i < acfg->plt_offset; ++i) {
char *debug_sym = NULL;
MonoPltEntry *plt_entry = NULL;
if (i == 0)
/*
* The first plt entry is unused.
*/
continue;
plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
debug_sym = plt_entry->debug_sym;
if (acfg->thumb_mixed && !plt_entry->jit_used)
/* Emit only a thumb version */
continue;
/* Skip plt entries not actually called */
if (!plt_entry->jit_used && !plt_entry->llvm_used)
continue;
if (acfg->llvm && !acfg->thumb_mixed) {
emit_label (acfg, plt_entry->llvm_symbol);
if (acfg->llvm) {
emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
#if defined(TARGET_MACH)
fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
#endif
}
}
if (debug_sym) {
if (acfg->need_no_dead_strip) {
emit_unset_mode (acfg);
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
}
emit_local_symbol (acfg, debug_sym, NULL, TRUE);
emit_label (acfg, debug_sym);
}
emit_label (acfg, plt_entry->symbol);
arch_emit_plt_entry (acfg, acfg->got_symbol, i, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
if (debug_sym)
emit_symbol_size (acfg, debug_sym, ".");
}
if (acfg->thumb_mixed) {
/* Make sure the ARM symbols don't alias the thumb ones */
emit_zero_bytes (acfg, 16);
/*
* Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
* code.
*/
for (i = 0; i < acfg->plt_offset; ++i) {
char *debug_sym = NULL;
MonoPltEntry *plt_entry = NULL;
if (i == 0)
continue;
plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
/* Skip plt entries not actually called by LLVM code */
if (!plt_entry->llvm_used)
continue;
if (acfg->aot_opts.write_symbols) {
if (plt_entry->debug_sym)
debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
}
if (debug_sym) {
#if defined(TARGET_MACH)
fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
#endif
emit_local_symbol (acfg, debug_sym, NULL, TRUE);
emit_label (acfg, debug_sym);
}
fprintf (acfg->fp, "\n.thumb_func\n");
emit_label (acfg, plt_entry->llvm_symbol);
if (acfg->llvm)
emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, i, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
if (debug_sym) {
emit_symbol_size (acfg, debug_sym, ".");
g_free (debug_sym);
}
}
}
emit_symbol_size (acfg, acfg->plt_symbol, ".");
emit_info_symbol (acfg, "plt_end", TRUE);
arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
}
/*
* emit_trampoline_full:
*
* If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
* create_jit_info_for_trampoline ().
*/
static G_GNUC_UNUSED void
emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
{
char start_symbol [MAX_SYMBOL_SIZE];
char end_symbol [MAX_SYMBOL_SIZE];
char symbol [MAX_SYMBOL_SIZE];
guint32 buf_size, info_offset;
MonoJumpInfo *patch_info;
guint8 *buf, *p;
GPtrArray *patches;
char *name;
guint8 *code;
guint32 code_size;
MonoJumpInfo *ji;
GSList *unwind_ops;
g_assert (info);
name = info->name;
code = (guint8*)MINI_FTNPTR_TO_ADDR (info->code);
code_size = info->code_size;
ji = info->ji;
unwind_ops = info->unwind_ops;
/* Emit code */
sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
emit_section_change (acfg, ".text", 0);
emit_global (acfg, start_symbol, TRUE);
emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
emit_label (acfg, start_symbol);
sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
emit_label (acfg, symbol);
/*
* The code should access everything through the GOT, so we pass
* TRUE here.
*/
emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
emit_symbol_size (acfg, start_symbol, ".");
if (emit_tinfo) {
sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
emit_label (acfg, end_symbol);
}
/* Emit info */
/* Sort relocations */
patches = g_ptr_array_new ();
for (patch_info = ji; patch_info; patch_info = patch_info->next)
if (patch_info->type != MONO_PATCH_INFO_NONE)
g_ptr_array_add (patches, patch_info);
g_ptr_array_sort (patches, compare_patches);
buf_size = patches->len * 128 + 128;
buf = (guint8 *)g_malloc (buf_size);
p = buf;
encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
g_assert (p - buf < buf_size);
g_ptr_array_free (patches, TRUE);
sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
info_offset = add_to_blob (acfg, buf, p - buf);
emit_section_change (acfg, RODATA_SECT, 0);
emit_global (acfg, symbol, FALSE);
emit_label (acfg, symbol);
emit_int32 (acfg, info_offset);
if (emit_tinfo) {
guint8 *encoded;
guint32 encoded_len;
guint32 uw_offset;
/*
* Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
*/
encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
g_free (encoded);
emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
emit_int32 (acfg, uw_offset);
}
/* Emit debug info */
if (unwind_ops) {
char symbol2 [MAX_SYMBOL_SIZE];
sprintf (symbol, "%s", name);
sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
if (acfg->dwarf)
mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
}
g_free (buf);
}
static G_GNUC_UNUSED void
emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
{
emit_trampoline_full (acfg, info, TRUE);
}
static void
emit_trampolines (MonoAotCompile *acfg)
{
char symbol [MAX_SYMBOL_SIZE];
char end_symbol [MAX_SYMBOL_SIZE + 2];
int i, tramp_got_offset;
int ntype;
#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
int tramp_type;
#endif
if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
return;
if (acfg->aot_opts.llvm_only)
return;
g_assert (acfg->image->assembly);
/* Currently, we emit most trampolines into the mscorlib AOT image. */
if (mono_is_corlib_image(acfg->image->assembly->image)) {
#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
MonoTrampInfo *info;
/*
* Emit the generic trampolines.
*
* We could save some code by treating the generic trampolines as a wrapper
* method, but that approach has its own complexities, so we choose the simpler
* method.
*/
for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
/* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
}
/* Emit the exception related code pieces */
mono_arch_get_restore_context (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_call_filter (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_throw_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_rethrow_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_rethrow_preserve_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_throw_corlib_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#endif
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
mono_arch_get_gsharedvt_trampoline (&info, TRUE);
if (info) {
emit_trampoline_full (acfg, info, TRUE);
/* Create a separate out trampoline for more information in stack traces */
info->name = g_strdup ("gsharedvt_out_trampoline");
emit_trampoline_full (acfg, info, TRUE);
mono_tramp_info_free (info);
}
#endif
#if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
{
GSList *l = mono_arch_get_trampolines (TRUE);
while (l) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
emit_trampoline (acfg, info);
l = l->next;
}
}
#endif
for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
int offset;
offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
}
#ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#endif
{
GSList *l;
/* delegate_invoke_impl trampolines */
l = mono_arch_get_delegate_invoke_impls ();
while (l) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
emit_trampoline (acfg, info);
l = l->next;
}
}
if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
mono_arch_get_interp_to_native_trampoline (&info);
emit_trampoline (acfg, info);
#ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
mono_arch_get_native_to_interp_trampoline (&info);
emit_trampoline (acfg, info);
#endif
}
#endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
/* Emit trampolines which are numerous */
/*
* These include the following:
* - specific trampolines
* - static rgctx invoke trampolines
* - imt trampolines
* These trampolines have the same code, they are parameterized by GOT
* slots.
* They are defined in this file, in the arch_... routines instead of
* in tramp-<ARCH>.c, since it is easier to do it this way.
*/
/*
* When running in aot-only mode, we can't create specific trampolines at
* runtime, so we create a few, and save them in the AOT file.
* Normal trampolines embed their argument as a literal inside the
* trampoline code, we can't do that here, so instead we embed an offset
* which needs to be added to the trampoline address to get the address of
* the GOT slot which contains the argument value.
* The generated trampolines jump to the generic trampolines using another
* GOT slot, which will be setup by the AOT loader to point to the
* generic trampoline code of the given type.
*/
/*
* FIXME: Maybe we should use more specific trampolines (i.e. one class init for
* each class).
*/
emit_section_change (acfg, ".text", 0);
tramp_got_offset = acfg->got_offset;
for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
switch (ntype) {
case MONO_AOT_TRAMP_SPECIFIC:
sprintf (symbol, "specific_trampolines");
break;
case MONO_AOT_TRAMP_STATIC_RGCTX:
sprintf (symbol, "static_rgctx_trampolines");
break;
case MONO_AOT_TRAMP_IMT:
sprintf (symbol, "imt_trampolines");
break;
case MONO_AOT_TRAMP_GSHAREDVT_ARG:
sprintf (symbol, "gsharedvt_arg_trampolines");
break;
case MONO_AOT_TRAMP_FTNPTR_ARG:
sprintf (symbol, "ftnptr_arg_trampolines");
break;
case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
sprintf (symbol, "unbox_arbitrary_trampolines");
break;
default:
g_assert_not_reached ();
}
sprintf (end_symbol, "%s_e", symbol);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, end_symbol, TRUE);
emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
emit_info_symbol (acfg, symbol, TRUE);
acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
int tramp_size = 0;
switch (ntype) {
case MONO_AOT_TRAMP_SPECIFIC:
arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_STATIC_RGCTX:
arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_IMT:
arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 1;
break;
case MONO_AOT_TRAMP_GSHAREDVT_ARG:
arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_FTNPTR_ARG:
arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 1;
break;
default:
g_assert_not_reached ();
}
if (!acfg->trampoline_size [ntype]) {
g_assert (tramp_size);
acfg->trampoline_size [ntype] = tramp_size;
}
}
emit_label (acfg, end_symbol);
emit_int32 (acfg, 0);
}
arch_emit_specific_trampoline_pages (acfg);
/* Reserve some entries at the end of the GOT for our use */
acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
}
acfg->got_offset += acfg->num_trampoline_got_entries;
}
static gboolean
str_begins_with (const char *str1, const char *str2)
{
int len = strlen (str2);
return strncmp (str1, str2, len) == 0;
}
void*
mono_aot_readonly_field_override (MonoClassField *field)
{
ReadOnlyValue *rdv;
for (rdv = readonly_values; rdv; rdv = rdv->next) {
char *p = rdv->name;
int len;
MonoClass *field_parent = m_field_get_parent (field);
len = strlen (m_class_get_name_space (field_parent));
if (strncmp (p, m_class_get_name_space (field_parent), len))
continue;
p += len;
if (*p++ != '.')
continue;
len = strlen (m_class_get_name (field_parent));
if (strncmp (p, m_class_get_name (field_parent), len))
continue;
p += len;
if (*p++ != '.')
continue;
if (strcmp (p, field->name))
continue;
switch (rdv->type) {
case MONO_TYPE_I1:
return &rdv->value.i1;
case MONO_TYPE_I2:
return &rdv->value.i2;
case MONO_TYPE_I4:
return &rdv->value.i4;
default:
break;
}
}
return NULL;
}
static void
add_readonly_value (MonoAotOptions *opts, const char *val)
{
ReadOnlyValue *rdv;
const char *fval;
const char *tval;
/* the format of val is:
* namespace.typename.fieldname=type/value
* type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
*/
fval = strrchr (val, '/');
if (!fval) {
fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
exit (1);
}
tval = strrchr (val, '=');
if (!tval) {
fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
exit (1);
}
rdv = g_new0 (ReadOnlyValue, 1);
rdv->name = (char *)g_malloc0 (tval - val + 1);
memcpy (rdv->name, val, tval - val);
tval++;
fval++;
if (strncmp (tval, "i1", 2) == 0) {
rdv->value.i1 = atoi (fval);
rdv->type = MONO_TYPE_I1;
} else if (strncmp (tval, "i2", 2) == 0) {
rdv->value.i2 = atoi (fval);
rdv->type = MONO_TYPE_I2;
} else if (strncmp (tval, "i4", 2) == 0) {
rdv->value.i4 = atoi (fval);
rdv->type = MONO_TYPE_I4;
} else {
fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
exit (1);
}
rdv->next = readonly_values;
readonly_values = rdv;
}
static gchar *
clean_path (gchar * path)
{
if (!path)
return NULL;
if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
return path;
gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, (const char*)NULL);
g_free (path);
return clean;
}
static const gchar *
wrap_path (const gchar * path)
{
int len;
if (!path)
return NULL;
// If the string contains no spaces, just return the original string.
if (strstr (path, " ") == NULL)
return path;
// If the string is already wrapped in quotes, return it.
len = strlen (path);
if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
return path;
// If the string contains spaces, then wrap it in quotes.
gchar *clean = g_strdup_printf ("\"%s\"", path);
return clean;
}
// Duplicate a char range and add it to a ptrarray, but only if it is nonempty
static void
ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
{
ptrdiff_t len = end-start;
if (len > 0)
g_ptr_array_add (args, g_strndup (start, len));
}
static GPtrArray *
mono_aot_split_options (const char *aot_options)
{
enum MonoAotOptionState {
MONO_AOT_OPTION_STATE_DEFAULT,
MONO_AOT_OPTION_STATE_STRING,
MONO_AOT_OPTION_STATE_ESCAPE,
};
GPtrArray *args = g_ptr_array_new ();
enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
gchar const *opt_start = aot_options;
gboolean end_of_string = FALSE;
gchar cur;
g_return_val_if_fail (aot_options != NULL, NULL);
while ((cur = *aot_options) != '\0') {
if (state == MONO_AOT_OPTION_STATE_ESCAPE)
goto next;
switch (cur) {
case '"':
// If we find a quote, then if we're in the default case then
// it means we've found the start of a string, if not then it
// means we've found the end of the string and should switch
// back to the default case.
switch (state) {
case MONO_AOT_OPTION_STATE_DEFAULT:
state = MONO_AOT_OPTION_STATE_STRING;
break;
case MONO_AOT_OPTION_STATE_STRING:
state = MONO_AOT_OPTION_STATE_DEFAULT;
break;
case MONO_AOT_OPTION_STATE_ESCAPE:
g_assert_not_reached ();
break;
}
break;
case '\\':
// If we've found an escaping operator, then this means we
// should not process the next character if inside a string.
if (state == MONO_AOT_OPTION_STATE_STRING)
state = MONO_AOT_OPTION_STATE_ESCAPE;
break;
case ',':
// If we're in the default state then this means we've found
// an option, store it for later processing.
if (state == MONO_AOT_OPTION_STATE_DEFAULT)
goto new_opt;
break;
}
next:
aot_options++;
restart:
// If the next character is end of string, then process the last option.
if (*(aot_options) == '\0') {
end_of_string = TRUE;
goto new_opt;
}
continue;
new_opt:
ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
opt_start = ++aot_options;
if (end_of_string)
break;
goto restart; // Check for null and continue loop
}
return args;
}
static gboolean
parse_cpu_features (const gchar *attr)
{
if (!attr || strlen (attr) < 2) {
fprintf (stderr, "Invalid attribute");
return FALSE;
}
//+foo - enable foo
//foo - enable foo
//-foo - disable foo
gboolean enabled = TRUE;
if (attr [0] == '-')
enabled = FALSE;
int prefix = (attr [0] == '-' || attr [0] == '+') ? 1 : 0;
MonoCPUFeatures feature = (MonoCPUFeatures) 0;
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// e.g.:
// `mattr=+sse3` = +sse,+sse2,+sse3
// `mattr=-sse3` = -sse3,-ssse3,-sse4.1,-sse4.2,-popcnt,-avx,-avx2,-fma
if (!strcmp (attr + prefix, "sse"))
feature = MONO_CPU_X86_SSE_COMBINED;
else if (!strcmp (attr + prefix, "sse2"))
feature = MONO_CPU_X86_SSE2_COMBINED;
else if (!strcmp (attr + prefix, "sse3"))
feature = MONO_CPU_X86_SSE3_COMBINED;
else if (!strcmp (attr + prefix, "ssse3"))
feature = MONO_CPU_X86_SSSE3_COMBINED;
else if (!strcmp (attr + prefix, "sse4.1"))
feature = MONO_CPU_X86_SSE41_COMBINED;
else if (!strcmp (attr + prefix, "sse4.2"))
feature = MONO_CPU_X86_SSE42_COMBINED;
else if (!strcmp (attr + prefix, "avx"))
feature = MONO_CPU_X86_AVX_COMBINED;
else if (!strcmp (attr + prefix, "avx2"))
feature = MONO_CPU_X86_AVX2_COMBINED;
else if (!strcmp (attr + prefix, "pclmul"))
feature = MONO_CPU_X86_PCLMUL_COMBINED;
else if (!strcmp (attr + prefix, "aes"))
feature = MONO_CPU_X86_AES_COMBINED;
else if (!strcmp (attr + prefix, "popcnt"))
feature = MONO_CPU_X86_POPCNT_COMBINED;
else if (!strcmp (attr + prefix, "fma"))
feature = MONO_CPU_X86_FMA_COMBINED;
// these are independent
else if (!strcmp (attr + prefix, "lzcnt")) // technically, it'a a part of BMI but only on Intel
feature = MONO_CPU_X86_LZCNT;
else if (!strcmp (attr + prefix, "bmi")) // NOTE: it's not "bmi1"
feature = MONO_CPU_X86_BMI1;
else if (!strcmp (attr + prefix, "bmi2"))
feature = MONO_CPU_X86_BMI2; // BMI2 doesn't imply BMI1
else {
// we don't have a flag for it but it's probably recognized by opt/llc so let's don't fire an error here
// printf ("Unknown cpu feature: %s\n", attr);
}
// if we disable a feature from the SSE-AVX tree we also need to disable all dependencies
if (!enabled && (feature & MONO_CPU_X86_FULL_SSEAVX_COMBINED))
feature = (MonoCPUFeatures) (MONO_CPU_X86_FULL_SSEAVX_COMBINED & ~feature);
#elif defined(TARGET_ARM64)
// MONO_CPU_ARM64_BASE is unconditionally set in mini_get_cpu_features.
if (!strcmp (attr + prefix, "crc"))
feature = MONO_CPU_ARM64_CRC;
else if (!strcmp (attr + prefix, "crypto"))
feature = MONO_CPU_ARM64_CRYPTO;
else if (!strcmp (attr + prefix, "neon"))
feature = MONO_CPU_ARM64_NEON;
else if (!strcmp (attr + prefix, "rdm"))
feature = MONO_CPU_ARM64_RDM;
else if (!strcmp (attr + prefix, "dotprod"))
feature = MONO_CPU_ARM64_DP;
#elif defined(TARGET_WASM)
if (!strcmp (attr + prefix, "simd"))
feature = MONO_CPU_WASM_SIMD;
#else
(void)prefix; // unused
#endif
if (enabled)
mono_cpu_features_enabled = (MonoCPUFeatures) (mono_cpu_features_enabled | feature);
else
mono_cpu_features_disabled = (MonoCPUFeatures) (mono_cpu_features_disabled | feature);
return TRUE;
}
static void
mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
{
GPtrArray* args;
args = mono_aot_split_options (aot_options ? aot_options : "");
for (int i = 0; i < args->len; ++i) {
const char *arg = (const char *)g_ptr_array_index (args, i);
if (str_begins_with (arg, "outfile=")) {
opts->outfile = g_strdup (arg + strlen ("outfile="));
} else if (str_begins_with (arg, "llvm-outfile=")) {
opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
} else if (str_begins_with (arg, "temp-path=")) {
opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
} else if (str_begins_with (arg, "save-temps")) {
opts->save_temps = TRUE;
} else if (str_begins_with (arg, "keep-temps")) {
opts->save_temps = TRUE;
} else if (str_begins_with (arg, "write-symbols")) {
opts->write_symbols = TRUE;
} else if (str_begins_with (arg, "no-write-symbols")) {
opts->write_symbols = FALSE;
// Intentionally undocumented -- one-off experiment
} else if (str_begins_with (arg, "metadata-only")) {
opts->metadata_only = TRUE;
} else if (str_begins_with (arg, "bind-to-runtime-version")) {
opts->bind_to_runtime_version = TRUE;
} else if (str_begins_with (arg, "full")) {
opts->mode = MONO_AOT_MODE_FULL;
} else if (str_begins_with (arg, "hybrid")) {
opts->mode = MONO_AOT_MODE_HYBRID;
} else if (str_begins_with (arg, "interp")) {
opts->interp = TRUE;
} else if (str_begins_with (arg, "threads=")) {
opts->nthreads = atoi (arg + strlen ("threads="));
} else if (str_begins_with (arg, "static")) {
opts->static_link = TRUE;
opts->no_dlsym = TRUE;
} else if (str_begins_with (arg, "asmonly")) {
opts->asm_only = TRUE;
} else if (str_begins_with (arg, "asmwriter")) {
opts->asm_writer = TRUE;
} else if (str_begins_with (arg, "nodebug")) {
opts->nodebug = TRUE;
} else if (str_begins_with (arg, "dwarfdebug")) {
opts->dwarf_debug = TRUE;
// Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
} else if (str_begins_with (arg, "nopagetrampolines")) {
opts->use_trampolines_page = FALSE;
} else if (str_begins_with (arg, "ntrampolines=")) {
opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
} else if (str_begins_with (arg, "nrgctx-trampolines=")) {
opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
} else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
} else if (str_begins_with (arg, "nimt-trampolines=")) {
opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
} else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
} else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
} else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
} else if (str_begins_with (arg, "tool-prefix=")) {
opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
} else if (str_begins_with (arg, "ld-flags=")) {
opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
} else if (str_begins_with (arg, "ld-name=")) {
opts->ld_name = g_strdup (arg + strlen ("ld-name="));
} else if (str_begins_with (arg, "soft-debug")) {
opts->soft_debug = TRUE;
// Intentionally undocumented x2-- deprecated
} else if (str_begins_with (arg, "gen-seq-points-file=")) {
fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
} else if (str_begins_with (arg, "gen-seq-points-file")) {
fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
} else if (str_begins_with (arg, "msym-dir=")) {
mini_debug_options.no_seq_points_compact_data = FALSE;
opts->gen_msym_dir = TRUE;
opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
} else if (str_begins_with (arg, "direct-pinvoke")) {
opts->direct_pinvoke = TRUE;
} else if (str_begins_with (arg, "direct-icalls")) {
opts->direct_icalls = TRUE;
} else if (str_begins_with (arg, "direct-extern-calls")) {
opts->direct_extern_calls = TRUE;
} else if (str_begins_with (arg, "no-direct-calls")) {
opts->no_direct_calls = TRUE;
} else if (str_begins_with (arg, "print-skipped")) {
opts->print_skipped_methods = TRUE;
} else if (str_begins_with (arg, "stats")) {
opts->stats = TRUE;
// Intentionally undocumented-- has no known function other than to debug the compiler
} else if (str_begins_with (arg, "no-instances")) {
opts->no_instances = TRUE;
// Intentionally undocumented x4-- Used for internal debugging of compiler
} else if (str_begins_with (arg, "log-generics")) {
opts->log_generics = TRUE;
} else if (str_begins_with (arg, "log-instances=")) {
opts->log_instances = TRUE;
opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
} else if (str_begins_with (arg, "log-instances")) {
opts->log_instances = TRUE;
} else if (str_begins_with (arg, "internal-logfile=")) {
opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
} else if (str_begins_with (arg, "dedup-skip")) {
opts->dedup = TRUE;
} else if (str_begins_with (arg, "dedup-include=")) {
opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
} else if (str_begins_with (arg, "mtriple=")) {
opts->mtriple = g_strdup (arg + strlen ("mtriple="));
} else if (str_begins_with (arg, "llvm-path=")) {
opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
} else if (!strcmp (arg, "try-llvm")) {
// If we can load LLVM, use it
// Note: if you call this function from anywhere but mono_compile_assembly,
// this will only set the try_llvm attribute and not do the probing / set the
// attribute.
opts->try_llvm = TRUE;
} else if (!strcmp (arg, "llvm")) {
opts->llvm = TRUE;
} else if (str_begins_with (arg, "readonly-value=")) {
add_readonly_value (opts, arg + strlen ("readonly-value="));
} else if (str_begins_with (arg, "info")) {
printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
exit (0);
// Intentionally undocumented: Used for precise stack maps, which are not available yet
} else if (str_begins_with (arg, "gc-maps")) {
mini_gc_enable_gc_maps_for_aot ();
// Intentionally undocumented: Used for internal debugging
} else if (str_begins_with (arg, "dump")) {
opts->dump_json = TRUE;
} else if (str_begins_with (arg, "llvmonly")) {
opts->mode = MONO_AOT_MODE_FULL;
opts->llvm = TRUE;
opts->llvm_only = TRUE;
} else if (str_begins_with (arg, "data-outfile=")) {
opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
} else if (str_begins_with (arg, "profile=")) {
opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
} else if (!strcmp (arg, "profile-only")) {
opts->profile_only = TRUE;
} else if (!strcmp (arg, "verbose")) {
opts->verbose = TRUE;
} else if (!strcmp (arg, "allow-errors")) {
opts->allow_errors = TRUE;
} else if (str_begins_with (arg, "llvmopts=")){
if (opts->llvm_opts) {
char *s = g_strdup_printf ("%s %s", opts->llvm_opts, arg + strlen ("llvmopts="));
g_free (opts->llvm_opts);
opts->llvm_opts = s;
} else {
opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
}
} else if (str_begins_with (arg, "llvmllc=")){
opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
} else if (!strcmp (arg, "deterministic")) {
opts->deterministic = TRUE;
} else if (!strcmp (arg, "no-opt")) {
opts->no_opt = TRUE;
} else if (str_begins_with (arg, "clangxx=")) {
opts->clangxx = g_strdup (arg + strlen ("clangxx="));
} else if (str_begins_with (arg, "mcpu=")) {
if (!strcmp(arg, "mcpu=native")) {
opts->use_current_cpu = TRUE;
} else if (!strcmp(arg, "mcpu=generic")) {
opts->use_current_cpu = FALSE;
} else {
printf ("mcpu can only be 'native' or 'generic' (default).\n");
exit (0);
}
} else if (str_begins_with (arg, "mattr=")) {
gchar* attr = g_strdup (arg + strlen ("mattr="));
if (!parse_cpu_features (attr))
exit (0);
// mattr can be declared more than once, e.g.
// `mattr=avx2,mattr=lzcnt,mattr=bmi2`
if (!opts->llvm_cpu_attr)
opts->llvm_cpu_attr = attr;
else {
char* old_attrs = opts->llvm_cpu_attr;
opts->llvm_cpu_attr = g_strdup_printf ("%s,%s", opts->llvm_cpu_attr, attr);
g_free (old_attrs);
}
} else if (str_begins_with (arg, "depfile=")) {
opts->depfile = g_strdup (arg + strlen ("depfile="));
} else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
printf ("Supported options for --aot:\n");
printf (" asmonly\n");
printf (" bind-to-runtime-version\n");
printf (" bitcode\n");
printf (" data-outfile=\n");
printf (" direct-icalls\n");
printf (" direct-pinvoke\n");
printf (" dwarfdebug\n");
printf (" full\n");
printf (" hybrid\n");
printf (" info\n");
printf (" keep-temps\n");
printf (" llvm\n");
printf (" llvmonly\n");
printf (" llvm-outfile=\n");
printf (" llvm-path=\n");
printf (" msym-dir=\n");
printf (" mtriple\n");
printf (" nimt-trampolines=\n");
printf (" nodebug\n");
printf (" no-direct-calls\n");
printf (" no-write-symbols\n");
printf (" nrgctx-trampolines=\n");
printf (" nrgctx-fetch-trampolines=\n");
printf (" ngsharedvt-trampolines=\n");
printf (" nftnptr-arg-trampolines=\n");
printf (" nunbox-arbitrary-trampolines=\n");
printf (" ntrampolines=\n");
printf (" outfile=\n");
printf (" profile=\n");
printf (" profile-only\n");
printf (" print-skipped-methods\n");
printf (" readonly-value=\n");
printf (" save-temps\n");
printf (" soft-debug\n");
printf (" static\n");
printf (" stats\n");
printf (" temp-path=\n");
printf (" tool-prefix=\n");
printf (" threads=\n");
printf (" write-symbols\n");
printf (" verbose\n");
printf (" allow-errors\n");
printf (" no-opt\n");
printf (" llvmopts=\n");
printf (" llvmllc=\n");
printf (" clangxx=\n");
printf (" depfile=\n");
printf (" mcpu=\n");
printf (" mattr=\n");
printf (" help/?\n");
exit (0);
} else {
fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
exit (1);
}
g_free ((gpointer) arg);
}
if (opts->use_trampolines_page) {
opts->ntrampolines = 0;
opts->nrgctx_trampolines = 0;
opts->nimt_trampolines = 0;
opts->ngsharedvt_arg_trampolines = 0;
opts->nftnptr_arg_trampolines = 0;
opts->nunbox_arbitrary_trampolines = 0;
}
g_ptr_array_free (args, /*free_seg=*/TRUE);
}
static void
add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
{
MonoMethod *method = (MonoMethod*)key;
MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
MonoAotCompile *acfg = (MonoAotCompile *)user_data;
MonoJumpInfoToken *new_ji;
new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
new_ji->image = ji->image;
new_ji->token = ji->token;
g_hash_table_insert (acfg->token_info_hash, method, new_ji);
}
static gboolean
can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
{
if (m_class_get_type_token (klass))
return TRUE;
if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR))
return TRUE;
if (m_class_get_rank (klass))
return can_encode_class (acfg, m_class_get_element_class (klass));
return FALSE;
}
static gboolean
can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
{
if (method->wrapper_type) {
switch (method->wrapper_type) {
case MONO_WRAPPER_NONE:
case MONO_WRAPPER_STELEMREF:
case MONO_WRAPPER_ALLOC:
case MONO_WRAPPER_OTHER:
case MONO_WRAPPER_WRITE_BARRIER:
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE:
case MONO_WRAPPER_SYNCHRONIZED:
case MONO_WRAPPER_MANAGED_TO_NATIVE:
break;
case MONO_WRAPPER_MANAGED_TO_MANAGED:
case MONO_WRAPPER_NATIVE_TO_MANAGED:
case MONO_WRAPPER_CASTCLASS: {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info)
return TRUE;
else
return FALSE;
break;
}
default:
//printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
return FALSE;
}
} else {
if (!method->token) {
/* The method is part of a constructed type like Int[,].Set (). */
if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
if (m_class_get_rank (method->klass))
return TRUE;
return FALSE;
}
}
}
return TRUE;
}
static gboolean
can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
{
switch (patch_info->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
MonoMethod *method = patch_info->data.method;
return can_encode_method (acfg, method);
}
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
if (!can_encode_class (acfg, patch_info->data.klass)) {
//printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
return FALSE;
}
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
//printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
return FALSE;
}
break;
}
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
if (entry->in_mrgctx) {
if (!can_encode_method (acfg, entry->d.method))
return FALSE;
} else {
if (!can_encode_class (acfg, entry->d.klass))
return FALSE;
}
if (!can_encode_patch (acfg, entry->data))
return FALSE;
break;
}
default:
break;
}
return TRUE;
}
static gboolean
is_concrete_type (MonoType *t)
{
MonoClass *klass;
int i;
if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
return FALSE;
if (t->type == MONO_TYPE_GENERICINST) {
MonoGenericContext *orig_ctx;
MonoGenericInst *inst;
MonoType *arg;
if (!MONO_TYPE_ISSTRUCT (t))
return TRUE;
klass = mono_class_from_mono_type_internal (t);
orig_ctx = &mono_class_get_generic_class (klass)->context;
inst = orig_ctx->class_inst;
if (inst) {
for (i = 0; i < inst->type_argc; ++i) {
arg = mini_get_underlying_type (inst->type_argv [i]);
if (!is_concrete_type (arg))
return FALSE;
}
}
inst = orig_ctx->method_inst;
if (inst) {
for (i = 0; i < inst->type_argc; ++i) {
arg = mini_get_underlying_type (inst->type_argv [i]);
if (!is_concrete_type (arg))
return FALSE;
}
}
}
return TRUE;
}
static MonoMethodSignature*
get_concrete_sig (MonoMethodSignature *sig)
{
gboolean concrete = TRUE;
if (!sig->has_type_parameters)
return sig;
/* For signatures created during generic sharing, convert them to a concrete signature if possible */
MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
int i;
//printf ("%s\n", mono_signature_full_name (sig));
if (m_type_is_byref (sig->ret))
copy->ret = mono_class_get_byref_type (mono_defaults.int_class);
else
copy->ret = mini_get_underlying_type (sig->ret);
if (!is_concrete_type (copy->ret))
concrete = FALSE;
for (i = 0; i < sig->param_count; ++i) {
if (m_type_is_byref (sig->params [i])) {
MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
t = mini_get_underlying_type (t);
copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
} else {
copy->params [i] = mini_get_underlying_type (sig->params [i]);
}
if (!is_concrete_type (copy->params [i]))
concrete = FALSE;
}
copy->has_type_parameters = 0;
if (!concrete)
return NULL;
return copy;
}
/* LOCKING: Assumes the loader lock is held */
static void
add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
{
MonoMethod *wrapper;
gboolean add_in = gsharedvt_in;
gboolean add_out = gsharedvt_out;
if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
add_in = FALSE;
if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
add_out = FALSE;
if (!add_in && !add_out && !interp_in)
return;
if (mini_is_gsharedvt_variable_signature (sig))
return;
if (add_in)
g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
if (add_out)
g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
sig = get_concrete_sig (sig);
if (!sig)
return;
//printf ("%s\n", mono_signature_full_name (sig));
if (gsharedvt_in) {
wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
add_extra_method (acfg, wrapper);
}
if (gsharedvt_out) {
wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
add_extra_method (acfg, wrapper);
}
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
if (interp_in) {
wrapper = mini_get_interp_in_wrapper (sig);
add_extra_method (acfg, wrapper);
}
#endif
}
/*
* compile_method:
*
* AOT compile a given method.
* This function might be called by multiple threads, so it must be thread-safe.
*/
static void
compile_method (MonoAotCompile *acfg, MonoMethod *method)
{
MonoCompile *cfg;
MonoJumpInfo *patch_info;
gboolean skip;
int index, depth;
MonoMethod *wrapped;
gint64 jit_time_start;
JitFlags flags;
if (acfg->aot_opts.metadata_only)
return;
mono_acfg_lock (acfg);
index = get_method_index (acfg, method);
mono_acfg_unlock (acfg);
/* fixme: maybe we can also precompile wrapper methods */
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
//printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
return;
}
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
return;
wrapped = mono_marshal_method_from_wrapper (method);
if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
// FIXME: The wrapper should be generic too, but it is not
return;
if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
return;
if (acfg->aot_opts.profile_only && !g_hash_table_lookup (acfg->profile_methods, method)) {
if (acfg->aot_opts.llvm_only) {
gboolean keep = FALSE;
if (method->wrapper_type) {
/* Keep most wrappers */
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
switch (info->subtype) {
case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
break;
default:
keep = TRUE;
break;
}
}
if (always_aot (method))
keep = TRUE;
if (!keep)
return;
} else {
if (!method->is_inflated)
return;
}
}
mono_atomic_inc_i32 (&acfg->stats.mcount);
#if 0
if (method->is_generic || mono_class_is_gtd (method->klass)) {
mono_atomic_inc_i32 (&acfg->stats.genericcount);
return;
}
#endif
//acfg->aot_opts.print_skipped_methods = TRUE;
/*
* Since these methods are the only ones which are compiled with
* AOT support, and they are not used by runtime startup/shutdown code,
* the runtime will not see AOT methods during AOT compilation,so it
* does not need to support them by creating a fake GOT etc.
*/
flags = JIT_FLAG_AOT;
if (mono_aot_mode_is_full (&acfg->aot_opts))
flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
if (acfg->llvm)
flags = (JitFlags)(flags | JIT_FLAG_LLVM);
if (acfg->aot_opts.llvm_only)
flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
if (acfg->aot_opts.no_direct_calls)
flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
if (acfg->aot_opts.direct_pinvoke)
flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
if (acfg->aot_opts.interp)
flags = (JitFlags)(flags | JIT_FLAG_INTERP);
if (acfg->aot_opts.use_current_cpu)
flags = (JitFlags)(flags | JIT_FLAG_USE_CURRENT_CPU);
if (method_is_externally_callable (acfg, method))
flags = (JitFlags)(flags | JIT_FLAG_SELF_INIT);
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)
flags = (JitFlags)(flags | JIT_FLAG_CODE_EXEC_ONLY);
jit_time_start = mono_time_track_start ();
cfg = mini_method_compile (method, acfg->jit_opts, flags, 0, index);
mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
mono_atomic_inc_i32 (&acfg->stats.genericcount);
return;
}
if (cfg->exception_type != MONO_EXCEPTION_NONE) {
/* Some instances cannot be JITted due to constraints etc. */
if (!method->is_inflated)
report_loader_error (acfg, cfg->error, FALSE, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (cfg->error));
/* Let the exception happen at runtime */
return;
}
if (cfg->disable_aot) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
mono_atomic_inc_i32 (&acfg->stats.ocount);
return;
}
cfg->method_index = index;
/* Nullify patches which need no aot processing */
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_LABEL:
case MONO_PATCH_INFO_BB:
patch_info->type = MONO_PATCH_INFO_NONE;
break;
default:
break;
}
}
/* Collect method->token associations from the cfg */
mono_acfg_lock (acfg);
g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
mono_acfg_unlock (acfg);
g_hash_table_destroy (cfg->token_info_hash);
cfg->token_info_hash = NULL;
/*
* Check for absolute addresses.
*/
skip = FALSE;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_ABS:
/* unable to handle this */
skip = TRUE;
break;
default:
break;
}
}
if (skip) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
mono_atomic_inc_i32 (&acfg->stats.abscount);
return;
}
/* Lock for the rest of the code */
mono_acfg_lock (acfg);
if (cfg->gsharedvt)
acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
else if (cfg->gshared)
acfg->stats.method_categories [METHOD_CAT_INST] ++;
else if (cfg->method->wrapper_type)
acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
else
acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
/*
* Check for methods/klasses we can't encode.
*/
skip = FALSE;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
if (!can_encode_patch (acfg, patch_info))
skip = TRUE;
}
if (skip) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
acfg->stats.ocount++;
mono_acfg_unlock (acfg);
return;
}
if (!cfg->compile_llvm)
acfg->has_jitted_code = TRUE;
if (method->is_inflated && acfg->aot_opts.log_instances) {
if (acfg->instances_logfile)
fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
else
printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
}
/* Adds generic instances referenced by this method */
/*
* The depth is used to avoid infinite loops when generic virtual recursion is
* encountered.
*/
depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_METHOD_RGCTX: {
MonoMethod *m = NULL;
if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
m = e->data->data.method;
} else {
m = patch_info->data.method;
}
if (!m)
break;
if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
if (!(mono_class_generic_sharing_enabled (m->klass) &&
mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
(!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
} else {
add_extra_method_with_depth (acfg, m, depth + 1);
add_types_from_method_header (acfg, m);
}
}
add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
}
if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
WrapperInfo *info = mono_marshal_get_wrapper_info (m);
if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
add_extra_method_with_depth (acfg, m, depth + 1);
}
break;
}
case MONO_PATCH_INFO_VTABLE: {
MonoClass *klass = patch_info->data.klass;
if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
break;
}
case MONO_PATCH_INFO_SFLDA: {
MonoClass *klass = m_field_get_parent (patch_info->data.field);
/* The .cctor needs to run at runtime. */
if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
break;
}
default:
break;
}
}
}
/* Determine whenever the method has GOT slots */
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_NONE:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
break;
case MONO_PATCH_INFO_IMAGE:
/* The assembly is stored in GOT slot 0 */
if (patch_info->data.image != acfg->image)
cfg->has_got_slots = TRUE;
break;
default:
if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
cfg->has_got_slots = TRUE;
break;
}
}
if (!cfg->has_got_slots)
mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
/* Add gsharedvt wrappers for signatures used by the method */
if (acfg->aot_opts.llvm_only) {
GSList *l;
if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
/* These only need out wrappers */
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
for (l = cfg->signatures; l; l = l->next) {
MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
/* These only need in wrappers */
add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
if (mono_aot_mode_is_interp (&acfg->aot_opts) && sig->param_count > MAX_INTERP_ENTRY_ARGS)
/* See below */
add_gsharedvt_wrappers (acfg, sig, FALSE, FALSE, TRUE);
}
for (l = cfg->interp_in_signatures; l; l = l->next) {
MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
/*
* Interpreter methods in llvmonly+interp mode are called using gsharedvt_in wrappers,
* since we already generate those in llvmonly mode. But methods with a large
* number of arguments need special processing (see interp_create_method_pointer_llvmonly),
* which only interp_in wrappers do.
*/
if (sig->param_count > MAX_INTERP_ENTRY_ARGS)
add_gsharedvt_wrappers (acfg, sig, FALSE, FALSE, TRUE);
else
add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
}
} else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
/* The interpreter uses these wrappers to call aot-ed code */
if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
}
if (cfg->llvm_only)
acfg->stats.llvm_count ++;
if (acfg->llvm && !cfg->compile_llvm && method_is_externally_callable (acfg, cfg->method)) {
/*
* This is a JITted fallback method for a method which failed LLVM compilation, emit a global
* symbol for it with the same name the LLVM method would get.
*/
char *name = mono_aot_get_mangled_method_name (cfg->method);
char *export_name = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, name);
g_hash_table_insert (acfg->export_names, cfg->method, export_name);
}
/*
* FIXME: Instead of this mess, allocate the patches from the aot mempool.
*/
/* Make a copy of the patch info which is in the mempool */
{
MonoJumpInfo *patches = NULL, *patches_end = NULL;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
if (!patches)
patches = new_patch_info;
else
patches_end->next = new_patch_info;
patches_end = new_patch_info;
}
cfg->patch_info = patches;
}
/* Make a copy of the unwind info */
{
GSList *l, *unwind_ops;
MonoUnwindOp *op;
unwind_ops = NULL;
for (l = cfg->unwind_ops; l; l = l->next) {
op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
memcpy (op, l->data, sizeof (MonoUnwindOp));
unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
}
cfg->unwind_ops = g_slist_reverse (unwind_ops);
}
/* Make a copy of the argument/local info */
{
ERROR_DECL (error);
MonoInst **args, **locals;
MonoMethodSignature *sig;
MonoMethodHeader *header;
int i;
sig = mono_method_signature_internal (method);
args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
memcpy (args [i], cfg->args [i], sizeof (MonoInst));
}
cfg->args = args;
header = mono_method_get_header_checked (method, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
for (i = 0; i < header->num_locals; ++i) {
locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
}
mono_metadata_free_mh (header);
cfg->locals = locals;
}
/* Free some fields used by cfg to conserve memory */
mono_empty_compile (cfg);
//printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
acfg->cfgs [index] = cfg;
g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
/* Update global stats while holding a lock. */
mono_update_jit_stats (cfg);
/*
if (cfg->orig_method->wrapper_type)
g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
*/
mono_acfg_unlock (acfg);
mono_atomic_inc_i32 (&acfg->stats.ccount);
}
static mono_thread_start_return_t WINAPI
compile_thread_main (gpointer user_data)
{
MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
GPtrArray *methods = ((GPtrArray **)user_data) [1];
int i;
mono_thread_set_name_constant_ignore_error (mono_thread_internal_current (), "AOT compiler", MonoSetThreadNameFlag_Permanent);
for (i = 0; i < methods->len; ++i)
compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
return 0;
}
/* Used by the LLVM backend */
guint32
mono_aot_get_got_offset (MonoJumpInfo *ji)
{
return get_got_offset (llvm_acfg, TRUE, ji);
}
/*
* mono_aot_is_shared_got_offset:
*
* Return whenever OFFSET refers to a GOT slot which is preinitialized
* when the AOT image is loaded.
*/
gboolean
mono_aot_is_shared_got_offset (int offset)
{
return offset < llvm_acfg->nshared_got_entries;
}
gboolean
mono_aot_is_externally_callable (MonoMethod *cmethod)
{
return method_is_externally_callable (llvm_acfg, cmethod);
}
char*
mono_aot_get_method_name (MonoCompile *cfg)
{
MonoMethod *method = cfg->orig_method;
/* Use the mangled name if possible */
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
char *name, *s;
name = mono_aot_get_mangled_method_name (method);
if (llvm_acfg->aot_opts.static_link) {
/* Include the assembly name too to avoid duplicate symbol errors */
s = g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, name);
g_free (name);
return s;
} else {
return name;
}
}
}
if (llvm_acfg->aot_opts.static_link)
/* Include the assembly name too to avoid duplicate symbol errors */
return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
else
return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
}
static gboolean
append_mangled_type (GString *s, MonoType *t)
{
if (m_type_is_byref (t))
g_string_append_printf (s, "b");
switch (t->type) {
case MONO_TYPE_VOID:
g_string_append_printf (s, "void");
break;
case MONO_TYPE_BOOLEAN:
g_string_append_printf (s, "bool");
break;
case MONO_TYPE_CHAR:
g_string_append_printf (s, "char");
break;
case MONO_TYPE_I1:
g_string_append_printf (s, "i1");
break;
case MONO_TYPE_U1:
g_string_append_printf (s, "u1");
break;
case MONO_TYPE_I2:
g_string_append_printf (s, "i2");
break;
case MONO_TYPE_U2:
g_string_append_printf (s, "u2");
break;
case MONO_TYPE_I4:
g_string_append_printf (s, "i4");
break;
case MONO_TYPE_U4:
g_string_append_printf (s, "u4");
break;
case MONO_TYPE_I8:
g_string_append_printf (s, "i8");
break;
case MONO_TYPE_U8:
g_string_append_printf (s, "u8");
break;
case MONO_TYPE_I:
g_string_append_printf (s, "ii");
break;
case MONO_TYPE_U:
g_string_append_printf (s, "ui");
break;
case MONO_TYPE_R4:
g_string_append_printf (s, "fl");
break;
case MONO_TYPE_R8:
g_string_append_printf (s, "do");
break;
case MONO_TYPE_OBJECT:
g_string_append_printf (s, "obj");
break;
default: {
char *fullname = mono_type_full_name (t);
char *name = fullname;
GString *temp;
char *temps;
gboolean is_system = FALSE;
int i, len;
len = strlen ("System.");
if (strncmp (fullname, "System.", len) == 0) {
name = fullname + len;
is_system = TRUE;
}
/*
* Have to create a mangled name which is:
* - a valid symbol
* - unique
*/
temp = g_string_new ("");
len = strlen (name);
for (i = 0; i < len; ++i) {
char c = name [i];
if (isalnum (c)) {
g_string_append_c (temp, c);
} else if (c == '_') {
g_string_append_c (temp, '_');
g_string_append_c (temp, '_');
} else {
g_string_append_c (temp, '_');
if (c == '.')
g_string_append_c (temp, 'd');
else
g_string_append_printf (temp, "%x", (int)c);
}
}
temps = g_string_free (temp, FALSE);
/* Include the length to avoid different length type names aliasing each other */
g_string_append_printf (s, "cl%s%x_%s_", is_system ? "s" : "", (int)strlen (temps), temps);
g_free (temps);
g_free (fullname);
}
}
if (t->attrs)
g_string_append_printf (s, "_attrs_%d", t->attrs);
return TRUE;
}
static gboolean
append_mangled_signature (GString *s, MonoMethodSignature *sig)
{
int i;
gboolean supported;
if (sig->pinvoke)
g_string_append_printf (s, "pinvoke_");
supported = append_mangled_type (s, sig->ret);
if (!supported)
return FALSE;
g_string_append_printf (s, "_");
if (sig->hasthis)
g_string_append_printf (s, "this_");
for (i = 0; i < sig->param_count; ++i) {
supported = append_mangled_type (s, sig->params [i]);
if (!supported)
return FALSE;
}
return TRUE;
}
static void
append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
{
const char *label;
switch (wrapper_type) {
case MONO_WRAPPER_ALLOC:
label = "alloc";
break;
case MONO_WRAPPER_WRITE_BARRIER:
label = "write_barrier";
break;
case MONO_WRAPPER_STELEMREF:
label = "stelemref";
break;
case MONO_WRAPPER_OTHER:
label = "unknown";
break;
case MONO_WRAPPER_MANAGED_TO_NATIVE:
label = "man2native";
break;
case MONO_WRAPPER_SYNCHRONIZED:
label = "synch";
break;
case MONO_WRAPPER_MANAGED_TO_MANAGED:
label = "man2man";
break;
case MONO_WRAPPER_CASTCLASS:
label = "castclass";
break;
case MONO_WRAPPER_RUNTIME_INVOKE:
label = "run_invoke";
break;
case MONO_WRAPPER_DELEGATE_INVOKE:
label = "del_inv";
break;
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
label = "del_beg_inv";
break;
case MONO_WRAPPER_DELEGATE_END_INVOKE:
label = "del_end_inv";
break;
case MONO_WRAPPER_NATIVE_TO_MANAGED:
label = "native2man";
break;
default:
g_assert_not_reached ();
}
g_string_append_printf (s, "%s_", label);
}
static void
append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
{
const char *label;
switch (subtype)
{
case WRAPPER_SUBTYPE_NONE:
return;
case WRAPPER_SUBTYPE_ELEMENT_ADDR:
label = "elem_addr";
break;
case WRAPPER_SUBTYPE_STRING_CTOR:
label = "str_ctor";
break;
case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
label = "virt_stelem";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
label = "fast_mon_enter";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
label = "fast_mon_enter_4";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
label = "fast_monitor_exit";
break;
case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
label = "ptr2struct";
break;
case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
label = "struct2ptr";
break;
case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
label = "castclass_w_cache";
break;
case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
label = "isinst_w_cache";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
label = "run_inv_norm";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
label = "run_inv_dyn";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
label = "run_inv_dir";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
label = "run_inv_vir";
break;
case WRAPPER_SUBTYPE_ICALL_WRAPPER:
label = "icall";
break;
case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
label = "native_func_aot";
break;
case WRAPPER_SUBTYPE_PINVOKE:
label = "pinvoke";
break;
case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
label = "synch_inner";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_IN:
label = "gshared_in";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
label = "gshared_out";
break;
case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
label = "array_acc";
break;
case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
label = "generic_arry_help";
break;
case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
label = "del_inv_virt";
break;
case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
label = "del_inv_bound";
break;
case WRAPPER_SUBTYPE_INTERP_IN:
label = "interp_in";
break;
case WRAPPER_SUBTYPE_INTERP_LMF:
label = "interp_lmf";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
label = "gsharedvt_in_sig";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
label = "gsharedvt_out_sig";
break;
case WRAPPER_SUBTYPE_AOT_INIT:
label = "aot_init";
break;
case WRAPPER_SUBTYPE_LLVM_FUNC:
label = "llvm_func";
break;
default:
g_assert_not_reached ();
}
g_string_append_printf (s, "%s_", label);
}
static char *
sanitize_mangled_string (const char *input)
{
GString *s = g_string_new ("");
for (int i=0; input [i] != '\0'; i++) {
char c = input [i];
switch (c) {
case '.':
g_string_append (s, "_dot_");
break;
case ' ':
g_string_append (s, "_");
break;
case '`':
g_string_append (s, "_bt_");
break;
case '<':
g_string_append (s, "_le_");
break;
case '>':
g_string_append (s, "_gt_");
break;
case '/':
g_string_append (s, "_sl_");
break;
case '[':
g_string_append (s, "_lbrack_");
break;
case ']':
g_string_append (s, "_rbrack_");
break;
case '(':
g_string_append (s, "_lparen_");
break;
case '-':
g_string_append (s, "_dash_");
break;
case ')':
g_string_append (s, "_rparen_");
break;
case ',':
g_string_append (s, "_comma_");
break;
case ':':
g_string_append (s, "_colon_");
break;
case '|':
g_string_append (s, "_verbar_");
break;
default:
g_string_append_c (s, c);
}
}
return g_string_free (s, FALSE);
}
static gboolean
append_mangled_klass (GString *s, MonoClass *klass)
{
char *klass_desc = mono_class_full_name (klass);
g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
g_free (klass_desc);
// Success
return TRUE;
}
static const char*
get_assembly_prefix (MonoImage *image)
{
if (mono_is_corlib_image (image))
return "corlib";
else if (!strcmp (image->assembly->aname.name, "corlib"))
return "__corlib__";
else
return image->assembly->aname.name;
}
static gboolean
append_mangled_method (GString *s, MonoMethod *method);
static gboolean
append_mangled_wrapper (GString *s, MonoMethod *method)
{
gboolean success = TRUE;
gboolean append_sig = TRUE;
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
gboolean is_corlib = mono_is_corlib_image (m_class_get_image (method->klass));
g_string_append_printf (s, "wrapper_");
/* Most wrappers are in mscorlib */
if (!is_corlib)
g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
append_mangled_wrapper_type (s, method->wrapper_type);
switch (method->wrapper_type) {
case MONO_WRAPPER_ALLOC: {
/* The GC name is saved once in MonoAotFileInfo */
g_assert (info->d.alloc.alloc_type != -1);
g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
// SlowAlloc, etc
g_string_append_printf (s, "%s_", method->name);
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
g_string_append_printf (s, "%s_", method->name);
break;
}
case MONO_WRAPPER_STELEMREF: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
else if (info->subtype == WRAPPER_SUBTYPE_LLVM_FUNC)
g_string_append_printf (s, "%d", info->d.llvm_func.subtype);
break;
}
case MONO_WRAPPER_OTHER: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
success = success && append_mangled_klass (s, method->klass);
else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
success = success && append_mangled_method (s, info->d.synchronized_inner.method);
else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
success = success && append_mangled_method (s, info->d.array_accessor.method);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
append_mangled_signature (s, info->d.interp_in.sig);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
append_mangled_signature (s, info->d.gsharedvt.sig);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
append_mangled_signature (s, info->d.gsharedvt.sig);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
g_string_append_printf (s, "%s", method->name);
else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
g_string_append_printf (s, "%s_%d_", get_assembly_prefix (m_class_get_image (method->klass)), info->d.aot_init.subtype);
append_sig = FALSE;
}
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
const char *name = method->name;
const char *prefix = "__icall_wrapper_";
if (strstr (name, prefix) == name)
name += strlen (prefix);
g_string_append_printf (s, "%s", name);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
success = success && append_mangled_method (s, info->d.managed_to_native.method);
} else {
g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
success = success && append_mangled_method (s, info->d.managed_to_native.method);
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m;
m = mono_marshal_method_from_wrapper (method);
g_assert (m);
g_assert (m != method);
success = success && append_mangled_method (s, m);
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
g_string_append_printf (s, "%d_", info->d.element_addr.rank);
g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
} else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
success = success && append_mangled_method (s, info->d.string_ctor.method);
} else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
success = success && append_mangled_method (s, info->d.generic_array_helper.method);
} else {
success = FALSE;
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
append_mangled_wrapper_subtype (s, info->subtype);
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
success = success && append_mangled_method (s, info->d.runtime_invoke.method);
else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
if (method->is_inflated) {
/* These wrappers are identified by their class */
g_string_append_printf (s, "i_");
success = success && append_mangled_klass (s, method->klass);
} else {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
g_string_append_printf (s, "u_");
if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
append_mangled_wrapper_subtype (s, info->subtype);
g_string_append_printf (s, "u_sigstart");
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
g_assert (info);
success = success && append_mangled_method (s, info->d.native_to_managed.method);
success = success && append_mangled_klass (s, method->klass);
break;
}
default:
g_assert_not_reached ();
}
if (success && append_sig)
success = append_mangled_signature (s, mono_method_signature_internal (method));
return success;
}
static void
append_mangled_ginst (GString *str, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
if (i > 0)
g_string_append (str, ", ");
MonoType *type = ginst->type_argv [i];
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR: {
MonoType *constraint = NULL;
if (type->data.generic_param)
constraint = type->data.generic_param->gshared_constraint;
if (constraint) {
g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
g_string_append (str, "gshared:");
mono_type_get_desc (str, constraint, TRUE);
break;
}
// Else falls through to common case
}
default:
mono_type_get_desc (str, type, TRUE);
}
}
}
static void
append_mangled_context (GString *str, MonoGenericContext *context)
{
GString *res = g_string_new ("");
g_string_append_printf (res, "gens_");
g_string_append (res, "00");
gboolean good = context->class_inst && context->class_inst->type_argc > 0;
good = good || (context->method_inst && context->method_inst->type_argc > 0);
g_assert (good);
if (context->class_inst)
append_mangled_ginst (res, context->class_inst);
if (context->method_inst) {
if (context->class_inst)
g_string_append (res, "11");
append_mangled_ginst (res, context->method_inst);
}
g_string_append_printf (str, "gens_%s", res->str);
g_free (res);
}
static gboolean
append_mangled_method (GString *s, MonoMethod *method)
{
if (method->wrapper_type)
return append_mangled_wrapper (s, method);
if (method->is_inflated) {
g_string_append_printf (s, "inflated_");
MonoMethodInflated *imethod = (MonoMethodInflated*) method;
g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
append_mangled_context (s, &imethod->context);
g_string_append_printf (s, "_declared_by_%s_", get_assembly_prefix (m_class_get_image (imethod->declaring->klass)));
append_mangled_method (s, imethod->declaring);
} else if (method->is_generic) {
g_string_append_printf (s, "%s_", get_assembly_prefix (m_class_get_image (method->klass)));
g_string_append_printf (s, "generic_");
append_mangled_klass (s, method->klass);
g_string_append_printf (s, "_%s_", method->name);
MonoGenericContainer *container = mono_method_get_generic_container (method);
g_string_append_printf (s, "_");
append_mangled_context (s, &container->context);
return append_mangled_signature (s, mono_method_signature_internal (method));
} else {
g_string_append_printf (s, "%s", get_assembly_prefix (m_class_get_image (method->klass)));
append_mangled_klass (s, method->klass);
g_string_append_printf (s, "_%s_", method->name);
if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
g_string_free (s, TRUE);
return FALSE;
}
}
return TRUE;
}
/*
* mono_aot_get_mangled_method_name:
*
* Return a unique mangled name for METHOD, or NULL.
*/
char*
mono_aot_get_mangled_method_name (MonoMethod *method)
{
// FIXME: use static cache (mempool?)
// We call this a *lot*
GString *s = g_string_new ("aot_");
if (!append_mangled_method (s, method)) {
g_string_free (s, TRUE);
return NULL;
} else {
char *out = g_string_free (s, FALSE);
// Scrub method and class names
char *cleaned = sanitize_mangled_string (out);
g_free (out);
return cleaned;
}
}
gboolean
mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
{
return is_direct_callable (llvm_acfg, NULL, patch_info);
}
void
mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
{
MonoPltEntry *plt_entry;
plt_entry = get_plt_entry (llvm_acfg, patch_info);
plt_entry->llvm_used = FALSE;
}
char*
mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
{
const char *sym = NULL;
if (llvm_acfg->aot_opts.direct_icalls) {
if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
/* Call to a C function implementing a jit icall */
sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
} else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
MonoMethod *method = (MonoMethod *)data;
if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
sym = lookup_icall_symbol_name_aot (method);
else if (llvm_acfg->aot_opts.direct_pinvoke)
sym = get_pinvoke_import (llvm_acfg, method);
} else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
char const * const name = info->c_symbol;
if (name && info->func == info->wrapper)
sym = name;
}
if (sym)
return g_strdup (sym);
}
return NULL;
}
char*
mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
{
MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
MonoPltEntry *plt_entry;
const char *sym = NULL;
ji->type = type;
ji->data.target = data;
if (!can_encode_patch (llvm_acfg, ji))
return NULL;
if (llvm_acfg->aot_opts.direct_icalls) {
if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
/* Call to a C function implementing a jit icall */
sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
} else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
MonoMethod *method = (MonoMethod *)data;
if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
sym = lookup_icall_symbol_name_aot (method);
}
if (sym)
return g_strdup (sym);
}
plt_entry = get_plt_entry (llvm_acfg, ji);
plt_entry->llvm_used = TRUE;
#if defined(TARGET_MACH)
return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
#else
return g_strdup (plt_entry->llvm_symbol);
#endif
}
int
mono_aot_get_method_index (MonoMethod *method)
{
g_assert (llvm_acfg);
return get_method_index (llvm_acfg, method);
}
MonoJumpInfo*
mono_aot_patch_info_dup (MonoJumpInfo* ji)
{
MonoJumpInfo *res;
mono_acfg_lock (llvm_acfg);
res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
mono_acfg_unlock (llvm_acfg);
return res;
}
static int
execute_system (const char * command)
{
int status = 0;
#if defined (HOST_WIN32)
// We need an extra set of quotes around the whole command to properly handle commands
// with spaces since internally the command is called through "cmd /c.
char * quoted_command = g_strdup_printf ("\"%s\"", command);
int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
status = _wsystem (wstr);
g_free (wstr);
g_free (quoted_command);
#elif defined (HAVE_SYSTEM)
status = system (command);
#else
g_assert_not_reached ();
#endif
return status;
}
#ifdef ENABLE_LLVM
/*
* emit_llvm_file:
*
* Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
* tools.
*/
static gboolean
emit_llvm_file (MonoAotCompile *acfg)
{
char *command, *opts, *tempbc, *optbc, *output_fname;
if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
if (acfg->aot_opts.no_opt)
tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
else
tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
optbc = g_strdup (acfg->aot_opts.llvm_outfile);
} else {
tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
}
mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
if (acfg->aot_opts.no_opt)
return TRUE;
/*
* FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
* a lot of time, and doesn't seem to save much space.
* The following optimizations cannot be enabled:
* - 'tailcallelim'
* - 'jump-threading' changes our blockaddress references to int constants.
* - 'basiccg' fails because it contains:
* if (CS && !isa<IntrinsicInst>(II)) {
* and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
* - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
* The opt list below was produced by taking the output of:
* llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
* then removing tailcallelim + the global opts.
* strip-dead-prototypes deletes unused intrinsics definitions.
*/
/* The dse pass is disabled because of #13734 and #17616 */
/*
* The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
* // If we have no DataLayout information around, then the size of the store
* // is inferrable from the pointee type. If they are the same type, then
* // we know that the store is safe.
* if (AA.getDataLayout() == 0 &&
* Later.Ptr->getType() == Earlier.Ptr->getType()) {
* return OverwriteComplete;
* Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
*/
if (acfg->aot_opts.llvm_only) {
// FIXME: This doesn't work yet
opts = g_strdup ("");
} else {
opts = g_strdup ("-disable-tail-calls -place-safepoints -spp-all-backedges");
}
if (acfg->aot_opts.llvm_opts) {
opts = g_strdup_printf ("%s %s", acfg->aot_opts.llvm_opts, opts);
} else if (!acfg->aot_opts.llvm_only) {
opts = g_strdup_printf ("-O2 %s", opts);
}
if (acfg->aot_opts.use_current_cpu) {
opts = g_strdup_printf ("%s -mcpu=native", opts);
}
if (acfg->aot_opts.llvm_cpu_attr) {
opts = g_strdup_printf ("%s -mattr=%s", opts, acfg->aot_opts.llvm_cpu_attr);
}
if (mono_use_fast_math) {
// same parameters are passed to llc and LLVM JIT
opts = g_strdup_printf ("%s -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math", opts);
}
command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
aot_printf (acfg, "Executing opt: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
g_free (opts);
if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
/* Nothing else to do */
return TRUE;
if (acfg->aot_opts.llvm_only) {
/* Use the stock clang from xcode */
// FIXME: arch
command = g_strdup_printf ("%s -fexceptions -fpic -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
aot_printf (acfg, "Executing clang: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
return TRUE;
}
if (!acfg->llc_args)
acfg->llc_args = g_string_new ("");
/* Verbose asm slows down llc greatly */
g_string_append (acfg->llc_args, " -asm-verbose=false");
if (acfg->aot_opts.mtriple)
g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
#if defined(TARGET_X86_64_WIN32_MSVC)
if (!acfg->aot_opts.mtriple)
g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
#endif
g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
#if defined(TARGET_AMD64) || defined(TARGET_X86)
/* This generates stack adjustments in the middle of functions breaking unwind info */
g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
#endif
#if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC) || defined(TARGET_ANDROID)
g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
#else
if (llvm_acfg->aot_opts.static_link)
g_string_append_printf (acfg->llc_args, " -relocation-model=static");
else
g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
#endif
if (acfg->llvm_owriter) {
/* Emit an object file directly */
output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
g_string_append_printf (acfg->llc_args, " -filetype=obj");
} else {
output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
}
if (acfg->aot_opts.llvm_llc) {
g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
}
if (acfg->aot_opts.use_current_cpu) {
g_string_append (acfg->llc_args, " -mcpu=native");
}
if (acfg->aot_opts.llvm_cpu_attr) {
g_string_append_printf (acfg->llc_args, " -mattr=%s", acfg->aot_opts.llvm_cpu_attr);
}
command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
g_free (output_fname);
aot_printf (acfg, "Executing llc: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
return TRUE;
}
#endif
/* Set the skip flag for methods which do not need to be emitted because of dedup */
static void
dedup_skip_methods (MonoAotCompile *acfg)
{
int oindex, i;
if (acfg->aot_opts.llvm_only)
return;
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
MonoCompile *cfg;
MonoMethod *method;
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
cfg = acfg->cfgs [i];
if (!cfg)
continue;
method = cfg->orig_method;
gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
gboolean dedupable = mono_aot_can_dedup (method);
// cfg->skip is vital for LLVM to work, can't just continue in this loop
if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
mono_dedup_cache_method (acfg, method);
// Don't compile inflated methods if we're in first phase of
// dedup
//
// In second phase, we emit methods that
// are dedupable. We also emit later methods
// which are referenced by them and added later.
// For this reason, when in the dedup_include mode,
// we never set skip.
if (acfg->aot_opts.dedup)
cfg->skip = TRUE;
}
// Don't compile anything in this mode
if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
cfg->skip = TRUE;
// Compile everything in this mode
if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
cfg->skip = FALSE;
/*if (dedup_collect) {*/
/*char *name = mono_aot_get_mangled_method_name (method);*/
/*if (ignore_cfg (cfg))*/
/*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
/*else*/
/*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
/*g_free (name);*/
/*}*/
}
}
static void
emit_code (MonoAotCompile *acfg)
{
int oindex, i, prev_index;
gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
char symbol [MAX_SYMBOL_SIZE];
if (acfg->aot_opts.llvm_only)
return;
#if defined(TARGET_POWERPC64)
sprintf (symbol, ".Lgot_addr");
emit_section_change (acfg, ".text", 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
emit_pointer (acfg, acfg->got_symbol);
#endif
/*
* This global symbol is used to compute the address of each method using the
* code_offsets array. It is also used to compute the memory ranges occupied by
* AOT code, so it must be equal to the address of the first emitted method.
*/
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, "jit_code_start", TRUE);
/*
* Emit some padding so the local symbol for the first method doesn't have the
* same address as 'methods'.
*/
emit_padding (acfg, 16);
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
MonoCompile *cfg;
MonoMethod *method;
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
cfg = acfg->cfgs [i];
if (!cfg)
continue;
method = cfg->orig_method;
if (ignore_cfg (cfg))
continue;
/* Emit unbox trampoline */
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
sprintf (symbol, "ut_%d", get_method_index (acfg, method));
emit_section_change (acfg, ".text", 0);
if (acfg->thumb_mixed && cfg->compile_llvm) {
emit_set_thumb_mode (acfg);
fprintf (acfg->fp, "\n.thumb_func\n");
}
emit_label (acfg, symbol);
arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
if (acfg->thumb_mixed && cfg->compile_llvm)
emit_set_arm_mode (acfg);
if (!saved_unbox_info) {
char user_symbol [128];
GSList *unwind_ops;
sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
emit_label (acfg, "ut_end");
unwind_ops = mono_unwind_get_cie_program ();
save_unwind_info (acfg, user_symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Save the unbox trampoline size */
#ifdef TARGET_AMD64
// LLVM unbox trampolines vary in size, 6 or 9 bytes,
// due to the last instruction being 2 or 5 bytes.
// There is no need to describe interior bytes of instructions
// however, so state the size as if the last instruction is size 1.
emit_int32 (acfg, 5);
#else
emit_symbol_diff (acfg, "ut_end", symbol, 0);
#endif
saved_unbox_info = TRUE;
}
}
if (cfg->compile_llvm) {
acfg->stats.llvm_count ++;
} else {
emit_method_code (acfg, cfg);
}
}
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, "jit_code_end", TRUE);
/* To distinguish it from the next symbol */
emit_padding (acfg, 4);
/*
* Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
* from optimizing them away, since it doesn't see that code_offsets references them.
* JITted methods don't need this since they are referenced using assembler local
* symbols.
* FIXME: This is why write-symbols doesn't work on OSX ?
*/
if (acfg->llvm && acfg->need_no_dead_strip) {
fprintf (acfg->fp, "\n");
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
}
}
/*
* To work around linker issues, we emit a table of branches, and disassemble them at runtime.
* This is PIE code, and the linker can update it if needed.
*/
#if defined(TARGET_ANDROID) || defined(__linux__)
gboolean is_func = FALSE;
#else
gboolean is_func = TRUE;
#endif
sprintf (symbol, "method_addresses");
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
/* Emit the method address table as a table of pointers */
emit_section_change (acfg, ".data", 0);
} else {
emit_section_change (acfg, RODATA_REL_SECT, !!is_func);
}
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, symbol, is_func);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, "method_addresses_end", is_func);
emit_unset_mode (acfg);
if (acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
for (i = 0; i < acfg->nmethods; ++i) {
#ifdef MONO_ARCH_AOT_SUPPORTED
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
if (!ignore_cfg (acfg->cfgs [i]))
emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
else
emit_pointer (acfg, NULL);
} else {
if (!ignore_cfg (acfg->cfgs [i])) {
arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &acfg->call_table_entry_size);
} else {
arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &acfg->call_table_entry_size);
}
}
#endif
}
sprintf (symbol, "method_addresses_end");
emit_label (acfg, symbol);
emit_line (acfg);
/* Emit a sorted table mapping methods to the index of their unbox trampolines */
sprintf (symbol, "unbox_trampolines");
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, FALSE);
prev_index = -1;
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
int index;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
index = get_method_index (acfg, method);
emit_int32 (acfg, index);
/* Make sure the table is sorted by index */
g_assert (index > prev_index);
prev_index = index;
}
}
sprintf (symbol, "unbox_trampolines_end");
emit_info_symbol (acfg, symbol, FALSE);
emit_int32 (acfg, 0);
/* Emit a separate table with the trampoline addresses/offsets */
sprintf (symbol, "unbox_trampoline_addresses");
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
/* Emit the unbox trampoline address table as a table of pointers */
emit_section_change (acfg, ".data", 0);
} else {
emit_section_change (acfg, ".text", 0);
}
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, symbol, TRUE);
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
(void)method;
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
#ifdef MONO_ARCH_AOT_SUPPORTED
const int index = get_method_index (acfg, method);
sprintf (symbol, "ut_%d", index);
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
emit_pointer (acfg, symbol);
} else {
int call_size;
arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
}
#endif
}
}
emit_int32 (acfg, 0);
}
static void
emit_method_info_table (MonoAotCompile *acfg)
{
int oindex, i;
gint32 *offsets;
guint8 *method_flags;
offsets = g_new0 (gint32, acfg->nmethods);
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
if (acfg->cfgs [i]) {
emit_method_info (acfg, acfg->cfgs [i]);
offsets [i] = acfg->cfgs [i]->method_info_offset;
} else {
offsets [i] = 0;
}
}
acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
g_free (offsets);
/* Emit a separate table for method flags, its needed at runtime */
method_flags = g_new0 (guint8, acfg->nmethods);
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i])
method_flags [acfg->cfgs [i]->method_index] = acfg->cfgs [i]->aot_method_flags;
}
emit_aot_data (acfg, MONO_AOT_TABLE_METHOD_FLAGS_TABLE, "method_flags_table", method_flags, acfg->nmethods);
}
#endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) { \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define mono_final(a,b,c) { \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
static guint
mono_aot_type_hash (MonoType *t1)
{
guint hash = t1->type;
hash |= m_type_is_byref (t1) << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.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) ^ 0;
default:
return hash;
}
}
/*
* mono_aot_method_hash:
*
* Return a hash code for methods which only depends on metadata.
*/
guint32
mono_aot_method_hash (MonoMethod *method)
{
MonoMethodSignature *sig;
MonoClass *klass;
int i, hindex;
int hashes_count;
guint32 *hashes_start, *hashes;
guint32 a, b, c;
MonoGenericInst *class_ginst = NULL;
MonoGenericInst *ginst = NULL;
/* Similar to the hash in mono_method_get_imt_slot () */
sig = mono_method_signature_internal (method);
if (mono_class_is_ginst (method->klass))
class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
if (method->is_inflated)
ginst = ((MonoMethodInflated*)method)->context.method_inst;
hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
hashes = hashes_start;
/* Some wrappers are assigned to random classes */
if (!method->wrapper_type)
klass = method->klass;
else
klass = mono_defaults.object_class;
if (!method->wrapper_type) {
char *full_name;
if (mono_class_is_ginst (klass))
full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
else
full_name = mono_type_full_name (m_class_get_byval_arg (klass));
hashes [0] = mono_metadata_str_hash (full_name);
hashes [1] = 0;
g_free (full_name);
} else {
hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
}
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && mono_marshal_get_wrapper_info (method)->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER)
/* The name might not be set correctly if DISABLE_JIT is set */
hashes [2] = mono_marshal_get_wrapper_info (method)->d.icall.jit_icall_id;
else
hashes [2] = mono_metadata_str_hash (method->name);
hashes [3] = method->wrapper_type;
hashes [4] = mono_aot_type_hash (sig->ret);
hindex = 5;
for (i = 0; i < sig->param_count; i++) {
hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
}
if (class_ginst) {
for (i = 0; i < class_ginst->type_argc; ++i)
hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
}
if (ginst) {
for (i = 0; i < ginst->type_argc; ++i)
hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
}
g_assert (hindex == hashes_count);
/* Setup internal state */
a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
/* Handle most of the hashes */
while (hashes_count > 3) {
a += hashes [0];
b += hashes [1];
c += hashes [2];
mix (a,b,c);
hashes_count -= 3;
hashes += 3;
}
/* Handle the last 3 hashes (all the case statements fall through) */
switch (hashes_count) {
case 3 : c += hashes [2];
case 2 : b += hashes [1];
case 1 : a += hashes [0];
mono_final (a,b,c);
case 0: /* nothing left to add */
break;
}
g_free (hashes_start);
return c;
}
#undef rot
#undef mix
#undef mono_final
/*
* mono_aot_get_array_helper_from_wrapper;
*
* Get the helper method in Array called by an array wrapper method.
*/
MonoMethod*
mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
{
MonoMethod *m;
const char *prefix;
MonoGenericContext ctx;
char *mname, *iname, *s, *s2, *helper_name = NULL;
prefix = "System.Collections.Generic";
s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
s2 = strstr (s, "`1.");
g_assert (s2);
s2 [0] = '\0';
iname = s;
mname = s2 + 3;
//printf ("X: %s %s\n", iname, mname);
if (!strcmp (iname, "IList"))
helper_name = g_strdup_printf ("InternalArray__%s", mname);
else
helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
g_assert (m);
g_free (helper_name);
g_free (s);
if (m->is_generic) {
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (m_class_get_element_class (method->klass)) };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
m = mono_class_inflate_generic_method_checked (m, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
return m;
}
#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
typedef struct HashEntry {
guint32 key, value, index;
struct HashEntry *next;
} HashEntry;
/*
* emit_extra_methods:
*
* Emit methods which are not in the METHOD table, like wrappers.
*/
static void
emit_extra_methods (MonoAotCompile *acfg)
{
int i, table_size, buf_size;
guint8 *p, *buf;
guint32 *info_offsets;
guint32 hash;
GPtrArray *table;
HashEntry *entry, *new_entry;
int nmethods, max_chain_length;
int *chain_lengths;
info_offsets = g_new0 (guint32, acfg->extra_methods->len);
/* Emit method info */
nmethods = 0;
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
if (ignore_cfg (cfg))
continue;
buf_size = 10240;
p = buf = (guint8 *)g_malloc (buf_size);
nmethods ++;
method = cfg->method_to_register;
encode_method_ref (acfg, method, p, &p);
g_assert ((p - buf) < buf_size);
info_offsets [i] = add_to_blob (acfg, buf, p - buf);
g_free (buf);
}
/*
* Construct a chained hash table for mapping indexes in extra_method_info to
* method indexes.
*/
table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
chain_lengths = g_new0 (int, table_size);
max_chain_length = 0;
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
guint32 key, value;
if (ignore_cfg (cfg))
continue;
key = info_offsets [i];
value = get_method_index (acfg, method);
hash = mono_aot_method_hash (method) % table_size;
//printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
chain_lengths [hash] ++;
max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
new_entry->key = key;
new_entry->value = value;
entry = (HashEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
g_free (chain_lengths);
//printf ("MAX: %d\n", max_chain_length);
buf_size = table->len * 12 + 4;
p = buf = (guint8 *)g_malloc (buf_size);
encode_int (table_size, p, &p);
for (i = 0; i < table->len; ++i) {
HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
encode_int (0, p, &p);
encode_int (0, p, &p);
encode_int (0, p, &p);
} else {
//g_assert (entry->key > 0);
encode_int (entry->key, p, &p);
encode_int (entry->value, p, &p);
if (entry->next)
encode_int (entry->next->index, p, &p);
else
encode_int (0, p, &p);
}
}
g_assert (p - buf <= buf_size);
/* Emit the table */
emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
g_free (buf);
/*
* Emit a table reverse mapping method indexes to their index in extra_method_info.
* This is used by mono_aot_find_jit_info ().
*/
buf_size = acfg->extra_methods->len * 8 + 4;
p = buf = (guint8 *)g_malloc (buf_size);
encode_int (acfg->extra_methods->len, p, &p);
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
encode_int (get_method_index (acfg, method), p, &p);
encode_int (info_offsets [i], p, &p);
}
emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
g_free (buf);
g_free (info_offsets);
g_ptr_array_free (table, TRUE);
}
static void
generate_aotid (guint8* aotid)
{
gpointer rand_handle;
ERROR_DECL (error);
mono_rand_open ();
rand_handle = mono_rand_init (NULL, 0);
mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
mono_error_assert_ok (error);
mono_rand_close (rand_handle);
}
static void
emit_exception_info (MonoAotCompile *acfg)
{
int i;
gint32 *offsets;
SeqPointData sp_data;
gboolean seq_points_to_file = FALSE;
offsets = g_new0 (gint32, acfg->nmethods);
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i]) {
MonoCompile *cfg = acfg->cfgs [i];
// By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
// As it is not possible to load debug data from a file its is also not possible to store it in a file.
gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
offsets [i] = cfg->ex_info_offset;
if (method_seq_points_to_file) {
if (!seq_points_to_file) {
mono_seq_point_data_init (&sp_data, acfg->nmethods);
seq_points_to_file = TRUE;
}
mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
}
} else {
offsets [i] = 0;
}
}
if (seq_points_to_file) {
char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, (const char*)NULL);
char *image_basename = g_path_get_basename (acfg->image->name);
char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
char *aot_file_path = g_build_filename (dir, aot_file, (const char*)NULL);
if (g_ensure_directory_exists (aot_file_path) == FALSE) {
fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
exit (1);
}
mono_seq_point_data_write (&sp_data, aot_file_path);
mono_seq_point_data_free (&sp_data);
g_free (aotid);
g_free (dir);
g_free (image_basename);
g_free (aot_file);
g_free (aot_file_path);
}
acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
g_free (offsets);
}
static void
emit_unwind_info (MonoAotCompile *acfg)
{
int i;
char symbol [128];
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->unwind_ops->len == 0);
return;
}
/*
* The unwind info contains a lot of duplicates so we emit each unique
* entry once, and only store the offset from the start of the table in the
* exception info.
*/
sprintf (symbol, "unwind_info");
emit_section_change (acfg, RODATA_SECT, 1);
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, TRUE);
for (i = 0; i < acfg->unwind_ops->len; ++i) {
guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
guint8 *unwind_info;
guint32 unwind_info_len;
guint8 buf [16];
guint8 *p;
unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
p = buf;
encode_value (unwind_info_len, p, &p);
emit_bytes (acfg, buf, p - buf);
emit_bytes (acfg, unwind_info, unwind_info_len);
acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
}
}
static void
emit_class_info (MonoAotCompile *acfg)
{
int i;
gint32 *offsets;
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
offsets = g_new0 (gint32, rows);
for (i = 0; i < rows; ++i)
offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, rows, 10, offsets);
g_free (offsets);
}
typedef struct ClassNameTableEntry {
guint32 token, index;
struct ClassNameTableEntry *next;
} ClassNameTableEntry;
static void
emit_class_name_table (MonoAotCompile *acfg)
{
int i, table_size, buf_size;
guint32 token, hash;
MonoClass *klass;
GPtrArray *table;
char *full_name;
guint8 *buf, *p;
ClassNameTableEntry *entry, *new_entry;
/*
* Construct a chained hash table for mapping class names to typedef tokens.
*/
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
table_size = g_spaced_primes_closest ((int)(rows * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
hash = mono_metadata_str_hash (full_name) % table_size;
g_free (full_name);
/* FIXME: Allocate from the mempool */
new_entry = g_new0 (ClassNameTableEntry, 1);
new_entry->token = token;
entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
/* Emit the table */
buf_size = table->len * 4 + 4;
p = buf = (guint8 *)g_malloc0 (buf_size);
/* FIXME: Optimize memory usage */
g_assert (table_size < 65000);
encode_int16 (table_size, p, &p);
g_assert (table->len < 65000);
for (i = 0; i < table->len; ++i) {
ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
encode_int16 (0, p, &p);
encode_int16 (0, p, &p);
} else {
encode_int16 (mono_metadata_token_index (entry->token), p, &p);
if (entry->next)
encode_int16 (entry->next->index, p, &p);
else
encode_int16 (0, p, &p);
}
g_free (entry);
}
g_assert (p - buf <= buf_size);
g_ptr_array_free (table, TRUE);
emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
g_free (buf);
}
static void
emit_image_table (MonoAotCompile *acfg)
{
int i, buf_size;
guint8 *buf, *p;
/*
* The image table is small but referenced in a lot of places.
* So we emit it at once, and reference its elements by an index.
*/
buf_size = acfg->image_table->len * 28 + 4;
for (i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
MonoAssemblyName *aname = &image->assembly->aname;
buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
}
buf = p = (guint8 *)g_malloc0 (buf_size);
encode_int (acfg->image_table->len, p, &p);
for (i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
MonoAssemblyName *aname = &image->assembly->aname;
/* FIXME: Support multi-module assemblies */
g_assert (image->assembly->image == image);
encode_string (image->assembly_name, p, &p);
encode_string (image->guid, p, &p);
encode_string (aname->culture ? aname->culture : "", p, &p);
encode_string ((const char*)aname->public_key_token, p, &p);
while (GPOINTER_TO_UINT (p) % 8 != 0)
p ++;
encode_int (aname->flags, p, &p);
encode_int (aname->major, p, &p);
encode_int (aname->minor, p, &p);
encode_int (aname->build, p, &p);
encode_int (aname->revision, p, &p);
}
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
g_free (buf);
}
static void
emit_weak_field_indexes (MonoAotCompile *acfg)
{
GHashTable *indexes;
GHashTableIter iter;
gpointer key, value;
int buf_size;
guint8 *buf, *p;
/* Emit a table of weak field indexes, since computing these at runtime is expensive */
mono_assembly_init_weak_fields (acfg->image);
indexes = acfg->image->weak_field_indexes;
g_assert (indexes);
buf_size = (g_hash_table_size (indexes) + 1) * 4;
buf = p = (guint8 *)g_malloc0 (buf_size);
encode_int (g_hash_table_size (indexes), p, &p);
g_hash_table_iter_init (&iter, indexes);
while (g_hash_table_iter_next (&iter, &key, &value)) {
guint32 index = GPOINTER_TO_UINT (key);
encode_int (index, p, &p);
}
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
g_free (buf);
}
static void
emit_got_info (MonoAotCompile *acfg, gboolean llvm)
{
int i, first_plt_got_patch = 0, buf_size;
guint8 *p, *buf;
guint32 *got_info_offsets;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
/* Add the patches needed by the PLT to the GOT */
if (!llvm) {
acfg->plt_got_offset_base = acfg->got_offset;
acfg->plt_got_info_offset_base = info->got_patches->len;
first_plt_got_patch = acfg->plt_got_info_offset_base;
for (i = 1; i < acfg->plt_offset; ++i) {
MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
g_ptr_array_add (info->got_patches, plt_entry->ji);
acfg->stats.got_slot_types [plt_entry->ji->type] ++;
}
acfg->got_offset += acfg->plt_offset;
}
/**
* FIXME:
* - optimize offsets table.
* - reduce number of exported symbols.
* - emit info for a klass only once.
* - determine when a method uses a GOT slot which is guaranteed to be already
* initialized.
* - clean up and document the code.
* - use String.Empty in class libs.
*/
/* Encode info required to decode shared GOT entries */
buf_size = info->got_patches->len * 128;
p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
if (!llvm) {
acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
/* Unused */
if (acfg->plt_offset)
acfg->plt_got_info_offsets [0] = 0;
}
for (i = 0; i < info->got_patches->len; ++i) {
MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
guint8 *p2;
p = buf;
encode_value (ji->type, p, &p);
p2 = p;
encode_patch (acfg, ji, p, &p);
acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
g_assert (p - buf <= buf_size);
got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
if (!llvm && i >= first_plt_got_patch)
acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
acfg->stats.got_info_size += p - buf;
}
/* Emit got_info_offsets table */
#ifdef MONO_ARCH_CODE_EXEC_ONLY
int got_info_offsets_to_emit = info->got_patches->len;
#else
/* No need to emit offsets for the got plt entries, the plt embeds them directly */
int got_info_offsets_to_emit = first_plt_got_patch;
#endif
acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : got_info_offsets_to_emit, 10, (gint32*)got_info_offsets);
}
static void
emit_got (MonoAotCompile *acfg)
{
char symbol [MAX_SYMBOL_SIZE];
if (acfg->aot_opts.llvm_only)
return;
/* Don't make GOT global so accesses to it don't need relocations */
sprintf (symbol, "%s", acfg->got_symbol);
#ifdef TARGET_MACH
emit_unset_mode (acfg);
fprintf (acfg->fp, ".section __DATA, __bss\n");
emit_alignment (acfg, 8);
if (acfg->llvm)
emit_info_symbol (acfg, "jit_got", FALSE);
fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
#else
emit_section_change (acfg, ".bss", 0);
emit_alignment (acfg, 8);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, "got_end", FALSE);
emit_label (acfg, symbol);
if (acfg->llvm)
emit_info_symbol (acfg, "jit_got", FALSE);
if (acfg->got_offset > 0)
emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
#endif
sprintf (symbol, "got_end");
emit_label (acfg, symbol);
}
typedef struct GlobalsTableEntry {
guint32 value, index;
struct GlobalsTableEntry *next;
} GlobalsTableEntry;
#ifdef TARGET_WIN32_MSVC
#define DLL_ENTRY_POINT "DllMain"
static void
emit_library_info (MonoAotCompile *acfg)
{
// Only include for shared libraries linked directly from generated object.
if (link_shared_library (acfg)) {
char *name = NULL;
char symbol [MAX_SYMBOL_SIZE];
// Ask linker to export all global symbols.
emit_section_change (acfg, ".drectve", 0);
for (guint i = 0; i < acfg->globals->len; ++i) {
name = (char *)g_ptr_array_index (acfg->globals, i);
g_assert (name != NULL);
sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
emit_string (acfg, symbol);
}
// Emit DLLMain function, needed by MSVC linker for DLL's.
// NOTE, DllMain should not go into exports above.
emit_section_change (acfg, ".text", 0);
emit_global (acfg, DLL_ENTRY_POINT, TRUE);
emit_label (acfg, DLL_ENTRY_POINT);
// Simple implementation of DLLMain, just returning TRUE.
// For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
fprintf (acfg->fp, "movl $1, %%eax\n");
fprintf (acfg->fp, "ret\n");
// Inform linker about our dll entry function.
emit_section_change (acfg, ".drectve", 0);
emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
return;
}
}
#else
static void
emit_library_info (MonoAotCompile *acfg)
{
return;
}
#endif
static void
emit_globals (MonoAotCompile *acfg)
{
int i, table_size;
guint32 hash;
GPtrArray *table;
char symbol [1024];
GlobalsTableEntry *entry, *new_entry;
if (!acfg->aot_opts.static_link)
return;
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->globals->len == 0);
return;
}
/*
* When static linking, we emit a table containing our globals.
*/
/*
* Construct a chained hash table for mapping global names to their index in
* the globals table.
*/
table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
hash = mono_metadata_str_hash (name) % table_size;
/* FIXME: Allocate from the mempool */
new_entry = g_new0 (GlobalsTableEntry, 1);
new_entry->value = i;
entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
/* Emit the table */
sprintf (symbol, ".Lglobals_hash");
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
/* FIXME: Optimize memory usage */
g_assert (table_size < 65000);
emit_int16 (acfg, table_size);
for (i = 0; i < table->len; ++i) {
GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
emit_int16 (acfg, 0);
emit_int16 (acfg, 0);
} else {
emit_int16 (acfg, entry->value + 1);
if (entry->next)
emit_int16 (acfg, entry->next->index);
else
emit_int16 (acfg, 0);
}
}
/* Emit the names */
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
sprintf (symbol, "name_%d", i);
emit_section_change (acfg, RODATA_SECT, 1);
#ifdef TARGET_MACH
emit_alignment (acfg, 4);
#endif
emit_label (acfg, symbol);
emit_string (acfg, name);
}
/* Emit the globals table */
sprintf (symbol, "globals");
emit_section_change (acfg, ".data", 0);
/* This is not a global, since it is accessed by the init function */
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, FALSE);
sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
emit_pointer (acfg, symbol);
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
sprintf (symbol, "name_%d", i);
emit_pointer (acfg, symbol);
g_assert (strlen (name) < sizeof (symbol));
sprintf (symbol, "%s", name);
emit_pointer (acfg, symbol);
}
/* Null terminate the table */
emit_int32 (acfg, 0);
emit_int32 (acfg, 0);
}
static void
emit_mem_end (MonoAotCompile *acfg)
{
char symbol [128];
if (acfg->aot_opts.llvm_only)
return;
sprintf (symbol, "mem_end");
emit_section_change (acfg, ".text", 1);
emit_alignment_code (acfg, 8);
emit_label (acfg, symbol);
}
static void
init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
{
int i;
info->version = MONO_AOT_FILE_VERSION;
info->plt_got_offset_base = acfg->plt_got_offset_base;
info->plt_got_info_offset_base = acfg->plt_got_info_offset_base;
info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
info->llvm_got_size = acfg->llvm_got_offset * sizeof (target_mgreg_t);
info->plt_size = acfg->plt_offset;
info->nmethods = acfg->nmethods;
info->call_table_entry_size = acfg->call_table_entry_size;
info->nextra_methods = acfg->nextra_methods;
info->flags = acfg->flags;
info->opts = acfg->jit_opts;
info->simd_opts = acfg->simd_opts;
info->gc_name_index = acfg->gc_name_offset;
info->datafile_size = acfg->datafile_offset;
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
info->table_offsets [i] = acfg->table_offsets [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->num_trampolines [i] = acfg->num_trampolines [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->trampoline_size [i] = acfg->trampoline_size [i];
info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
int card_table_shift_bits = 0;
target_mgreg_t card_table_mask = 0;
mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
/*
* Sanity checking variables used to make sure the host and target
* environment matches when cross compiling.
*/
info->double_align = MONO_ABI_ALIGNOF (double);
info->long_align = MONO_ABI_ALIGNOF (gint64);
info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
info->card_table_shift_bits = card_table_shift_bits;
info->card_table_mask = card_table_mask;
info->tramp_page_size = acfg->tramp_page_size;
info->nshared_got_entries = acfg->nshared_got_entries;
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
memcpy(&info->aotid, acfg->image->aotid, 16);
}
static void
emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
{
char symbol [MAX_SYMBOL_SIZE];
int i, sindex;
const char **symbols;
symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
sindex = 0;
symbols [sindex ++] = acfg->got_symbol;
if (acfg->llvm) {
symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
} else {
symbols [sindex ++] = NULL;
}
/* llvm_get_method */
symbols [sindex ++] = NULL;
/* llvm_get_unbox_tramp */
symbols [sindex ++] = NULL;
/* llvm_init_aotconst */
symbols [sindex ++] = NULL;
if (!acfg->aot_opts.llvm_only) {
symbols [sindex ++] = "jit_code_start";
symbols [sindex ++] = "jit_code_end";
symbols [sindex ++] = "method_addresses";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
if (acfg->data_outfile) {
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
symbols [sindex ++] = NULL;
} else {
symbols [sindex ++] = "blob";
symbols [sindex ++] = "class_name_table";
symbols [sindex ++] = "class_info_offsets";
symbols [sindex ++] = "method_info_offsets";
symbols [sindex ++] = "ex_info_offsets";
symbols [sindex ++] = "extra_method_info_offsets";
symbols [sindex ++] = "extra_method_table";
symbols [sindex ++] = "got_info_offsets";
if (acfg->llvm)
symbols [sindex ++] = "llvm_got_info_offsets";
else
symbols [sindex ++] = NULL;
symbols [sindex ++] = "image_table";
symbols [sindex ++] = "weak_field_indexes";
symbols [sindex ++] = "method_flags_table";
}
symbols [sindex ++] = "mem_end";
symbols [sindex ++] = "assembly_guid";
symbols [sindex ++] = "runtime_version";
if (acfg->num_trampoline_got_entries) {
symbols [sindex ++] = "specific_trampolines";
symbols [sindex ++] = "static_rgctx_trampolines";
symbols [sindex ++] = "imt_trampolines";
symbols [sindex ++] = "gsharedvt_arg_trampolines";
symbols [sindex ++] = "ftnptr_arg_trampolines";
symbols [sindex ++] = "unbox_arbitrary_trampolines";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
if (acfg->aot_opts.static_link) {
symbols [sindex ++] = "globals";
} else {
symbols [sindex ++] = NULL;
}
symbols [sindex ++] = "assembly_name";
symbols [sindex ++] = "plt";
symbols [sindex ++] = "plt_end";
symbols [sindex ++] = "unwind_info";
if (!acfg->aot_opts.llvm_only) {
symbols [sindex ++] = "unbox_trampolines";
symbols [sindex ++] = "unbox_trampolines_end";
symbols [sindex ++] = "unbox_trampoline_addresses";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
emit_section_change (acfg, ".data", 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
if (!acfg->aot_opts.static_link)
emit_global (acfg, symbol, FALSE);
/* The data emitted here must match MonoAotFileInfo. */
emit_int32 (acfg, info->version);
emit_int32 (acfg, info->dummy);
/*
* We emit pointers to our data structures instead of emitting global symbols which
* point to them, to reduce the number of globals, and because using globals leads to
* various problems (i.e. arm/thumb).
*/
for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
emit_pointer (acfg, symbols [i]);
emit_int32 (acfg, info->plt_got_offset_base);
emit_int32 (acfg, info->plt_got_info_offset_base);
emit_int32 (acfg, info->got_size);
emit_int32 (acfg, info->llvm_got_size);
emit_int32 (acfg, info->plt_size);
emit_int32 (acfg, info->nmethods);
emit_int32 (acfg, info->nextra_methods);
emit_int32 (acfg, info->flags);
emit_int32 (acfg, info->opts);
emit_int32 (acfg, info->simd_opts);
emit_int32 (acfg, info->gc_name_index);
emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
emit_int32 (acfg, info->double_align);
emit_int32 (acfg, info->long_align);
emit_int32 (acfg, info->generic_tramp_num);
emit_int32 (acfg, info->card_table_shift_bits);
emit_int32 (acfg, info->card_table_mask);
emit_int32 (acfg, info->tramp_page_size);
emit_int32 (acfg, info->call_table_entry_size);
emit_int32 (acfg, info->nshared_got_entries);
emit_int32 (acfg, info->datafile_size);
emit_int32 (acfg, 0);
emit_int32 (acfg, 0);
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
emit_int32 (acfg, info->table_offsets [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->num_trampolines [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->trampoline_got_offset_base [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->trampoline_size [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->tramp_page_code_offsets [i]);
emit_bytes (acfg, info->aotid, 16);
if (acfg->aot_opts.static_link) {
emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
emit_alignment (acfg, sizeof (target_mgreg_t));
emit_label (acfg, acfg->static_linking_symbol);
emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
}
}
/*
* Emit a structure containing all the information not stored elsewhere.
*/
static void
emit_file_info (MonoAotCompile *acfg)
{
char *build_info;
MonoAotFileInfo *info;
if (acfg->aot_opts.bind_to_runtime_version) {
build_info = mono_get_runtime_build_info ();
emit_string_symbol (acfg, "runtime_version", build_info);
g_free (build_info);
} else {
emit_string_symbol (acfg, "runtime_version", "");
}
emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
/* Emit a string holding the assembly name */
emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
info = g_new0 (MonoAotFileInfo, 1);
init_aot_file_info (acfg, info);
if (acfg->aot_opts.static_link) {
char symbol [MAX_SYMBOL_SIZE];
char *p;
/*
* Emit a global symbol which can be passed by an embedding app to
* mono_aot_register_module (). The symbol points to a pointer to the the file info
* structure.
*/
sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
/* Get rid of characters which cannot occur in symbols */
p = symbol;
for (p = symbol; *p; ++p) {
if (!(isalnum (*p) || *p == '_'))
*p = '_';
}
acfg->static_linking_symbol = g_strdup (symbol);
}
if (acfg->llvm)
mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
else
emit_aot_file_info (acfg, info);
}
static void
emit_blob (MonoAotCompile *acfg)
{
acfg->blob_closed = TRUE;
emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
}
static void
emit_objc_selectors (MonoAotCompile *acfg)
{
int i;
char symbol [128];
if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
return;
/*
* From
* cat > foo.m << EOF
* void *ret ()
* {
* return @selector(print:);
* }
* EOF
*/
mono_img_writer_emit_unset_mode (acfg->w);
g_assert (acfg->fp);
fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
fprintf (acfg->fp, ".align 3\n");
for (i = 0; i < acfg->objc_selectors->len; ++i) {
sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
emit_label (acfg, symbol);
sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
emit_pointer (acfg, symbol);
}
fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
for (i = 0; i < acfg->objc_selectors->len; ++i) {
fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
}
fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
fprintf (acfg->fp, ".align 3\n");
fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
fprintf (acfg->fp, ".long 0\n");
fprintf (acfg->fp, ".long 16\n");
}
static void
emit_dwarf_info (MonoAotCompile *acfg)
{
#ifdef EMIT_DWARF_INFO
int i;
char symbol2 [128];
/* DIEs for methods */
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
// FIXME: LLVM doesn't define .Lme_...
if (cfg->compile_llvm)
continue;
sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
MonoDebugMethodJitInfo *jit_debug_info = mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ());
mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, jit_debug_info);
mono_debug_free_method_jit_info (jit_debug_info);
}
#endif
}
#ifdef EMIT_WIN32_CODEVIEW_INFO
typedef struct _CodeViewSubSectionData
{
gchar *start_section;
gchar *end_section;
gchar *start_section_record;
gchar *end_section_record;
int section_type;
int section_record_type;
int section_id;
} CodeViewSubsectionData;
typedef struct _CodeViewCompilerVersion
{
gint major;
gint minor;
gint revision;
gint patch;
} CodeViewCompilerVersion;
#define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
#define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
#define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
#define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
#define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
#define CODEVIEW_CPU_TYPE 0x0
#define CODEVIEW_MAGIC_HEADER 0x4
static void
codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
{
g_free (section_data->start_section);
g_free (section_data->end_section);
g_free (section_data->start_section_record);
g_free (section_data->end_section_record);
memset (section_data, 0, sizeof (CodeViewSubsectionData));
}
static void
codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
{
gint values[4] = { 0 };
gint *value = values;
while (*version && (value < values + G_N_ELEMENTS (values))) {
if (isdigit (*version)) {
*value *= 10;
*value += *version - '0';
}
else if (*version == '.') {
value++;
}
version++;
}
data->major = values[0];
data->minor = values[1];
data->revision = values[2];
data->patch = values[3];
}
static void
emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
{
// Starting a new subsection, clear old data.
codeview_clear_subsection_data (section_data);
// Keep subsection data.
section_data->section_id = section_id;
section_data->section_type = section_type;
section_data->section_record_type = section_record_type;
// Allocate all labels used in subsection.
section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
// Subsection type, function symbol.
emit_int32 (acfg, section_data->section_type);
// Subsection size.
emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
emit_label (acfg, section_data->start_section);
// Subsection record size.
fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
emit_label (acfg, section_data->start_section_record);
// Subsection record type.
emit_int16 (acfg, section_record_type);
}
static void
emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
{
g_assert (section_data->start_section);
g_assert (section_data->end_section);
g_assert (section_data->start_section_record);
g_assert (section_data->end_section_record);
emit_label (acfg, section_data->end_section_record);
if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
// Emit record length.
emit_int16 (acfg, 2);
// Emit specific record type end.
emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
}
emit_label (acfg, section_data->end_section);
// Next subsection needs to be 4 byte aligned.
emit_alignment (acfg, 4);
*section_id = section_data->section_id + 1;
codeview_clear_subsection_data (section_data);
}
inline static void
emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
{
emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
}
inline static void
emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
{
emit_codeview_end_subsection (acfg, section_data, section_id);
}
static void
emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
{
CodeViewSubsectionData section_data = { 0 };
CodeViewCompilerVersion compiler_version = { 0 };
// Start new compiler record subsection.
emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, §ion_data);
emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
emit_int16 (acfg, CODEVIEW_CPU_TYPE);
// Get compiler version information.
codeview_parse_compiler_version (VERSION, &compiler_version);
// Compiler frontend version, 4 digits.
emit_int16 (acfg, compiler_version.major);
emit_int16 (acfg, compiler_version.minor);
emit_int16 (acfg, compiler_version.revision);
emit_int16 (acfg, compiler_version.patch);
// Compiler backend version, 4 digits (currently same as frontend).
emit_int16 (acfg, compiler_version.major);
emit_int16 (acfg, compiler_version.minor);
emit_int16 (acfg, compiler_version.revision);
emit_int16 (acfg, compiler_version.patch);
// Compiler string.
emit_string (acfg, "Mono AOT compiler");
// Done with section.
emit_codeview_end_symbol_subsection (acfg, §ion_data, section_id);
}
static void
emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
{
CodeViewSubsectionData section_data = { 0 };
gchar *full_method_name = NULL;
// Start new function record subsection.
emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, §ion_data);
// Emit 3 int 0 byte padding, currently not used.
emit_zero_bytes (acfg, sizeof (int) * 3);
// Emit size of function.
emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
// Emit 3 int 0 byte padding, currently not used.
emit_zero_bytes (acfg, sizeof (int) * 3);
// Emit reallocation info.
fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
fprintf (acfg->fp, "\t.secidx %s\n", symbol);
// Emit flag, currently not used.
emit_zero_bytes (acfg, 1);
// Emit function name, exclude signature since it should be described by own metadata.
full_method_name = mono_method_full_name (method, FALSE);
emit_string (acfg, full_method_name ? full_method_name : "");
g_free (full_method_name);
// Done with section.
emit_codeview_end_symbol_subsection (acfg, §ion_data, section_id);
}
static void
emit_codeview_info (MonoAotCompile *acfg)
{
int i;
int section_id = 0;
gchar symbol_buffer[MAX_SYMBOL_SIZE];
// Emit codeview debug info section
emit_section_change (acfg, ".debug$S", 0);
// Emit magic header.
emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
emit_codeview_compiler_info (acfg, §ion_id);
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg = acfg->cfgs[i];
if (!cfg || COMPILE_LLVM (cfg))
continue;
int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
emit_codeview_function_info (acfg, cfg->method, §ion_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
}
}
#else
static void
emit_codeview_info (MonoAotCompile *acfg)
{
}
#endif /* EMIT_WIN32_CODEVIEW_INFO */
#ifdef EMIT_WIN32_UNWIND_INFO
static UnwindInfoSectionCacheItem *
get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
UnwindInfoSectionCacheItem *item = NULL;
if (!acfg->unwind_info_section_cache)
acfg->unwind_info_section_cache = g_list_alloc ();
PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
// Search for unwind info in cache.
GList *list = acfg->unwind_info_section_cache;
int list_size = 0;
while (list && list->data) {
item = (UnwindInfoSectionCacheItem*)list->data;
if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
// Cache hit, return cached item.
return item;
}
list = list->next;
list_size++;
}
// Add to cache.
if (acfg->unwind_info_section_cache) {
item = g_new0 (UnwindInfoSectionCacheItem, 1);
if (item) {
// Format .xdata section label for function, used to get unwind info address RVA.
// Since the unwind info is similar for most functions, the symbol will be reused.
item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
// Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
//over ownership of unwind info.
item->unwind_info = unwind_info;
// Needs to be emitted once.
item->xdata_section_emitted = FALSE;
// Prepend to beginning of list to speed up inserts.
acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
}
}
return item;
}
static void
free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
{
GList *list = acfg->unwind_info_section_cache;
while (list) {
UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
if (item) {
g_free (item->xdata_section_label);
mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
g_free (item);
list->data = NULL;
}
list = list->next;
}
g_list_free (acfg->unwind_info_section_cache);
acfg->unwind_info_section_cache = NULL;
}
static void
emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
{
// Emit the unwind info struct.
emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
// Emit all unwind codes encoded in unwind info struct.
PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
while (current_unwind_node < last_unwind_node) {
guint8 node_count = 0;
switch (current_unwind_node->UnwindOp) {
case UWOP_PUSH_NONVOL:
case UWOP_ALLOC_SMALL:
case UWOP_SET_FPREG:
case UWOP_PUSH_MACHFRAME:
node_count = 1;
break;
case UWOP_SAVE_NONVOL:
case UWOP_SAVE_XMM128:
node_count = 2;
break;
case UWOP_SAVE_NONVOL_FAR:
case UWOP_SAVE_XMM128_FAR:
node_count = 3;
break;
case UWOP_ALLOC_LARGE:
if (current_unwind_node->OpInfo == 0)
node_count = 2;
else
node_count = 3;
break;
default:
g_assert (!"Unknown unwind opcode.");
}
while (node_count > 0) {
g_assert (current_unwind_node < last_unwind_node);
//Emit current node.
emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
node_count--;
current_unwind_node++;
}
}
}
// Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
// .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
// UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
// .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
static void
emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
char *pdata_section_label = NULL;
int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
temp_prefix_len = 0;
}
// Format .pdata section label for function.
pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
// Emit .pdata section.
emit_section_change (acfg, ".pdata", 0);
emit_alignment (acfg, sizeof (DWORD));
emit_label (acfg, pdata_section_label);
// Emit function start address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
// Emit function end address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
// Emit unwind info address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
if (!cache_item->xdata_section_emitted) {
// Emit .xdata section.
emit_section_change (acfg, ".xdata", 0);
emit_alignment (acfg, sizeof (DWORD));
emit_label (acfg, cache_item->xdata_section_label);
// Emit unwind info into .xdata section.
emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
cache_item->xdata_section_emitted = TRUE;
}
g_free (pdata_section_label);
}
#endif
static gboolean
should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
{
#ifdef TARGET_WASM
if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
/* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
return FALSE;
#endif
if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Volatile"))
/* Read<T>/Write<T> are not needed and cause JIT failures */
return FALSE;
return TRUE;
}
static gboolean
collect_methods (MonoAotCompile *acfg)
{
int mindex, i;
MonoImage *image = acfg->image;
/* Collect methods */
int rows = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (!method) {
aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
return FALSE;
}
/* Load all methods eagerly to skip the slower lazy loading code */
mono_class_setup_methods (method->klass);
if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
/* Compile the wrapper instead */
/* We do this here instead of add_wrappers () because it is easy to do it here */
MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
method = wrapper;
}
/* FIXME: Some mscorlib methods don't have debug info */
/*
if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
if (!mono_debug_lookup_method (method)) {
fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
exit (1);
}
}
}
*/
if (method->is_generic || mono_class_is_gtd (method->klass)) {
/* Compile the ref shared version instead */
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
if (!method) {
aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
return FALSE;
}
}
/* Since we add the normal methods first, their index will be equal to their zero based token index */
add_method_with_index (acfg, method, i, FALSE);
acfg->method_index ++;
}
/* gsharedvt methods */
rows = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
for (mindex = 0; mindex < rows; ++mindex) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
if (!(acfg->jit_opts & MONO_OPT_GSHAREDVT))
continue;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
MonoMethod *gshared;
gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
}
if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
add_generic_instances (acfg);
if (mono_aot_mode_is_full (&acfg->aot_opts))
add_wrappers (acfg);
return TRUE;
}
static void
compile_methods (MonoAotCompile *acfg)
{
int i, methods_len;
if (acfg->aot_opts.nthreads > 0) {
GPtrArray *frag;
int len, j;
GPtrArray *threads;
MonoThreadHandle *thread_handle;
gpointer *user_data;
MonoMethod **methods;
methods_len = acfg->methods->len;
len = acfg->methods->len / acfg->aot_opts.nthreads;
g_assert (len > 0);
/*
* Partition the list of methods into fragments, and hand it to threads to
* process.
*/
threads = g_ptr_array_new ();
/* Make a copy since acfg->methods is modified by compile_method () */
methods = g_new0 (MonoMethod*, methods_len);
//memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
for (i = 0; i < methods_len; ++i)
methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
i = 0;
while (i < methods_len) {
ERROR_DECL (error);
MonoInternalThread *thread;
frag = g_ptr_array_new ();
for (j = 0; j < len; ++j) {
if (i < methods_len) {
g_ptr_array_add (frag, methods [i]);
i ++;
}
}
user_data = g_new0 (gpointer, 3);
user_data [0] = acfg;
user_data [1] = frag;
thread = mono_thread_create_internal ((MonoThreadStart)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
mono_error_assert_ok (error);
thread_handle = mono_threads_open_thread_handle (thread->handle);
g_ptr_array_add (threads, thread_handle);
}
g_free (methods);
for (i = 0; i < threads->len; ++i) {
mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
}
} else {
methods_len = 0;
}
/* Compile methods added by compile_method () or all methods if nthreads == 0 */
for (i = methods_len; i < acfg->methods->len; ++i) {
/* This can add new methods to acfg->methods */
compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
}
#ifdef ENABLE_LLVM
if (acfg->llvm)
mono_llvm_fixup_aot_module ();
#endif
}
static int
compile_asm (MonoAotCompile *acfg)
{
char *command, *objfile;
char *outfile_name, *tmp_outfile_name, *llvm_ofile;
const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
#ifdef TARGET_WIN32_MSVC
#define AS_OPTIONS "--target=x86_64-pc-windows-msvc -c -x assembler"
#elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
#define AS_OPTIONS "--64"
#elif defined(TARGET_POWERPC64)
#define AS_OPTIONS "-a64 -mppc64"
#elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
#define AS_OPTIONS "-xarch=v9"
#elif defined(TARGET_X86) && defined(TARGET_MACH)
#define AS_OPTIONS "-arch i386"
#elif defined(TARGET_X86) && !defined(TARGET_MACH)
#define AS_OPTIONS "--32"
#elif defined(MONO_ARCH_ENABLE_PTRAUTH)
#define AS_OPTIONS "-arch arm64e"
#else
#define AS_OPTIONS ""
#endif
#if defined(TARGET_OSX)
#define AS_NAME "clang"
#elif defined(TARGET_WIN32_MSVC)
#define AS_NAME "clang.exe"
#else
#define AS_NAME "as"
#endif
#ifdef TARGET_WIN32_MSVC
#define AS_OBJECT_FILE_SUFFIX "obj"
#else
#define AS_OBJECT_FILE_SUFFIX "o"
#endif
#if defined(sparc)
#define LD_NAME "ld"
#define LD_OPTIONS "-shared -G -Bsymbolic"
#elif defined(__ppc__) && defined(TARGET_MACH)
#define LD_NAME "gcc"
#define LD_OPTIONS "-dynamiclib -Wl,-Bsymbolic"
#elif defined(TARGET_AMD64) && defined(TARGET_MACH)
#define LD_NAME "clang"
#define LD_OPTIONS "--shared"
#elif defined(TARGET_ARM64) && defined(TARGET_OSX)
#define LD_NAME "clang"
#if defined(TARGET_OSX) && __has_feature(ptrauth_intrinsics)
#define LD_OPTIONS "--shared -arch arm64e"
#else
#define LD_OPTIONS "--shared"
#endif
#elif defined(TARGET_WIN32_MSVC)
#define LD_NAME "link.exe"
#define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
#define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
#elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
#define LD_NAME "gcc"
#define LD_OPTIONS "-shared -Wl,-Bsymbolic"
#elif defined(TARGET_X86) && defined(TARGET_MACH)
#define LD_NAME "clang"
#define LD_OPTIONS "-m32 -dynamiclib"
#elif defined(TARGET_X86) && !defined(TARGET_MACH)
#define LD_OPTIONS "-m elf_i386 -Bsymbolic"
#elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
#define LD_NAME "gcc"
#define LD_OPTIONS "--shared -Wl,-Bsymbolic"
#elif defined(TARGET_POWERPC64)
#define LD_OPTIONS "-m elf64ppc -Bsymbolic"
#endif
#ifndef LD_OPTIONS
#define LD_OPTIONS "-Bsymbolic"
#endif
if (acfg->aot_opts.asm_only) {
aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
if (acfg->aot_opts.static_link)
aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
if (acfg->llvm)
aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
return 0;
}
if (acfg->aot_opts.static_link) {
if (acfg->aot_opts.outfile)
objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
} else {
objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
}
#ifdef TARGET_OSX
g_string_append (acfg->as_args, "-c -x assembler ");
#endif
command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
acfg->as_args ? acfg->as_args->str : "",
wrap_path (objfile), wrap_path (acfg->tmpfname));
aot_printf (acfg, "Executing the native assembler: %s\n", command);
if (execute_system (command) != 0) {
g_free (command);
g_free (objfile);
return 1;
}
if (acfg->llvm && !acfg->llvm_owriter) {
command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
acfg->as_args ? acfg->as_args->str : "",
wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
aot_printf (acfg, "Executing the native assembler: %s\n", command);
if (execute_system (command) != 0) {
g_free (command);
g_free (objfile);
return 1;
}
}
g_free (command);
if (acfg->aot_opts.static_link) {
aot_printf (acfg, "Output file: '%s'.\n", objfile);
aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
g_free (objfile);
return 0;
}
if (acfg->aot_opts.outfile)
outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
if (acfg->llvm) {
llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
} else {
llvm_ofile = g_strdup ("");
}
/* replace the ; flags separators with spaces */
g_strdelimit (ld_flags, ';', ' ');
if (acfg->aot_opts.llvm_only)
ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
#ifdef TARGET_WIN32_MSVC
g_assert (tmp_outfile_name != NULL);
g_assert (objfile != NULL);
command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
#else
GString *str;
str = g_string_new ("");
const char *ld_binary_name = acfg->aot_opts.ld_name;
#if defined(LD_NAME)
if (ld_binary_name == NULL) {
ld_binary_name = LD_NAME;
}
g_string_append_printf (str, "%s%s %s", tool_prefix, ld_binary_name, LD_OPTIONS);
#else
if (ld_binary_name == NULL) {
ld_binary_name = "ld";
}
// Default (linux)
if (acfg->aot_opts.tool_prefix)
/* Cross compiling */
g_string_append_printf (str, "\"%s%s\" %s", tool_prefix, ld_binary_name, LD_OPTIONS);
else if (acfg->aot_opts.llvm_only)
g_string_append_printf (str, "%s", acfg->aot_opts.clangxx);
else
g_string_append_printf (str, "\"%s%s\"", tool_prefix, ld_binary_name);
g_string_append_printf (str, " -shared");
#endif
g_string_append_printf (str, " -o %s %s %s %s",
wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
#if defined(TARGET_MACH)
g_string_append_printf (str, " \"-Wl,-install_name,%s%s\"", g_path_get_basename (acfg->image->name), MONO_SOLIB_EXT);
#endif
command = g_string_free (str, FALSE);
#endif
aot_printf (acfg, "Executing the native linker: %s\n", command);
if (execute_system (command) != 0) {
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (command);
g_free (objfile);
g_free (ld_flags);
return 1;
}
g_free (command);
/*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
printf ("Stripping the binary: %s\n", com);
execute_system (com);
g_free (com);*/
#if defined(TARGET_ARM) && !defined(TARGET_MACH)
/*
* gas generates 'mapping symbols' each time code and data is mixed, which
* happens a lot in emit_and_reloc_code (), so we need to get rid of them.
*/
command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, wrap_path(tmp_outfile_name));
aot_printf (acfg, "Stripping the binary: %s\n", command);
if (execute_system (command) != 0) {
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (command);
g_free (objfile);
return 1;
}
#endif
if (0 != rename (tmp_outfile_name, outfile_name)) {
if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
/* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
unlink (outfile_name);
rename (tmp_outfile_name, outfile_name);
}
}
#if defined(TARGET_MACH)
command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
aot_printf (acfg, "Executing dsymutil: %s\n", command);
if (execute_system (command) != 0) {
return 1;
}
#endif
if (!acfg->aot_opts.save_temps)
unlink (objfile);
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (objfile);
if (acfg->aot_opts.save_temps)
aot_printf (acfg, "Retained input file.\n");
else
unlink (acfg->tmpfname);
return 0;
}
static guint8
profread_byte (FILE *infile)
{
guint8 i;
int res;
res = fread (&i, 1, 1, infile);
g_assert (res == 1);
return i;
}
static int
profread_int (FILE *infile)
{
int i, res;
res = fread (&i, 4, 1, infile);
g_assert (res == 1);
return i;
}
static char*
profread_string (FILE *infile)
{
int len, res;
char *pbuf;
len = profread_int (infile);
pbuf = (char*)g_malloc (len + 1);
res = fread (pbuf, 1, len, infile);
g_assert (res == len);
pbuf [len] = '\0';
return pbuf;
}
static void
load_profile_file (MonoAotCompile *acfg, char *filename)
{
FILE *infile;
char buf [1024];
int res, len, version;
char magic [32];
infile = fopen (filename, "rb");
if (!infile) {
fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
exit (1);
}
printf ("Using profile data file '%s'\n", filename);
sprintf (magic, AOT_PROFILER_MAGIC);
len = strlen (magic);
res = fread (buf, 1, len, infile);
magic [len] = '\0';
buf [len] = '\0';
if ((res != len) || strcmp (buf, magic) != 0) {
printf ("Profile file has wrong header: '%s'.\n", buf);
fclose (infile);
exit (1);
}
guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
version = profread_int (infile);
if (version != expected_version) {
printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
fclose (infile);
exit (1);
}
ProfileData *data = g_new0 (ProfileData, 1);
data->images = g_hash_table_new (NULL, NULL);
data->classes = g_hash_table_new (NULL, NULL);
data->ginsts = g_hash_table_new (NULL, NULL);
data->methods = g_hash_table_new (NULL, NULL);
while (TRUE) {
int type = profread_byte (infile);
int id = profread_int (infile);
if (type == AOTPROF_RECORD_NONE)
break;
switch (type) {
case AOTPROF_RECORD_IMAGE: {
ImageProfileData *idata = g_new0 (ImageProfileData, 1);
idata->name = profread_string (infile);
char *mvid = profread_string (infile);
g_free (mvid);
g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
break;
}
case AOTPROF_RECORD_GINST: {
int i;
int len = profread_int (infile);
GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
gdata->argc = len;
gdata->argv = g_new0 (ClassProfileData*, len);
for (i = 0; i < len; ++i) {
int class_id = profread_int (infile);
gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
g_assert (gdata->argv [i]);
}
g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
break;
}
case AOTPROF_RECORD_TYPE: {
int type = profread_byte (infile);
switch (type) {
case MONO_TYPE_CLASS: {
int image_id = profread_int (infile);
int ginst_id = profread_int (infile);
char *class_name = profread_string (infile);
ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
g_assert (image);
char *p = strrchr (class_name, '.');
g_assert (p);
*p = '\0';
ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
cdata->image = image;
cdata->ns = g_strdup (class_name);
cdata->name = g_strdup (p + 1);
if (ginst_id != -1) {
cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
g_assert (cdata->inst);
}
g_free (class_name);
g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
break;
}
#if 0
case MONO_TYPE_SZARRAY: {
int elem_id = profread_int (infile);
// FIXME:
break;
}
#endif
default:
g_assert_not_reached ();
break;
}
break;
}
case AOTPROF_RECORD_METHOD: {
int class_id = profread_int (infile);
int ginst_id = profread_int (infile);
int param_count = profread_int (infile);
char *method_name = profread_string (infile);
char *sig = profread_string (infile);
ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
g_assert (klass);
MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
mdata->id = id;
mdata->klass = klass;
mdata->name = method_name;
mdata->signature = sig;
mdata->param_count = param_count;
if (ginst_id != -1) {
mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
g_assert (mdata->inst);
}
g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
break;
}
default:
printf ("%d\n", type);
g_assert_not_reached ();
break;
}
}
fclose (infile);
acfg->profile_data = g_list_append (acfg->profile_data, data);
}
static void
resolve_class (ClassProfileData *cdata);
static void
resolve_ginst (GInstProfileData *inst_data)
{
int i;
if (inst_data->inst)
return;
for (i = 0; i < inst_data->argc; ++i) {
resolve_class (inst_data->argv [i]);
if (!inst_data->argv [i]->klass)
return;
}
MonoType **args = g_new0 (MonoType*, inst_data->argc);
for (i = 0; i < inst_data->argc; ++i)
args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
}
static void
resolve_class (ClassProfileData *cdata)
{
ERROR_DECL (error);
MonoClass *klass;
if (!cdata->image->image)
return;
klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
if (!klass) {
//printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
return;
}
if (cdata->inst) {
resolve_ginst (cdata->inst);
if (!cdata->inst->inst) {
/*
* The instance might not be found if its arguments are in another assembly,
* use the definition instead.
*/
cdata->klass = klass;
//printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
return;
}
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
ctx.class_inst = cdata->inst->inst;
cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
} else {
cdata->klass = klass;
}
}
/*
* Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
*/
static void
resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
{
GHashTableIter iter;
gpointer key, value;
int i;
if (!data)
return;
/* Images */
GPtrArray *assemblies = mono_alc_get_all_loaded_assemblies ();
g_hash_table_iter_init (&iter, data->images);
while (g_hash_table_iter_next (&iter, &key, &value)) {
ImageProfileData *idata = (ImageProfileData*)value;
if (!strcmp (current->aname.name, idata->name)) {
idata->image = current->image;
continue;
}
for (i = 0; i < assemblies->len; ++i) {
MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
if (!strcmp (ass->aname.name, idata->name)) {
idata->image = ass->image;
break;
}
}
}
g_ptr_array_free (assemblies, TRUE);
/* Classes */
g_hash_table_iter_init (&iter, data->classes);
while (g_hash_table_iter_next (&iter, &key, &value)) {
ClassProfileData *cdata = (ClassProfileData*)value;
if (!cdata->image->image) {
if (acfg->aot_opts.verbose)
printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
continue;
}
resolve_class (cdata);
/*
if (cdata->klass)
printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
*/
}
/* Methods */
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoClass *klass;
MonoMethod *m;
gpointer miter;
resolve_class (mdata->klass);
klass = mdata->klass->klass;
if (!klass) {
if (acfg->aot_opts.verbose)
printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
continue;
}
miter = NULL;
while ((m = mono_class_get_methods (klass, &miter))) {
ERROR_DECL (error);
if (strcmp (m->name, mdata->name))
continue;
MonoMethodSignature *sig = mono_method_signature_internal (m);
if (!sig)
continue;
if (sig->param_count != mdata->param_count)
continue;
if (mdata->inst) {
resolve_ginst (mdata->inst);
if (mdata->inst->inst) {
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
ctx.method_inst = mdata->inst->inst;
m = mono_class_inflate_generic_method_checked (m, &ctx, error);
if (!m)
continue;
sig = mono_method_signature_checked (m, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
continue;
}
} else {
/* Use the generic definition */
mdata->method = m;
break;
}
}
char *sig_str = mono_signature_full_name (sig);
gboolean match = !strcmp (sig_str, mdata->signature);
g_free (sig_str);
if (!match) {
// The signature might not match for methods on gtds
if (!mono_class_is_gtd (klass))
continue;
}
//printf ("%s\n", mono_method_full_name (m, 1));
mdata->method = m;
break;
}
if (!mdata->method) {
if (acfg->aot_opts.verbose)
printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
}
}
}
static gboolean
inst_references_image (MonoGenericInst *inst, MonoImage *image)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
if (m_class_get_image (k) == image)
return TRUE;
if (mono_class_is_ginst (k)) {
MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
if (inst_references_image (kinst, image))
return TRUE;
}
}
return FALSE;
}
static gboolean
is_local_inst (MonoGenericInst *inst, MonoImage *image)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
return FALSE;
}
return TRUE;
}
static void
add_profile_method (MonoAotCompile *acfg, MonoMethod *m)
{
g_hash_table_insert (acfg->profile_methods, m, m);
add_extra_method (acfg, m);
}
static void
add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
{
GHashTableIter iter;
gpointer key, value;
int count = 0;
if (!data)
return;
if (acfg->aot_opts.profile_only) {
/* Add methods referenced by the profile */
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoMethod *m = mdata->method;
if (!m)
continue;
if (m->is_inflated)
continue;
if (m_class_get_image (m->klass) != acfg->image)
continue;
add_profile_method (acfg, m);
count ++;
}
}
/*
* Add method instances 'related' to this assembly to the AOT image.
*/
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoMethod *m = mdata->method;
MonoGenericContext *ctx;
if (!m)
continue;
if (!m->is_inflated)
continue;
if (mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
if (acfg->aot_opts.profile_only && m_class_get_image (m->klass) == acfg->image) {
// Add the fully shared version to its home image
add_profile_method (acfg, m);
count ++;
}
continue;
}
if (acfg->aot_opts.dedup_include) {
/* Add all instances from the profile */
add_profile_method (acfg, m);
count ++;
} else {
ctx = mono_method_get_context (m);
/* For simplicity, add instances which reference the assembly we are compiling */
if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
(ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image)))) {
//printf ("%s\n", mono_method_full_name (m, TRUE));
add_profile_method (acfg, m);
count ++;
} else if (m_class_get_image (m->klass) == acfg->image &&
((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
(ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image)))) {
/* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
//printf ("%s\n", mono_method_full_name (m, TRUE));
add_profile_method (acfg, m);
count ++;
} else {
//printf ("SKIP: %s (%s)\n", mono_method_get_full_name (m), acfg->image->name);
}
/*
* FIXME: We might skip some instances, for example:
* Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
* and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
*/
}
}
printf ("Added %d methods from profile.\n", count);
}
static void
init_got_info (GotInfo *info)
{
int i;
info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
info->got_patches = g_ptr_array_new ();
}
static MonoAotCompile*
acfg_create (MonoAssembly *ass, guint32 jit_opts)
{
MonoImage *image = ass->image;
MonoAotCompile *acfg;
acfg = g_new0 (MonoAotCompile, 1);
acfg->methods = g_ptr_array_new ();
acfg->method_indexes = g_hash_table_new (NULL, NULL);
acfg->method_depth = g_hash_table_new (NULL, NULL);
acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
acfg->image_hash = g_hash_table_new (NULL, NULL);
acfg->image_table = g_ptr_array_new ();
acfg->globals = g_ptr_array_new ();
acfg->image = image;
acfg->jit_opts = jit_opts;
acfg->mempool = mono_mempool_new ();
acfg->extra_methods = g_ptr_array_new ();
acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
acfg->unwind_ops = g_ptr_array_new ();
acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
acfg->method_order = g_ptr_array_new ();
acfg->export_names = g_hash_table_new (NULL, NULL);
acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
acfg->profile_methods = g_hash_table_new (NULL, NULL);
mono_os_mutex_init_recursive (&acfg->mutex);
init_got_info (&acfg->got_info);
init_got_info (&acfg->llvm_got_info);
method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
return acfg;
}
static void
got_info_free (GotInfo *info)
{
int i;
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
g_free (info->patch_to_got_offset_by_type);
g_hash_table_destroy (info->patch_to_got_offset);
g_ptr_array_free (info->got_patches, TRUE);
}
static void
acfg_free (MonoAotCompile *acfg)
{
int i;
mono_img_writer_destroy (acfg->w);
for (i = 0; i < acfg->nmethods; ++i)
if (acfg->cfgs [i])
mono_destroy_compile (acfg->cfgs [i]);
g_free (acfg->cfgs);
g_free (acfg->static_linking_symbol);
g_free (acfg->got_symbol);
g_free (acfg->plt_symbol);
g_ptr_array_free (acfg->methods, TRUE);
g_ptr_array_free (acfg->image_table, TRUE);
g_ptr_array_free (acfg->globals, TRUE);
g_ptr_array_free (acfg->unwind_ops, TRUE);
g_hash_table_destroy (acfg->method_indexes);
g_hash_table_destroy (acfg->method_depth);
g_hash_table_destroy (acfg->plt_offset_to_entry);
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
g_free (acfg->patch_to_plt_entry);
g_hash_table_destroy (acfg->method_to_cfg);
g_hash_table_destroy (acfg->token_info_hash);
g_hash_table_destroy (acfg->method_to_pinvoke_import);
g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
g_hash_table_destroy (acfg->image_hash);
g_hash_table_destroy (acfg->unwind_info_offsets);
g_hash_table_destroy (acfg->method_label_hash);
g_hash_table_destroy (acfg->typespec_classes);
g_hash_table_destroy (acfg->export_names);
g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
g_hash_table_destroy (acfg->klass_blob_hash);
g_hash_table_destroy (acfg->method_blob_hash);
if (acfg->blob_hash)
g_hash_table_destroy (acfg->blob_hash);
got_info_free (&acfg->got_info);
got_info_free (&acfg->llvm_got_info);
arch_free_unwind_info_section_cache (acfg);
mono_mempool_destroy (acfg->mempool);
method_to_external_icall_symbol_name = NULL;
g_free (acfg);
}
#define WRAPPER(e,n) n,
static const char* const
wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
#include "mono/metadata/wrapper-types.h"
NULL
};
static G_GNUC_UNUSED const char*
get_wrapper_type_name (int type)
{
return wrapper_type_names [type];
}
//#define DUMP_PLT
//#define DUMP_GOT
static void aot_dump (MonoAotCompile *acfg)
{
FILE *dumpfile;
char * dumpname;
JsonWriter writer;
mono_json_writer_init (&writer);
mono_json_writer_object_begin(&writer);
// Methods
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "methods");
mono_json_writer_array_begin (&writer);
int i;
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
MonoClass *klass;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
mono_json_writer_indent (&writer);
mono_json_writer_object_begin(&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "name");
mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "signature");
mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "code_size");
mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
klass = method->klass;
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "class");
mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "namespace");
mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "wrapper_type");
mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_end (&writer);
mono_json_writer_printf (&writer, ",\n");
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
// PLT entries
#ifdef DUMP_PLT
mono_json_writer_indent_push (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "plt");
mono_json_writer_array_begin (&writer);
for (i = 0; i < acfg->plt_offset; ++i) {
MonoPltEntry *plt_entry = NULL;
MonoJumpInfo *ji;
if (i == 0)
/*
* The first plt entry is unused.
*/
continue;
plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
ji = plt_entry->ji;
mono_json_writer_indent (&writer);
mono_json_writer_printf (&writer, "{ ");
mono_json_writer_object_key(&writer, "symbol");
mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
#endif
// GOT entries
#ifdef DUMP_GOT
mono_json_writer_indent_push (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "got");
mono_json_writer_array_begin (&writer);
mono_json_writer_indent_push (&writer);
for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
mono_json_writer_indent (&writer);
mono_json_writer_printf (&writer, "{ ");
mono_json_writer_object_key(&writer, "patch_name");
mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
#endif
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_end (&writer);
dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
dumpfile = fopen (dumpname, "w+");
g_free (dumpname);
fprintf (dumpfile, "%s", writer.text->str);
fclose (dumpfile);
mono_json_writer_destroy (&writer);
}
static const MonoJitICallId preinited_jit_icalls [] = {
MONO_JIT_ICALL_mini_llvm_init_method,
MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
MONO_JIT_ICALL_mini_llvmonly_throw_corlib_exception,
MONO_JIT_ICALL_mono_threads_state_poll,
MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
MONO_JIT_ICALL_mono_fill_method_rgctx,
MONO_JIT_ICALL_mono_fill_class_rgctx
};
static void
add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
{
if (!acfg->aot_opts.llvm_only)
get_got_offset (acfg, FALSE, ji);
get_got_offset (acfg, TRUE, ji);
}
static void
add_preinit_got_slots (MonoAotCompile *acfg)
{
MonoJumpInfo *ji;
int i;
/*
* Allocate the first few GOT entries to information which is needed frequently, or it is needed
* during method initialization etc.
*/
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_IMAGE;
ji->data.image = acfg->image;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_AOT_MODULE;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
add_preinit_slot (acfg, ji);
if (!acfg->aot_opts.llvm_only) {
for (i = 0; i < TLS_KEY_NUM; i++) {
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
ji->data.jit_icall_id = mono_get_tls_key_to_jit_icall_id (i);
add_preinit_slot (acfg, ji);
}
}
/* Called by native-to-managed wrappers on possibly unattached threads */
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
ji->data.jit_icall_id = MONO_JIT_ICALL_mono_threads_attach_coop;
add_preinit_slot (acfg, ji);
for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
ji->data.jit_icall_id = preinited_jit_icalls [i];
add_preinit_slot (acfg, ji);
}
if (acfg->aot_opts.llvm_only)
acfg->nshared_got_entries = acfg->llvm_got_offset;
else
acfg->nshared_got_entries = acfg->got_offset;
g_assert (acfg->nshared_got_entries);
}
static void
mono_dedup_log_stats (MonoAotCompile *acfg)
{
GHashTableIter iter;
g_assert (acfg->dedup_stats);
if (!acfg->dedup_emit_mode)
return;
// If dedup_emit_mode, acfg is the dummy dedup module that consolidates
// deduped modules
g_hash_table_iter_init (&iter, acfg->method_to_cfg);
MonoCompile *dcfg = NULL;
MonoMethod *method = NULL;
size_t wrappers_size_saved = 0;
size_t inflated_size_saved = 0;
size_t copied_singles = 0;
int wrappers_saved = 0;
int instances_saved = 0;
int copied = 0;
while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
gchar *dedup_name = mono_aot_get_mangled_method_name (method);
guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
if (count == 0)
continue;
if (acfg->dedup_emit_mode) {
// Size *saved* is the size due to things not emitted.
if (count < 2) {
// Just moved, didn't save space / dedup
copied ++;
copied_singles += dcfg->code_len;
} else if (method->wrapper_type != MONO_WRAPPER_NONE) {
wrappers_saved ++;
wrappers_size_saved += dcfg->code_len * (count - 1);
} else {
instances_saved ++;
inflated_size_saved += dcfg->code_len * (count - 1);
}
}
if (acfg->aot_opts.dedup) {
if (method->wrapper_type != MONO_WRAPPER_NONE) {
wrappers_saved ++;
wrappers_size_saved += dcfg->code_len * count;
} else {
instances_saved ++;
inflated_size_saved += dcfg->code_len * count;
}
}
}
aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", wrappers_saved, wrappers_size_saved);
aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", instances_saved, inflated_size_saved);
if (acfg->dedup_emit_mode)
aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", copied, copied_singles);
g_hash_table_destroy (acfg->dedup_stats);
acfg->dedup_stats = NULL;
}
// Flush the cache to tell future calls what to skip
static void
mono_flush_method_cache (MonoAotCompile *acfg)
{
GHashTable *method_cache = acfg->dedup_cache;
char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
g_free (filename);
return;
}
acfg->dedup_cache = NULL;
FILE *cache = fopen (filename, "w");
if (!cache)
g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
GHashTableIter iter;
gchar *name = NULL;
g_hash_table_iter_init (&iter, method_cache);
gboolean cont = TRUE;
while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
int res = fprintf (cache, "%s\n", name);
cont = res >= 0;
}
// FIXME: don't assert if error when flushing
g_assert (cont);
fclose (cache);
g_free (filename);
// The keys are all in the imageset, nothing to free
// Values are just pointers to memory owned elsewhere, or sentinels
g_hash_table_destroy (method_cache);
}
// Read in what has been emitted by previous invocations,
// what can be skipped
static void
mono_read_method_cache (MonoAotCompile *acfg)
{
char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
// Only do once, when dedup_cache is null
if (acfg->dedup_cache)
goto early_exit;
if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
g_assert (acfg->dedup_stats);
// only in skip mode
if (!acfg->aot_opts.dedup)
goto early_exit;
g_assert (acfg->dedup_cache);
FILE *cache;
cache = fopen (filename, "r");
if (!cache)
goto early_exit;
// Since we do pointer comparisons, and it can't be allocated at
// the address 0x1 due to alignment, we use this as a sentinel
gpointer other_acfg_sentinel;
other_acfg_sentinel = GINT_TO_POINTER (0x1);
if (fseek (cache, 0L, SEEK_END))
goto cleanup;
size_t fileLength;
fileLength = ftell (cache);
g_assert (fileLength > 0);
if (fseek (cache, 0L, SEEK_SET))
goto cleanup;
// Avoid thousands of new malloc entries
// FIXME: allocate into imageset, so we don't need to free.
// put the other mangled names there too.
char *bulk;
bulk = g_malloc0 (fileLength * sizeof (char));
size_t offset;
offset = 0;
while (fgets (&bulk [offset], fileLength - offset, cache)) {
// strip newline
char *line = &bulk [offset];
size_t len = strlen (line);
if (len == 0)
break;
if (len >= 0 && line [len] == '\n')
line [len] = '\0';
offset += strlen (line) + 1;
g_assert (fileLength >= offset);
g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
}
cleanup:
fclose (cache);
early_exit:
g_free (filename);
return;
}
typedef struct {
GHashTable *cache;
GHashTable *stats;
gboolean emit_inflated_methods;
MonoAssembly *inflated_assembly;
} MonoAotState;
static MonoAotState *
alloc_aot_state (void)
{
MonoAotState *state = g_malloc (sizeof (MonoAotState));
// FIXME: Should this own the memory?
state->cache = g_hash_table_new (g_str_hash, g_str_equal);
state->stats = g_hash_table_new (g_str_hash, g_str_equal);
// Start in "collect mode"
state->emit_inflated_methods = FALSE;
state->inflated_assembly = NULL;
return state;
}
static void
free_aot_state (MonoAotState *astate)
{
g_hash_table_destroy (astate->cache);
g_free (astate);
}
static void
mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
{
GHashTableIter iter;
gchar *name = NULL;
MonoMethod *method = NULL;
acfg->dedup_emit_mode = TRUE;
g_hash_table_iter_init (&iter, astate->cache);
while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
add_method_full (acfg, method, TRUE, 0);
}
return;
}
static void
mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
{
if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
return;
if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
// Thread the state through when making the inflate pass
*astate = *global_aot_state;
}
if (!*astate) {
*astate = alloc_aot_state ();
*global_aot_state = *astate;
}
acfg->dedup_cache = (*astate)->cache;
acfg->dedup_stats = (*astate)->stats;
// fills out acfg->dedup_cache
if (acfg->aot_opts.dedup)
mono_read_method_cache (acfg);
if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
gchar *asm_file = NULL;
// Get the last part of the path, the filename
for (int i=0; asm_path [i] != NULL; i++)
asm_file = asm_path [i];
if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
// Save
*is_dedup_dummy = TRUE;
(*astate)->inflated_assembly = ass;
}
g_strfreev (asm_path);
} else if ((*astate)->inflated_assembly) {
*is_dedup_dummy = (ass == (*astate)->inflated_assembly);
}
}
int
mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
{
// create assembly, loop and add extra_methods
// in add_generic_instances , rip out what's in that for loop
// and apply that to this aot_state inside of mono_compile_assembly
MonoAotState *astate;
astate = *(MonoAotState **)aot_state;
g_assert (astate);
// FIXME: allow suffixes?
if (!astate->inflated_assembly) {
const char* inflate = strstr (aot_options, "dedup-inflate");
if (!inflate)
return 0;
else
g_error ("Error: mono was not given an assembly with the provided inflate name\n");
}
// Switch modes
astate->emit_inflated_methods = TRUE;
int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
*aot_state = NULL;
free_aot_state (astate);
return res;
}
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
static MonoMethodSignature * const * const interp_in_static_sigs [] = {
&mono_icall_sig_bool_ptr_int32_ptrref,
&mono_icall_sig_bool_ptr_ptrref,
&mono_icall_sig_int32_int32_ptrref,
&mono_icall_sig_int32_int32_ptr_ptrref,
&mono_icall_sig_int32_ptr_int32_ptr,
&mono_icall_sig_int32_ptr_int32_ptrref,
&mono_icall_sig_int32_ptr_ptrref,
&mono_icall_sig_object_object_ptr_ptr_ptr,
&mono_icall_sig_object,
&mono_icall_sig_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_uint32_ptrref,
&mono_icall_sig_ptr_uint32_ptrref,
&mono_icall_sig_void_object_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
&mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
&mono_icall_sig_void_ptr_ptr_ptrref,
&mono_icall_sig_void_ptr_ptrref,
&mono_icall_sig_void_ptr,
&mono_icall_sig_void_int32_ptrref,
&mono_icall_sig_void_uint32_ptrref,
&mono_icall_sig_void,
};
#else
// Common signatures for which we use interp in wrappers even in fullaot + trampolines mode
// for increased performance
static MonoMethodSignature *const * const interp_in_static_common_sigs [] = {
&mono_icall_sig_void,
&mono_icall_sig_ptr,
&mono_icall_sig_void_ptr,
&mono_icall_sig_ptr_ptr,
&mono_icall_sig_void_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr_ptr,
};
#endif
static void
add_interp_in_wrapper_for_sig (MonoAotCompile *acfg, MonoMethodSignature *sig)
{
MonoMethod *wrapper;
sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
sig->pinvoke = FALSE;
wrapper = mini_get_interp_in_wrapper (sig);
add_method (acfg, wrapper);
}
int
mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
{
MonoImage *image = ass->image;
int res;
MonoAotCompile *acfg;
char *p;
TV_DECLARE (atv);
TV_DECLARE (btv);
acfg = acfg_create (ass, opts);
memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
acfg->aot_opts.write_symbols = TRUE;
acfg->aot_opts.ntrampolines = 4096;
acfg->aot_opts.nrgctx_trampolines = 4096;
acfg->aot_opts.nimt_trampolines = 512;
acfg->aot_opts.nrgctx_fetch_trampolines = 128;
acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
acfg->aot_opts.nftnptr_arg_trampolines = 128;
#endif
acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
if (!acfg->aot_opts.llvm_path)
acfg->aot_opts.llvm_path = g_strdup ("");
acfg->aot_opts.temp_path = g_strdup ("");
#if defined(MONOTOUCH)&& !defined(TARGET_AMD64)
acfg->aot_opts.use_trampolines_page = TRUE;
#endif
acfg->aot_opts.clangxx = g_strdup ("clang++");
mono_aot_parse_options (aot_options, &acfg->aot_opts);
if (acfg->aot_opts.direct_extern_calls && !(acfg->aot_opts.llvm && acfg->aot_opts.static_link)) {
aot_printerrf (acfg, "The 'direct-extern-calls' option requires the 'llvm' and 'static' options.\n");
return 1;
}
// start dedup
MonoAotState *astate = NULL;
gboolean is_dedup_dummy = FALSE;
mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
// Process later
if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
return 0;
if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
acfg->dedup_collect_only = TRUE;
// end dedup
if (acfg->aot_opts.logfile) {
acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
}
if (acfg->aot_opts.data_outfile) {
acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
if (!acfg->data_outfile) {
aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
return 1;
}
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
}
//acfg->aot_opts.print_skipped_methods = TRUE;
#if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
if (acfg->jit_opts & MONO_OPT_GSHAREDVT) {
aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
return 1;
}
if (acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
return 1;
}
#else
if (acfg->aot_opts.llvm_only) {
if (!mono_aot_mode_is_interp (&acfg->aot_opts))
acfg->jit_opts |= MONO_OPT_GSHAREDVT;
} else if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
acfg->jit_opts |= MONO_OPT_GSHAREDVT;
#endif
#if !defined(ENABLE_LLVM)
if (acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
return 1;
}
if (mono_use_llvm || acfg->aot_opts.llvm) {
aot_printerrf (acfg, "--aot=llvm requires a runtime compiled with llvm support.\n");
return 1;
}
#endif
if (acfg->jit_opts & MONO_OPT_GSHAREDVT)
mono_set_generic_sharing_vt_supported (TRUE);
if (!acfg->dedup_collect_only)
aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
if (!acfg->aot_opts.deterministic)
generate_aotid ((guint8*) &acfg->image->aotid);
char *aotid = mono_guid_to_string (acfg->image->aotid);
if (!acfg->dedup_collect_only && !acfg->aot_opts.deterministic)
aot_printf (acfg, "AOTID %s\n", aotid);
g_free (aotid);
#ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
if (mono_aot_mode_is_full (&acfg->aot_opts)) {
aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
return 1;
}
#endif
if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
return 1;
}
if (acfg->aot_opts.static_link)
acfg->aot_opts.asm_writer = TRUE;
if (acfg->aot_opts.soft_debug) {
mini_debug_options.mdb_optimizations = TRUE;
mini_debug_options.gen_sdb_seq_points = TRUE;
if (!mono_debug_enabled ()) {
aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
return 1;
}
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
}
if (acfg->aot_opts.try_llvm)
acfg->aot_opts.llvm = mini_llvm_init ();
if (mono_use_llvm || acfg->aot_opts.llvm) {
acfg->llvm = TRUE;
acfg->aot_opts.asm_writer = TRUE;
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
if (acfg->aot_opts.soft_debug) {
aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
return 1;
}
mini_llvm_init ();
if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
return 1;
}
}
if (mono_aot_mode_is_full (&acfg->aot_opts)) {
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
acfg->is_full_aot = TRUE;
}
if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
acfg->is_full_aot = TRUE;
}
if (mini_safepoints_enabled ())
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
// The methods in dedup-emit amodules must be available on runtime startup
// Note: Only one such amodule can have this attribute
if (astate && astate->emit_inflated_methods)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
if (acfg->aot_opts.instances_logfile_path) {
acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
if (!acfg->instances_logfile) {
aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
return 1;
}
}
if (acfg->aot_opts.profile_files) {
GList *l;
for (l = acfg->aot_opts.profile_files; l; l = l->next) {
load_profile_file (acfg, (char*)l->data);
}
}
if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (int method_index = 0; method_index < rows; ++method_index)
g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
}
if (mono_aot_mode_is_interp (&acfg->aot_opts) || mono_aot_mode_is_full (&acfg->aot_opts)) {
/* In interp mode, we don't need some trampolines, but this avoids having to add more conditionals at runtime */
acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.ntrampolines;
#ifdef MONO_ARCH_GSHARED_SUPPORTED
acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.nrgctx_trampolines;
#endif
acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = acfg->aot_opts.nimt_trampolines;
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
if (acfg->jit_opts & MONO_OPT_GSHAREDVT)
acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.ngsharedvt_arg_trampolines;
#endif
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = acfg->aot_opts.nftnptr_arg_trampolines;
#endif
acfg->num_trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = mono_aot_mode_is_interp (&acfg->aot_opts) && mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nunbox_arbitrary_trampolines : 0;
}
acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
arch_init (acfg);
if (mono_use_llvm || acfg->aot_opts.llvm) {
/*
* Emit all LLVM code into a separate assembly/object file and link with it
* normally.
*/
if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
acfg->llvm_owriter = TRUE;
} else if (acfg->aot_opts.llvm_outfile) {
int len = strlen (acfg->aot_opts.llvm_outfile);
if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
acfg->llvm_owriter = TRUE;
}
}
if (acfg->llvm && acfg->thumb_mixed)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
if (acfg->aot_opts.llvm_only)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
acfg->assembly_name_sym = g_strdup (get_assembly_prefix (acfg->image));
/* Get rid of characters which cannot occur in symbols */
for (p = acfg->assembly_name_sym; *p; ++p) {
if (!(isalnum (*p) || *p == '_'))
*p = '_';
}
acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
if (acfg->llvm) {
acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
}
acfg->method_index = 1;
if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
mono_set_partial_sharing_supported (TRUE);
if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
res = collect_methods (acfg);
if (!res)
return 1;
}
// If we're emitting all of the inflated methods into a dummy
// Assembly, then after extra_methods is set up, we're done
// in this function.
if (astate && astate->emit_inflated_methods)
mono_add_deferred_extra_methods (acfg, astate);
{
GList *l;
for (l = acfg->profile_data; l; l = l->next)
resolve_profile_data (acfg, (ProfileData*)l->data, ass);
for (l = acfg->profile_data; l; l = l->next)
add_profile_instances (acfg, (ProfileData*)l->data);
}
/* PLT offset 0 is reserved for the PLT trampoline */
acfg->plt_offset = 1;
add_preinit_got_slots (acfg);
current_acfg = acfg;
#ifdef ENABLE_LLVM
if (acfg->llvm) {
llvm_acfg = acfg;
LLVMModuleFlags flags = (LLVMModuleFlags)0;
#ifdef EMIT_DWARF_INFO
flags = LLVM_MODULE_FLAG_DWARF;
#endif
#ifdef EMIT_WIN32_CODEVIEW_INFO
flags = LLVM_MODULE_FLAG_CODEVIEW;
#endif
if (acfg->aot_opts.static_link)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
if (acfg->aot_opts.llvm_only)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
if (acfg->aot_opts.interp)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
add_lazy_init_wrappers (acfg);
add_method (acfg, mono_marshal_get_llvm_func_wrapper (LLVM_FUNC_WRAPPER_GC_POLL));
}
#endif
if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
add_method (acfg, wrapper);
wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
add_method (acfg, wrapper);
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++)
add_interp_in_wrapper_for_sig (acfg, *interp_in_static_sigs [i]);
#else
for (int i = 0; i < G_N_ELEMENTS (interp_in_static_common_sigs); i++)
add_interp_in_wrapper_for_sig (acfg, *interp_in_static_common_sigs [i]);
#endif
/* required for mixed mode */
if (strcmp (acfg->image->assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME) == 0) {
add_gc_wrappers (acfg);
for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
}
}
TV_GETTIME (atv);
compile_methods (acfg);
TV_GETTIME (btv);
acfg->stats.jit_time = TV_ELAPSED (atv, btv);
dedup_skip_methods (acfg);
if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
/* We only collected methods from this assembly */
return 0;
current_acfg = NULL;
return emit_aot_image (acfg);
}
static void
print_stats (MonoAotCompile *acfg)
{
int i;
gint64 all_sizes;
char llvm_stats_msg [256];
if (acfg->llvm && !acfg->aot_opts.llvm_only)
sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
else
strcpy (llvm_stats_msg, "");
all_sizes = acfg->stats.code_size + acfg->stats.method_info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d, BLOB: %d\n",
(int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
(int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
(int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
(int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
(int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
(int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
(int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
(int)(acfg->got_offset * sizeof (target_mgreg_t)),
(int)acfg->stats.blob_size);
aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
llvm_stats_msg,
acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
if (acfg->stats.genericcount)
aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.abscount)
aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.lmfcount)
aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.ocount)
aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
aot_printf (acfg, "GOT slot distribution:\n");
int nslots = 0;
int size = 0;
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
nslots += acfg->stats.got_slot_types [i];
size += acfg->stats.got_slot_info_sizes [i];
if (acfg->stats.got_slot_types [i])
aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
}
aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
aot_printf (acfg, "\nEncoding stats:\n");
aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
aot_printf (acfg, "\nMethod stats:\n");
aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
mono_dedup_log_stats (acfg);
}
static void
create_depfile (MonoAotCompile *acfg)
{
FILE *depfile;
// FIXME: Support other configurations
g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
depfile = fopen (acfg->aot_opts.depfile, "w");
g_assert (depfile);
int ntargets = 1;
char **targets = g_new0 (char*, ntargets);
targets [0] = acfg->aot_opts.llvm_outfile;
for (int tindex = 0; tindex < ntargets; ++tindex) {
fprintf (depfile, "%s: ", targets [tindex]);
for (int i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
fprintf (depfile, " %s", image->filename);
}
fprintf (depfile, "\n");
}
g_free (targets);
fclose (depfile);
}
static int
emit_aot_image (MonoAotCompile *acfg)
{
int i, res;
TV_DECLARE (atv);
TV_DECLARE (btv);
TV_GETTIME (atv);
#ifdef ENABLE_LLVM
if (acfg->llvm) {
if (acfg->aot_opts.asm_only) {
if (acfg->aot_opts.outfile) {
acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
acfg->tmpbasename = g_strdup (acfg->tmpfname);
} else {
acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
}
g_assert (acfg->aot_opts.llvm_outfile);
acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
if (acfg->llvm_owriter)
acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
else
acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
} else {
gchar *temp_path;
if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
temp_path = g_strdup (acfg->aot_opts.temp_path);
} else {
temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
acfg->temp_dir_to_delete = g_strdup (temp_path);
}
acfg->tmpbasename = g_build_filename (temp_path, "temp", (const char*)NULL);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
g_free (temp_path);
}
}
#endif
if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
if (acfg->aot_opts.outfile)
acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
acfg->fp = fopen (acfg->tmpfname, "w+");
} else {
if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
acfg->fp = fdopen (i, "w+");
} else {
acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", (const char*)NULL);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
acfg->fp = fopen (acfg->tmpfname, "w+");
}
}
if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
return 1;
}
if (acfg->fp)
acfg->w = mono_img_writer_create (acfg->fp);
/* Compute symbols for methods */
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i]) {
MonoCompile *cfg = acfg->cfgs [i];
int method_index = get_method_index (acfg, cfg->orig_method);
if (cfg->asm_symbol) {
// Set by method emitter in backend
if (acfg->llvm_label_prefix) {
char *old_symbol = cfg->asm_symbol;
cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
g_free (old_symbol);
}
} else if (COMPILE_LLVM (cfg)) {
cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
} else if (acfg->global_symbols || acfg->llvm) {
cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
} else {
cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
}
cfg->asm_debug_symbol = cfg->asm_symbol;
}
}
if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
/*
* CLANG supports GAS .file/.loc directives, so emit line number information this way
*/
acfg->gas_line_numbers = TRUE;
}
#ifdef EMIT_DWARF_INFO
if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
return 1;
}
acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
}
#endif /* EMIT_DWARF_INFO */
if (acfg->w)
mono_img_writer_emit_start (acfg->w);
if (acfg->dwarf)
mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
if (acfg->aot_opts.dedup)
mono_flush_method_cache (acfg);
emit_code (acfg);
emit_method_info_table (acfg);
emit_extra_methods (acfg);
emit_trampolines (acfg);
emit_class_name_table (acfg);
emit_got_info (acfg, FALSE);
if (acfg->llvm)
emit_got_info (acfg, TRUE);
emit_exception_info (acfg);
emit_unwind_info (acfg);
emit_class_info (acfg);
emit_plt (acfg);
emit_image_table (acfg);
emit_weak_field_indexes (acfg);
emit_got (acfg);
{
/*
* The managed allocators are GC specific, so can't use an AOT image created by one GC
* in another.
*/
const char *gc_name = mono_gc_get_gc_name ();
acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
}
emit_blob (acfg);
emit_objc_selectors (acfg);
emit_globals (acfg);
emit_file_info (acfg);
if (acfg->dwarf) {
emit_dwarf_info (acfg);
mono_dwarf_writer_close (acfg->dwarf);
} else {
if (!acfg->aot_opts.nodebug)
emit_codeview_info (acfg);
}
emit_mem_end (acfg);
if (acfg->need_pt_gnu_stack) {
/* This is required so the .so doesn't have an executable stack */
/* The bin writer already emits this */
fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
}
if (acfg->aot_opts.data_outfile)
fclose (acfg->data_outfile);
#ifdef ENABLE_LLVM
if (acfg->llvm) {
gboolean res;
res = emit_llvm_file (acfg);
if (!res)
return 1;
}
#endif
emit_library_info (acfg);
TV_GETTIME (btv);
acfg->stats.gen_time = TV_ELAPSED (atv, btv);
if (!acfg->aot_opts.stats)
aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
TV_GETTIME (atv);
if (acfg->w) {
res = mono_img_writer_emit_writeout (acfg->w);
if (res != 0) {
acfg_free (acfg);
return res;
}
res = compile_asm (acfg);
if (res != 0) {
acfg_free (acfg);
return res;
}
}
TV_GETTIME (btv);
acfg->stats.link_time = TV_ELAPSED (atv, btv);
if (acfg->aot_opts.stats)
print_stats (acfg);
aot_printf (acfg, "JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
if (acfg->aot_opts.depfile)
create_depfile (acfg);
if (acfg->aot_opts.dump_json)
aot_dump (acfg);
if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
execute_system (command);
g_free (command);
}
acfg_free (acfg);
return 0;
}
#else
/* AOT disabled */
void*
mono_aot_readonly_field_override (MonoClassField *field)
{
return NULL;
}
int
mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
{
return 0;
}
gboolean
mono_aot_is_shared_got_offset (int offset)
{
return FALSE;
}
gboolean
mono_aot_is_externally_callable (MonoMethod *cmethod)
{
return FALSE;
}
int
mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_can_enter_interp (MonoMethod *method)
{
return FALSE;
}
int
mono_aot_get_method_index (MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
#endif
| /**
* \file
* mono Ahead of Time compiler
*
* Author:
* Dietmar Maurer ([email protected])
* Zoltan Varga ([email protected])
* Johan Lorensson ([email protected])
*
* (C) 2002 Ximian, Inc.
* Copyright 2003-2011 Novell, Inc
* 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 <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#ifndef HOST_WIN32
#include <sys/time.h>
#else
#include <winsock2.h>
#include <windows.h>
#endif
#include <errno.h>
#include <sys/stat.h>
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/custom-attrs-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-rand.h>
#include <mono/utils/json.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/profiler/aot.h>
#include <mono/utils/w32api.h>
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "seq-points.h"
#include "image-writer.h"
#include "dwarfwriter.h"
#include "mini-gc.h"
#include "mini-llvm.h"
#include "mini-runtime.h"
#include "interp/interp.h"
static MonoMethod*
try_get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
{
MonoMethod *result;
ERROR_DECL (error);
result = mono_class_get_method_from_name_checked (klass, method_name, param_count, flags, error);
mono_error_assert_ok (error);
return result;
}
// FIXME Consolidate the multiple functions named get_method_nofail.
static MonoMethod*
get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
{
MonoMethod *result = try_get_method_nofail (klass, method_name, param_count, flags);
g_assertf (result, "Expected to find method %s in klass %s", method_name, m_class_get_name (klass));
return result;
}
#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
// Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
// targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
#if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
#define TARGET_X86_64_WIN32_MSVC
#endif
#if defined(TARGET_X86_64_WIN32_MSVC)
#define TARGET_WIN32_MSVC
#endif
// Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
// works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
// compiling for AMD64 (Windows x64 platforms).
#if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
#define EMIT_WIN32_UNWIND_INFO
#endif
#if defined(TARGET_ANDROID) || defined(__linux__)
#define RODATA_REL_SECT ".data.rel.ro"
#else
#define RODATA_REL_SECT ".text"
#endif
#if defined(__linux__)
#define RODATA_SECT ".rodata"
#elif defined(TARGET_MACH)
#define RODATA_SECT ".section __TEXT, __const"
#elif defined(TARGET_WIN32_MSVC)
#define RODATA_SECT ".rdata"
#else
#define RODATA_SECT ".text"
#endif
#define TV_DECLARE(name) gint64 name
#define TV_GETTIME(tv) tv = mono_100ns_ticks ()
#define TV_ELAPSED(start,end) (((end) - (start)) / 10)
#define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
typedef struct {
char *name;
MonoImage *image;
} ImageProfileData;
typedef struct ClassProfileData ClassProfileData;
typedef struct {
int argc;
ClassProfileData **argv;
MonoGenericInst *inst;
} GInstProfileData;
struct ClassProfileData {
ImageProfileData *image;
char *ns, *name;
GInstProfileData *inst;
MonoClass *klass;
};
typedef struct {
ClassProfileData *klass;
int id;
char *name;
int param_count;
char *signature;
GInstProfileData *inst;
MonoMethod *method;
} MethodProfileData;
typedef struct {
GHashTable *images, *classes, *ginsts, *methods;
} ProfileData;
/* predefined values for static readonly fields without needed to run the .cctor */
typedef struct _ReadOnlyValue ReadOnlyValue;
struct _ReadOnlyValue {
ReadOnlyValue *next;
char *name;
int type; /* to be used later for typechecking to prevent user errors */
union {
guint8 i1;
guint16 i2;
guint32 i4;
guint64 i8;
gpointer ptr;
} value;
};
static ReadOnlyValue *readonly_values;
typedef struct MonoAotOptions {
char *outfile;
char *llvm_outfile;
char *data_outfile;
GList *profile_files;
gboolean save_temps;
gboolean write_symbols;
gboolean metadata_only;
gboolean bind_to_runtime_version;
MonoAotMode mode;
gboolean interp;
gboolean no_dlsym;
gboolean static_link;
gboolean asm_only;
gboolean asm_writer;
gboolean nodebug;
gboolean dwarf_debug;
gboolean soft_debug;
gboolean log_generics;
gboolean log_instances;
gboolean gen_msym_dir;
char *gen_msym_dir_path;
gboolean direct_pinvoke;
gboolean direct_icalls;
gboolean direct_extern_calls;
gboolean no_direct_calls;
gboolean use_trampolines_page;
gboolean no_instances;
// We are collecting inflated methods and emitting non-inflated
gboolean dedup;
// The name of the assembly for which the AOT module is going to have all deduped methods moved to.
// When set, we are emitting inflated methods only
char *dedup_include;
gboolean gnu_asm;
gboolean try_llvm;
gboolean llvm;
gboolean llvm_only;
int nthreads;
int ntrampolines;
int nrgctx_trampolines;
int nimt_trampolines;
int ngsharedvt_arg_trampolines;
int nftnptr_arg_trampolines;
int nrgctx_fetch_trampolines;
int nunbox_arbitrary_trampolines;
gboolean print_skipped_methods;
gboolean stats;
gboolean verbose;
gboolean deterministic;
gboolean allow_errors;
char *tool_prefix;
char *ld_flags;
char *ld_name;
char *mtriple;
char *llvm_path;
char *temp_path;
char *instances_logfile_path;
char *logfile;
char *llvm_opts;
char *llvm_llc;
char *llvm_cpu_attr;
gboolean use_current_cpu;
gboolean dump_json;
gboolean profile_only;
gboolean no_opt;
char *clangxx;
char *depfile;
} MonoAotOptions;
typedef enum {
METHOD_CAT_NORMAL,
METHOD_CAT_GSHAREDVT,
METHOD_CAT_INST,
METHOD_CAT_WRAPPER,
METHOD_CAT_NUM
} MethodCategory;
typedef struct MonoAotStats {
int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
gint64 code_size, method_info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size, blob_size;
int methods_without_got_slots, direct_calls, all_calls, llvm_count;
int got_slots, offsets_size;
int method_categories [METHOD_CAT_NUM];
int got_slot_types [MONO_PATCH_INFO_NUM];
int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
int jit_time, gen_time, link_time;
int method_ref_count, method_ref_size;
int class_ref_count, class_ref_size;
int ginst_count, ginst_size;
} MonoAotStats;
typedef struct GotInfo {
GHashTable *patch_to_got_offset;
GHashTable **patch_to_got_offset_by_type;
GPtrArray *got_patches;
} GotInfo;
#ifdef EMIT_WIN32_UNWIND_INFO
typedef struct _UnwindInfoSectionCacheItem {
char *xdata_section_label;
PUNWIND_INFO unwind_info;
gboolean xdata_section_emitted;
} UnwindInfoSectionCacheItem;
#endif
typedef struct MonoAotCompile {
MonoImage *image;
GPtrArray *methods;
GHashTable *method_indexes;
GHashTable *method_depth;
MonoCompile **cfgs;
int cfgs_size;
GHashTable **patch_to_plt_entry;
GHashTable *plt_offset_to_entry;
//GHashTable *patch_to_got_offset;
//GHashTable **patch_to_got_offset_by_type;
//GPtrArray *got_patches;
GotInfo got_info, llvm_got_info;
GHashTable *image_hash;
GHashTable *method_to_cfg;
GHashTable *token_info_hash;
GHashTable *method_to_pinvoke_import;
GHashTable *method_to_external_icall_symbol_name;
GPtrArray *extra_methods;
GPtrArray *image_table;
GPtrArray *globals;
GPtrArray *method_order;
GHashTable *dedup_stats;
GHashTable *dedup_cache;
gboolean dedup_cache_changed;
GHashTable *export_names;
/* Maps MonoClass* -> blob offset */
GHashTable *klass_blob_hash;
/* Maps MonoMethod* -> blob offset */
GHashTable *method_blob_hash;
/* Maps MonoGenericInst* -> blob offset */
GHashTable *ginst_blob_hash;
GHashTable *gsharedvt_in_signatures;
GHashTable *gsharedvt_out_signatures;
guint32 *plt_got_info_offsets;
guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, plt_got_info_offset_base, nshared_got_entries;
/* Number of GOT entries reserved for trampolines */
guint32 num_trampoline_got_entries;
guint32 tramp_page_size;
guint32 table_offsets [MONO_AOT_TABLE_NUM];
guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
MonoAotOptions aot_opts;
guint32 nmethods;
int call_table_entry_size;
guint32 nextra_methods;
guint32 jit_opts;
guint32 simd_opts;
MonoMemPool *mempool;
MonoAotStats stats;
int method_index;
char *static_linking_symbol;
mono_mutex_t mutex;
gboolean gas_line_numbers;
/* Whenever to emit an object file directly from llc */
gboolean llvm_owriter;
gboolean llvm_owriter_supported;
MonoImageWriter *w;
MonoDwarfWriter *dwarf;
FILE *fp;
char *tmpbasename;
char *tmpfname;
char *temp_dir_to_delete;
char *llvm_sfile;
char *llvm_ofile;
GSList *cie_program;
GHashTable *unwind_info_offsets;
GPtrArray *unwind_ops;
guint32 unwind_info_offset;
char *global_prefix;
char *got_symbol;
char *llvm_got_symbol;
char *plt_symbol;
char *llvm_eh_frame_symbol;
GHashTable *method_label_hash;
const char *temp_prefix;
const char *user_symbol_prefix;
const char *llvm_label_prefix;
const char *inst_directive;
int align_pad_value;
guint32 label_generator;
gboolean llvm;
gboolean has_jitted_code;
gboolean is_full_aot;
gboolean dedup_collect_only;
MonoAotFileFlags flags;
MonoDynamicStream blob;
gboolean blob_closed;
GHashTable *typespec_classes;
GString *llc_args;
GString *as_args;
char *assembly_name_sym;
GHashTable *plt_entry_debug_sym_cache;
gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
GHashTable *ginst_hash;
GHashTable *dwarf_ln_filenames;
gboolean global_symbols;
int objc_selector_index, objc_selector_index_2;
GPtrArray *objc_selectors;
GHashTable *objc_selector_to_index;
GList *profile_data;
GHashTable *profile_methods;
GHashTable *blob_hash;
#ifdef EMIT_WIN32_UNWIND_INFO
GList *unwind_info_section_cache;
#endif
FILE *logfile;
FILE *instances_logfile;
FILE *data_outfile;
int datafile_offset;
int gc_name_offset;
// In this mode, we are emitting dedupable methods that we encounter
gboolean dedup_emit_mode;
} MonoAotCompile;
typedef struct {
int plt_offset;
char *symbol, *llvm_symbol, *debug_sym;
MonoJumpInfo *ji;
gboolean jit_used, llvm_used;
} MonoPltEntry;
#define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
#define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
/* This points to the current acfg in LLVM mode */
static MonoAotCompile *llvm_acfg;
static MonoAotCompile *current_acfg;
/* Cache of decoded method external icall symbol names. */
/* Owned by acfg, but kept in this static as well since it is */
/* accessed by code paths not having access to acfg. */
static GHashTable *method_to_external_icall_symbol_name;
// 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 PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
#include "patch-info.h"
#undef PATCH_INFO
} opstr = {
#define PATCH_INFO(a,b) b,
#include "patch-info.h"
#undef PATCH_INFO
};
static const gint16 opidx [] = {
#define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
#include "patch-info.h"
#undef PATCH_INFO
};
static G_GNUC_UNUSED const char*
get_patch_name (int info)
{
return (const char*)&opstr + opidx [info];
}
static int
emit_aot_image (MonoAotCompile *acfg);
static void
mono_flush_method_cache (MonoAotCompile *acfg);
static void
mono_read_method_cache (MonoAotCompile *acfg);
static guint32
get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
static char*
get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
static void
add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
static void
add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
static void
encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf);
static gboolean
ignore_cfg (MonoCompile *cfg)
{
return !cfg || cfg->skip;
}
static void
aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
{
FILE *output;
va_list args;
if (acfg->logfile)
output = acfg->logfile;
else
output = stdout;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
}
static void
aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
{
FILE *output;
va_list args;
if (acfg->logfile)
output = acfg->logfile;
else
output = stderr;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
}
static void
report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
{
FILE *output;
va_list args;
if (is_ok (error))
return;
if (acfg->logfile)
output = acfg->logfile;
else
output = stderr;
va_start (args, format);
vfprintf (output, format, args);
va_end (args);
mono_error_cleanup (error);
if (acfg->is_full_aot && !acfg->aot_opts.allow_errors && fatal) {
fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
exit (1);
}
}
/* Wrappers around the image writer functions */
#define MAX_SYMBOL_SIZE 256
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static const char *
mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
{
gsize needed_size = length;
g_assert (NULL != symbol);
g_assert (NULL != mangled_symbol);
g_assert (0 != length);
if (symbol && '_' != symbol [0]) {
needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
} else {
needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
}
g_assert (0 <= needed_size && needed_size < length);
return mangled_symbol;
}
static char *
mangle_symbol_alloc (const char * symbol)
{
g_assert (NULL != symbol);
if (symbol && '_' != symbol [0]) {
return g_strdup_printf ("_%s", symbol);
}
else {
return g_strdup_printf ("%s", symbol);
}
}
#endif
static void
emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
{
mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
}
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static void
emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
{
const char * mangled_symbol_name = name;
char * mangled_symbol_name_alloc = NULL;
if (TRUE == func) {
mangled_symbol_name_alloc = mangle_symbol_alloc (name);
mangled_symbol_name = mangled_symbol_name_alloc;
}
if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
}
mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
if (NULL != mangled_symbol_name_alloc) {
g_free (mangled_symbol_name_alloc);
}
}
#else
static void
emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
{
mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
}
#endif
static void
emit_label (MonoAotCompile *acfg, const char *name)
{
mono_img_writer_emit_label (acfg->w, name);
}
static void
emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
{
mono_img_writer_emit_bytes (acfg->w, buf, size);
}
static void
emit_string (MonoAotCompile *acfg, const char *value)
{
mono_img_writer_emit_string (acfg->w, value);
}
static void
emit_line (MonoAotCompile *acfg)
{
mono_img_writer_emit_line (acfg->w);
}
static void
emit_alignment (MonoAotCompile *acfg, int size)
{
mono_img_writer_emit_alignment (acfg->w, size);
}
static void
emit_alignment_code (MonoAotCompile *acfg, int size)
{
if (acfg->align_pad_value)
mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
else
mono_img_writer_emit_alignment (acfg->w, size);
}
static void
emit_padding (MonoAotCompile *acfg, int size)
{
int i;
guint8 buf [16];
if (acfg->align_pad_value) {
for (i = 0; i < 16; ++i)
buf [i] = acfg->align_pad_value;
} else {
memset (buf, 0, sizeof (buf));
}
for (i = 0; i < size; i += 16) {
if (size - i < 16)
emit_bytes (acfg, buf, size - i);
else
emit_bytes (acfg, buf, 16);
}
}
static void
emit_pointer (MonoAotCompile *acfg, const char *target)
{
mono_img_writer_emit_pointer (acfg->w, target);
}
static void
emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
{
if (prefix [0] != '\0') {
char *s = g_strdup_printf ("%s%s", prefix, target);
mono_img_writer_emit_pointer (acfg->w, s);
g_free (s);
} else {
mono_img_writer_emit_pointer (acfg->w, target);
}
}
static void
emit_int16 (MonoAotCompile *acfg, int value)
{
mono_img_writer_emit_int16 (acfg->w, value);
}
static void
emit_int32 (MonoAotCompile *acfg, int value)
{
mono_img_writer_emit_int32 (acfg->w, value);
}
static void
emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
{
mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
}
static void
emit_zero_bytes (MonoAotCompile *acfg, int num)
{
mono_img_writer_emit_zero_bytes (acfg->w, num);
}
static void
emit_byte (MonoAotCompile *acfg, guint8 val)
{
mono_img_writer_emit_byte (acfg->w, val);
}
#if defined(TARGET_WIN32) && defined(TARGET_X86)
static G_GNUC_UNUSED void
emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
{
const char * mangled_symbol_name = name;
char * mangled_symbol_name_alloc = NULL;
mangled_symbol_name_alloc = mangle_symbol_alloc (name);
mangled_symbol_name = mangled_symbol_name_alloc;
if (0 != g_strcasecmp (name, mangled_symbol_name)) {
mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
}
mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
if (NULL != mangled_symbol_name_alloc) {
g_free (mangled_symbol_name_alloc);
}
}
#else
static G_GNUC_UNUSED void
emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
{
mono_img_writer_emit_global (acfg->w, name, func);
}
#endif
#ifdef TARGET_WIN32_MSVC
static gboolean
link_shared_library (MonoAotCompile *acfg)
{
return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
}
#endif
static gboolean
add_to_global_symbol_table (MonoAotCompile *acfg)
{
#ifdef TARGET_WIN32_MSVC
return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
#else
return acfg->aot_opts.no_dlsym;
#endif
}
static void
emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
{
if (add_to_global_symbol_table (acfg))
g_ptr_array_add (acfg->globals, g_strdup (name));
if (acfg->aot_opts.no_dlsym) {
mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
} else {
emit_global_inner (acfg, name, func);
}
}
static void
emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
{
mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
}
/* Emit a symbol which is referenced by the MonoAotFileInfo structure */
static void
emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
{
char symbol [MAX_SYMBOL_SIZE];
if (acfg->llvm) {
emit_label (acfg, name);
/* LLVM generated code references this */
int n = snprintf (symbol, MAX_SYMBOL_SIZE, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
if (n >= MAX_SYMBOL_SIZE)
symbol[MAX_SYMBOL_SIZE - 1] = 0;
emit_label (acfg, symbol);
#ifndef TARGET_WIN32_MSVC
emit_global_inner (acfg, symbol, FALSE);
#else
emit_global_inner (acfg, symbol, func);
#endif
} else {
emit_label (acfg, name);
}
}
static void
emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
{
if (acfg->llvm) {
mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
return;
}
mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
#ifdef TARGET_MACH
/* On apple, all symbols need to be aligned to avoid warnings from ld */
emit_alignment (acfg, 4);
#endif
mono_img_writer_emit_label (acfg->w, name);
mono_img_writer_emit_string (acfg->w, value);
}
static G_GNUC_UNUSED void
emit_uleb128 (MonoAotCompile *acfg, guint32 value)
{
do {
guint8 b = value & 0x7f;
value >>= 7;
if (value != 0) /* more bytes to come */
b |= 0x80;
emit_byte (acfg, b);
} while (value);
}
static G_GNUC_UNUSED void
emit_sleb128 (MonoAotCompile *acfg, gint64 value)
{
gboolean more = 1;
gboolean negative = (value < 0);
guint32 size = 64;
guint8 byte;
while (more) {
byte = value & 0x7f;
value >>= 7;
/* the following is unnecessary if the
* implementation of >>= uses an arithmetic rather
* than logical shift for a signed left operand
*/
if (negative)
/* sign extend */
value |= - ((gint64)1 <<(size - 7));
/* sign bit of byte is second high order bit (0x40) */
if ((value == 0 && !(byte & 0x40)) ||
(value == -1 && (byte & 0x40)))
more = 0;
else
byte |= 0x80;
emit_byte (acfg, byte);
}
}
static G_GNUC_UNUSED void
encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
do {
guint8 b = value & 0x7f;
value >>= 7;
if (value != 0) /* more bytes to come */
b |= 0x80;
*p ++ = b;
} while (value);
*endbuf = p;
}
static G_GNUC_UNUSED void
encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
{
gboolean more = 1;
gboolean negative = (value < 0);
guint32 size = 32;
guint8 byte;
guint8 *p = buf;
while (more) {
byte = value & 0x7f;
value >>= 7;
/* the following is unnecessary if the
* implementation of >>= uses an arithmetic rather
* than logical shift for a signed left operand
*/
if (negative)
/* sign extend */
value |= - (1 <<(size - 7));
/* sign bit of byte is second high order bit (0x40) */
if ((value == 0 && !(byte & 0x40)) ||
(value == -1 && (byte & 0x40)))
more = 0;
else
byte |= 0x80;
*p ++= byte;
}
*endbuf = p;
}
static void
encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
{
// FIXME: Big-endian
buf [0] = (val >> 0) & 0xff;
buf [1] = (val >> 8) & 0xff;
buf [2] = (val >> 16) & 0xff;
buf [3] = (val >> 24) & 0xff;
*endbuf = buf + 4;
}
static void
encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
{
buf [0] = (val >> 0) & 0xff;
buf [1] = (val >> 8) & 0xff;
*endbuf = buf + 2;
}
static void
encode_string (const char *s, guint8 *buf, guint8 **endbuf)
{
int len = strlen (s);
memcpy (buf, s, len + 1);
*endbuf = buf + len + 1;
}
static void
emit_unset_mode (MonoAotCompile *acfg)
{
mono_img_writer_emit_unset_mode (acfg->w);
}
static G_GNUC_UNUSED void
emit_set_thumb_mode (MonoAotCompile *acfg)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, ".code 16\n");
}
static G_GNUC_UNUSED void
emit_set_arm_mode (MonoAotCompile *acfg)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, ".code 32\n");
}
static void
emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
{
#ifdef TARGET_ARM64
int i;
g_assert (size % 4 == 0);
emit_unset_mode (acfg);
for (i = 0; i < size; i += 4)
fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
#else
emit_bytes (acfg, buf, size);
#endif
}
/* ARCHITECTURE SPECIFIC CODE */
#if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
#define EMIT_DWARF_INFO 1
#endif
#ifdef TARGET_WIN32_MSVC
#undef EMIT_DWARF_INFO
#define EMIT_WIN32_CODEVIEW_INFO
#endif
#ifdef EMIT_WIN32_UNWIND_INFO
static UnwindInfoSectionCacheItem *
get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
static void
free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
static void
emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
static void
emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
#endif
static void
arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
{
#ifdef EMIT_WIN32_UNWIND_INFO
free_unwind_info_section_cache_win32 (acfg);
#endif
}
static void
arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
#ifdef EMIT_WIN32_UNWIND_INFO
gboolean own_unwind_ops = FALSE;
if (!unwind_ops) {
unwind_ops = mono_unwind_get_cie_program ();
own_unwind_ops = TRUE;
}
emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
if (own_unwind_ops)
mono_free_unwind_info (unwind_ops);
#endif
}
#if defined(TARGET_ARM)
#define AOT_FUNC_ALIGNMENT 4
#else
#define AOT_FUNC_ALIGNMENT 16
#endif
#if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
#define PPC_LD_OP "ld"
#define PPC_LDX_OP "ldx"
#else
#define PPC_LD_OP "lwz"
#define PPC_LDX_OP "lwzx"
#endif
#ifdef TARGET_X86_64_WIN32_MSVC
#define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
#elif TARGET_AMD64
#define AOT_TARGET_STR "AMD64"
#endif
#ifdef TARGET_ARM
#ifdef TARGET_MACH
#define AOT_TARGET_STR "ARM (MACH)"
#else
#define AOT_TARGET_STR "ARM (!MACH)"
#endif
#endif
#ifdef TARGET_ARM64
#ifdef TARGET_MACH
#define AOT_TARGET_STR "ARM64 (MACH)"
#else
#define AOT_TARGET_STR "ARM64 (!MACH)"
#endif
#endif
#ifdef TARGET_POWERPC64
#ifdef MONO_ARCH_ILP32
#define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
#else
#define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
#endif
#else
#ifdef TARGET_POWERPC
#ifdef MONO_ARCH_ILP32
#define AOT_TARGET_STR "POWERPC (mono ilp32)"
#else
#define AOT_TARGET_STR "POWERPC (!mono ilp32)"
#endif
#endif
#endif
#ifdef TARGET_RISCV32
#define AOT_TARGET_STR "RISCV32"
#endif
#ifdef TARGET_RISCV64
#define AOT_TARGET_STR "RISCV64"
#endif
#ifdef TARGET_X86
#ifdef TARGET_WIN32
#define AOT_TARGET_STR "X86 (WIN32)"
#else
#define AOT_TARGET_STR "X86"
#endif
#endif
#ifndef AOT_TARGET_STR
#define AOT_TARGET_STR ""
#endif
static void
arch_init (MonoAotCompile *acfg)
{
acfg->llc_args = g_string_new ("");
acfg->as_args = g_string_new ("");
acfg->llvm_owriter_supported = TRUE;
/*
* The prefix LLVM likes to put in front of symbol names on darwin.
* The mach-os specs require this for globals, but LLVM puts them in front of all
* symbols. We need to handle this, since we need to refer to LLVM generated
* symbols.
*/
acfg->llvm_label_prefix = "";
acfg->user_symbol_prefix = "";
#if TARGET_X86 || TARGET_AMD64
const gboolean has_custom_args = !!acfg->aot_opts.llvm_llc || acfg->aot_opts.use_current_cpu;
#endif
#if defined(TARGET_X86)
g_string_append_printf (acfg->llc_args, " -march=x86 %s", has_custom_args ? "" : "-mcpu=generic");
#endif
#if defined(TARGET_AMD64)
g_string_append_printf (acfg->llc_args, " -march=x86-64 %s", has_custom_args ? "" : "-mcpu=generic");
/* NOP */
acfg->align_pad_value = 0x90;
#ifdef MONO_ARCH_CODE_EXEC_ONLY
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY);
#endif
#endif
g_string_append (acfg->llc_args, " -enable-implicit-null-checks -disable-fault-maps");
if (mono_use_fast_math) {
// same parameters are passed to opt and LLVM JIT
g_string_append (acfg->llc_args, " -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math");
}
#ifdef TARGET_ARM
if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
g_string_append (acfg->llc_args, "-mattr=+v6");
} else {
if (!acfg->aot_opts.mtriple) {
g_string_append (acfg->llc_args, " -march=arm");
} else {
/* arch will be defined via mtriple, e.g. armv7s-ios or thumb. */
if (strstr (acfg->aot_opts.mtriple, "ios")) {
g_string_append (acfg->llc_args, " -mattr=+v7");
g_string_append (acfg->llc_args, " -exception-model=dwarf -frame-pointer=all");
}
}
#if defined(ARM_FPU_VFP_HARD)
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
g_string_append (acfg->as_args, " -mfpu=vfp3");
#elif defined(ARM_FPU_VFP)
#if defined(TARGET_ARM)
// +d16 triggers a warning on arm
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon");
#else
g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
#endif
g_string_append (acfg->as_args, " -mfpu=vfp3");
#else
g_string_append (acfg->llc_args, " -mattr=+soft-float");
#endif
}
if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
acfg->thumb_mixed = TRUE;
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#endif
#ifdef TARGET_ARM64
g_string_append (acfg->llc_args, " -march=aarch64");
acfg->inst_directive = ".inst";
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#endif
#ifdef TARGET_MACH
acfg->user_symbol_prefix = "_";
acfg->llvm_label_prefix = "_";
acfg->inst_directive = ".word";
acfg->need_no_dead_strip = TRUE;
acfg->aot_opts.gnu_asm = TRUE;
#endif
#if defined(__linux__) && !defined(TARGET_ARM)
acfg->need_pt_gnu_stack = TRUE;
#endif
#ifdef TARGET_RISCV
if (acfg->aot_opts.mtriple)
mono_arch_set_target (acfg->aot_opts.mtriple);
#ifdef TARGET_RISCV64
g_string_append (acfg->as_args, " -march=rv64i ");
#ifdef RISCV_FPABI_DOUBLE
g_string_append (acfg->as_args, " -mabi=lp64d");
#else
g_string_append (acfg->as_args, " -mabi=lp64");
#endif
#else
g_string_append (acfg->as_args, " -march=rv32i ");
#ifdef RISCV_FPABI_DOUBLE
g_string_append (acfg->as_args, " -mabi=ilp32d ");
#else
g_string_append (acfg->as_args, " -mabi=ilp32 ");
#endif
#endif
#endif
#ifdef MONOTOUCH
acfg->global_symbols = TRUE;
#endif
#ifdef TARGET_ANDROID
acfg->llvm_owriter_supported = FALSE;
#endif
}
#ifdef TARGET_ARM64
/* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
/* Must emit 12 bytes of instructions */
static void
arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
{
int offset;
g_assert (acfg->fp);
emit_unset_mode (acfg);
/* r16==ip0 */
offset = (int)(got_slot * TARGET_SIZEOF_VOID_P);
#ifdef TARGET_MACH
/* clang's integrated assembler */
fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
#ifdef MONO_ARCH_ILP32
fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF+%d\n", acfg->got_symbol, offset & 0xfff);
fprintf (acfg->fp, "ldr w%d, [x16, #%d]\n", dreg, 0);
#else
fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
#endif
#else
/* Linux GAS */
fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
#endif
}
static void
arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
{
int reg;
g_assert (acfg->fp);
emit_unset_mode (acfg);
/* ldr rt, target */
reg = arm_get_ldr_lit_reg (code);
fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
*code_size = 12;
}
static void
arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
g_assert (acfg->fp);
emit_unset_mode (acfg);
if (ji && ji->relocation == MONO_R_ARM64_B) {
fprintf (acfg->fp, "b %s\n", target);
} else {
if (ji)
g_assert (ji->relocation == MONO_R_ARM64_BL);
fprintf (acfg->fp, "bl %s\n", target);
}
*call_size = 4;
}
static void
arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
{
int reg;
/* ldr rt, target */
reg = arm_get_ldr_lit_reg (code);
arm64_emit_load_got_slot (acfg, reg, got_slot);
*code_size = 12;
}
static void
arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
{
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
/* Used by mono_aot_get_plt_info_offset () */
fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
}
static void
arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
{
guint8 buf [256];
guint8 *code;
int imm;
/* The common code */
code = buf;
imm = pagesize;
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Trampoline argument */
arm_ldrp (code, arg_reg, ARMREG_IP0, 0);
/* Address */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* Emit it */
emit_code_bytes (acfg, buf, code - buf);
*size = code - buf;
}
static void
arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
{
guint8 buf [256];
guint8 *code;
int i, count;
count = (pagesize - common_tramp_size) / specific_tramp_size;
for (i = 0; i < count; ++i) {
code = buf;
arm_adrx (code, ARMREG_IP0, code);
/* Branch to the generic code */
arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
#ifndef MONO_ARCH_ILP32
/* This has to be 2 pointers long */
arm_nop (code);
arm_nop (code);
#endif
g_assert (code - buf == specific_tramp_size);
emit_code_bytes (acfg, buf, code - buf);
}
}
static void
arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
{
guint8 buf [128];
guint8 *code;
guint8 *labels [16];
int common_tramp_size;
int specific_tramp_size = 2 * TARGET_SIZEOF_VOID_P;
int imm, pagesize;
char symbol [128];
if (!acfg->aot_opts.use_trampolines_page)
return;
#ifdef TARGET_MACH
/* Have to match the target pagesize */
pagesize = 16384;
#else
pagesize = mono_pagesize ();
#endif
acfg->tramp_page_size = pagesize;
/* The specific trampolines */
sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* The common code */
arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The rgctx trampolines */
/* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* The common code */
arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The gsharedvt arg trampolines */
/* These are the same as the specific trampolines */
sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* Unbox arbitrary trampolines */
sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm = pagesize;
/* Unbox this arg */
arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Address */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* Emit it */
emit_code_bytes (acfg, buf, code - buf);
common_tramp_size = code - buf;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
/* The IMT trampolines */
sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm = pagesize;
/* The trampoline address is in IP0 */
arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
/* Compute the data slot address */
arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
/* Trampoline argument */
arm_ldrp (code, ARMREG_IP1, ARMREG_IP0, 0);
/* Same as arch_emit_imt_trampoline () */
labels [0] = code;
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, 0);
arm_cmpp (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
labels [1] = code;
arm_bcc (code, ARMCOND_EQ, 0);
/* End-of-loop check */
labels [2] = code;
arm_cbzx (code, ARMREG_IP0, 0);
/* Loop footer */
arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * TARGET_SIZEOF_VOID_P);
arm_b (code, labels [0]);
/* Match */
mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
/* Load vtable slot addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
/* Load vtable slot */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* No match */
mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
/* Load fail addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
emit_code_bytes (acfg, buf, code - buf);
common_tramp_size = code - buf;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
}
static void
arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Load argument from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
/* Load generic trampoline address from first GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
static void
arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
{
emit_unset_mode (acfg);
fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
fprintf (acfg->fp, "b %s\n", call_target);
}
static void
arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
/* Load argument from first GOT slot */
arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
/* Load generic trampoline address from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
static void
arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
guint8 buf [128];
guint8 *code, *labels [16];
/* Load parameter from GOT slot into ip1 */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
code = buf;
labels [0] = code;
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, 0);
arm_cmpp (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
labels [1] = code;
arm_bcc (code, ARMCOND_EQ, 0);
/* End-of-loop check */
labels [2] = code;
arm_cbzx (code, ARMREG_IP0, 0);
/* Loop footer */
arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
arm_b (code, labels [0]);
/* Match */
mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
/* Load vtable slot addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
/* Load vtable slot */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP0, 0);
code = mono_arm_emit_brx (code, ARMREG_IP0);
/* No match */
mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
/* Load fail addr */
arm_ldrp (code, ARMREG_IP0, ARMREG_IP1, TARGET_SIZEOF_VOID_P);
code = mono_arm_emit_brx (code, ARMREG_IP0);
emit_code_bytes (acfg, buf, code - buf);
*tramp_size = code - buf + (3 * 4);
}
static void
arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/* Similar to the specific trampolines, but the address is in the second slot */
/* Load argument from first GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
/* Load generic trampoline address from second GOT slot */
arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
#ifdef MONO_ARCH_ENABLE_PTRAUTH
fprintf (acfg->fp, "braaz x16\n");
#else
fprintf (acfg->fp, "br x16\n");
#endif
*tramp_size = 7 * 4;
}
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_direct_call:
*
* Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
* calling code.
*/
static void
arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
/* Need to make sure this is exactly 5 bytes long */
emit_unset_mode (acfg);
fprintf (acfg->fp, "call %s\n", target);
*call_size = 5;
#elif defined(TARGET_ARM)
emit_unset_mode (acfg);
if (thumb)
fprintf (acfg->fp, "blx %s\n", target);
else
fprintf (acfg->fp, "bl %s\n", target);
*call_size = 4;
#elif defined(TARGET_ARM64)
arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
#elif defined(TARGET_POWERPC)
emit_unset_mode (acfg);
fprintf (acfg->fp, "bl %s\n", target);
*call_size = 4;
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_label_address (MonoAotCompile *acfg, const char *target, gboolean external_call, gboolean thumb, MonoJumpInfo *ji, int *call_size)
{
#if defined(TARGET_ARM) && defined(TARGET_ANDROID)
/* binutils ld does not support branch islands on arm32 */
if (!thumb) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "ldr pc,=%s\n", target);
fprintf (acfg->fp, ".ltorg\n");
*call_size = 8;
} else
#endif
arch_emit_direct_call (acfg, target, external_call, thumb, ji, call_size);
}
#endif
/*
* PPC32 design:
* - we use an approach similar to the x86 abi: reserve a register (r30) to hold
* the GOT pointer.
* - The full-aot trampolines need access to the GOT of mscorlib, so we store
* in in the 2. slot of every GOT, and require every method to place the GOT
* address in r30, even when it doesn't access the GOT otherwise. This way,
* the trampolines can compute the mscorlib GOT address by loading 4(r30).
*/
/*
* PPC64 design:
* PPC64 uses function descriptors which greatly complicate all code, since
* these are used very inconsistently in the runtime. Some functions like
* mono_compile_method () return ftn descriptors, while others like the
* trampoline creation functions do not.
* We assume that all GOT slots contain function descriptors, and create
* descriptors in aot-runtime.c when needed.
* The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
* from function descriptors, we could do the same, but it would require
* rewriting all the ppc/aot code to handle function descriptors properly.
* So instead, we use the same approach as on PPC32.
* This is a horrible mess, but fixing it would probably lead to an even bigger
* one.
*/
/*
* X86 design:
* - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
*/
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_got_offset:
*
* The memory pointed to by CODE should hold native code for computing the GOT
* address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
* between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
*/
static void
arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
{
#if defined(TARGET_POWERPC64)
emit_unset_mode (acfg);
/*
* The ppc32 code doesn't seem to work on ppc64, the assembler complains about
* unsupported relocations. So we store the got address into the .Lgot_addr
* symbol which is in the text segment, compute its address, and load it.
*/
fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
fprintf (acfg->fp, "add 30, 30, 0\n");
fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
acfg->label_generator ++;
*code_size = 16;
#elif defined(TARGET_POWERPC)
emit_unset_mode (acfg);
fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
acfg->label_generator ++;
*code_size = 8;
#else
guint32 offset = mono_arch_get_patch_offset (code);
emit_bytes (acfg, code, offset);
emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
*code_size = offset + 4;
#endif
}
/*
* arch_emit_got_access:
*
* The memory pointed to by CODE should hold native code for loading a GOT
* slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
* GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
*/
static void
arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
{
#ifdef TARGET_AMD64
/* mov reg, got+offset(%rip) */
if (acfg->llvm) {
/* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
int dreg;
int rex_r;
/* Decode reg, see amd64_mov_reg_membase () */
rex_r = code [0] & AMD64_REX_R;
g_assert (code [0] == 0x49 + rex_r);
g_assert (code [1] == 0x8b);
dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
*code_size = 7;
} else {
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
*code_size = mono_arch_get_patch_offset (code) + 4;
}
#elif defined(TARGET_X86)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
*code_size = mono_arch_get_patch_offset (code) + 4;
#elif defined(TARGET_ARM)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
*code_size = mono_arch_get_patch_offset (code) + 4;
#elif defined(TARGET_ARM64)
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
arm64_emit_got_access (acfg, code, got_slot, code_size);
#elif defined(TARGET_POWERPC)
{
guint8 buf [32];
emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
code = buf;
ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
*code_size = code - buf;
}
#else
g_assert_not_reached ();
#endif
}
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
/*
* arch_emit_objc_selector_ref:
*
* Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
*/
static void
arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
{
#if defined(TARGET_ARM)
char symbol1 [MAX_SYMBOL_SIZE];
char symbol2 [MAX_SYMBOL_SIZE];
int lindex = acfg->objc_selector_index_2 ++;
/* Emit ldr.imm/b */
emit_bytes (acfg, code, 8);
sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
emit_label (acfg, symbol1);
mono_img_writer_emit_unset_mode (acfg->w);
fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
*code_size = 12;
#elif defined(TARGET_ARM64)
arm64_emit_objc_selector_ref (acfg, code, index, code_size);
#else
g_assert_not_reached ();
#endif
}
#endif
#ifdef MONO_ARCH_CODE_EXEC_ONLY
#if defined(TARGET_AMD64)
/* Keep in sync with tramp-amd64.c, aot_arch_get_plt_entry_index. */
#define PLT_ENTRY_OFFSET_REG AMD64_RAX
#endif
#endif
/*
* arch_emit_plt_entry:
*
* Emit code for the PLT entry.
* The plt entry should look like this on architectures where code is read/execute:
* <indirect jump to GOT_SYMBOL + OFFSET>
* <INFO_OFFSET embedded into the instruction stream>
* The plt entry should look like this on architectures where code is execute only:
* mov RAX, PLT entry offset
* <indirect jump to GOT_SYMBOL + OFFSET>
*/
static void
arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, guint32 plt_index, int offset, int info_offset)
{
#if defined(TARGET_X86)
/* jmp *<offset>(%ebx) */
emit_byte (acfg, 0xff);
emit_byte (acfg, 0xa3);
emit_int32 (acfg, offset);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
#elif defined(TARGET_AMD64)
#ifdef MONO_ARCH_CODE_EXEC_ONLY
guint8 buf [16];
guint8 *code = buf;
/* Emit smallest possible imm size 1, 2 or 4 bytes based on total number of PLT entries. */
if (acfg->plt_offset <= (guint32)0xFF) {
amd64_emit_rex(code, sizeof (guint8), 0, 0, PLT_ENTRY_OFFSET_REG);
*(code)++ = (unsigned char)0xb0 + (PLT_ENTRY_OFFSET_REG & 0x7);
x86_imm_emit8 (code, (guint8)(plt_index));
} else if (acfg->plt_offset <= (guint32)0xFFFF) {
x86_prefix(code, X86_OPERAND_PREFIX);
amd64_emit_rex(code, sizeof (guint16), 0, 0, PLT_ENTRY_OFFSET_REG);
*(code)++ = (unsigned char)0xb8 + (PLT_ENTRY_OFFSET_REG & 0x7);
x86_imm_emit16 (code, (guint16)(plt_index));
} else {
amd64_mov_reg_imm_size (code, PLT_ENTRY_OFFSET_REG, plt_index, sizeof(plt_index));
}
emit_bytes (acfg, buf, code - buf);
acfg->stats.plt_size += code - buf;
emit_unset_mode (acfg);
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
acfg->stats.plt_size += 6;
#else
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
acfg->stats.plt_size += 10;
#endif
#elif defined(TARGET_ARM)
guint8 buf [256];
guint8 *code;
code = buf;
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
/* Used by mono_aot_get_plt_info_offset */
emit_int32 (acfg, info_offset);
#elif defined(TARGET_ARM64)
arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
#elif defined(TARGET_POWERPC)
/* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
emit_unset_mode (acfg);
fprintf (acfg->fp, "lis 11, %d@h\n", offset);
fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
fprintf (acfg->fp, "add 11, 11, 30\n");
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
fprintf (acfg->fp, "bctr\n");
emit_int32 (acfg, info_offset);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_llvm_plt_entry:
*
* Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
* This is only needed on arm to handle thumb interop.
*/
static void
arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int plt_index, int offset, int info_offset)
{
#if defined(TARGET_ARM)
/* LLVM calls the PLT entries using bl, so these have to be thumb2 */
/* The caller already transitioned to thumb */
/* The code below should be 12 bytes long */
/* clang has trouble encoding these instructions, so emit the binary */
#if 0
fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
/* thumb can't encode ld pc, [pc, ip] */
fprintf (acfg->fp, "add ip, pc, ip\n");
fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
fprintf (acfg->fp, "bx ip\n");
#endif
emit_set_thumb_mode (acfg);
fprintf (acfg->fp, ".4byte 0xc008f8df\n");
fprintf (acfg->fp, ".2byte 0x44fc\n");
fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
fprintf (acfg->fp, ".2byte 0x4760\n");
emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
emit_int32 (acfg, info_offset);
emit_unset_mode (acfg);
emit_set_arm_mode (acfg);
#else
g_assert_not_reached ();
#endif
}
/* Save unwind_info in the module and emit the offset to the information at symbol */
static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
{
guint32 uw_offset, encoded_len;
guint8 *encoded;
emit_section_change (acfg, RODATA_SECT, 0);
emit_global (acfg, symbol, FALSE);
emit_label (acfg, symbol);
encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
g_free (encoded);
emit_int32 (acfg, uw_offset);
}
/*
* arch_emit_specific_trampoline_pages:
*
* Emits a page full of trampolines: each trampoline uses its own address to
* lookup both the generic trampoline code and the data argument.
* This page can be remapped in process multiple times so we can get an
* unlimited number of trampolines.
* Specifically this implementation uses the following trick: two memory pages
* are allocated, with the first containing the data and the second containing the trampolines.
* To reduce trampoline size, each trampoline jumps at the start of the page where a common
* implementation does all the lifting.
* Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
* on the arm 32 bit system.
*/
static void
arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
{
#if defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
int i;
int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
GSList *unwind_ops = NULL;
#define COMMON_TRAMP_SIZE 16
int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
int imm8, rot_amount;
char symbol [128];
if (!acfg->aot_opts.use_trampolines_page)
return;
acfg->tramp_page_size = pagesize;
sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
emit_alignment (acfg, pagesize);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
/* emit the generic code first, the trampoline address + 8 is in the lr register */
code = buf;
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_PUSH (code, 0x5fff);
ARM_BL (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the rgctx trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the values
* We again fit the generic trampiline in 16 bytes.
*/
sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/*
* gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
*/
sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the target addr.
* We again fit the generic trampoline in 16 bytes.
*/
sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
ARM_NOP (code);
g_assert (code - buf == COMMON_TRAMP_SIZE);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
/* now the imt trampolines: each specific trampolines puts in the ip register
* the instruction pointer address, so the generic trampoline at the start of the page
* subtracts 4096 to get to the data page and loads the values
*/
#define IMT_TRAMP_SIZE 72
sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
emit_global (acfg, symbol, TRUE);
emit_label (acfg, symbol);
code = buf;
/* Need at least two free registers, plus a slot for storing the pc */
ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
/* The IMT method is in v5, r0 has the imt array address */
loop_start = code;
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
imt_found_check = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* End-of-loop check */
ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
loop_end_check = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* Loop footer */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
loop_branch_back = code;
ARM_B (code, 0);
arm_patch (loop_branch_back, loop_start);
/* Match */
arm_patch (imt_found_check, code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
/* Save it to the third stack slot */
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
/* Restore the registers and branch */
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* No match */
arm_patch (loop_end_check, code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
ARM_NOP (code);
/* Emit it */
g_assert (code - buf == IMT_TRAMP_SIZE);
emit_bytes (acfg, buf, code - buf);
for (i = 0; i < count; ++i) {
code = buf;
ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
ARM_B (code, 0);
arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
g_assert (code - buf == 8);
emit_bytes (acfg, buf, code - buf);
}
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
/* Unwind info for specifc trampolines */
sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
/* We unwind to the original caller, from the stack, since lr is clobbered */
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for rgctx trampolines */
sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for gsharedvt trampolines */
sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for unbox arbitrary trampolines */
sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Unwind info for imt trampolines */
sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
save_unwind_info (acfg, symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
#elif defined(TARGET_ARM64)
arm64_emit_specific_trampoline_pages (acfg);
#endif
}
/*
* arch_emit_specific_trampoline:
*
* Emit code for a specific trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the generic trampoline address and the trampoline
* argument. TRAMP_SIZE is set to the size of the emitted trampoline.
*/
static void
arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
/*
* The trampolines created here are variations of the specific
* trampolines created in mono_arch_create_specific_trampoline (). The
* differences are:
* - the generic trampoline address is taken from a got slot.
* - the offset of the got slot where the trampoline argument is stored
* is embedded in the instruction stream, and the generic trampoline
* can load the argument by loading the offset, adding it to the
* address of the trampoline to get the address of the got slot, and
* loading the argument from there.
* - all the trampolines should be of the same length.
*/
#if defined(TARGET_AMD64)
/* This should be exactly 8 bytes long */
*tramp_size = 8;
/* call *<offset>(%rip) */
if (acfg->llvm) {
emit_byte (acfg, '\x41');
emit_unset_mode (acfg);
fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
emit_zero_bytes (acfg, 1);
} else {
emit_byte (acfg, '\x41');
emit_byte (acfg, '\xff');
emit_byte (acfg, '\x15');
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
emit_zero_bytes (acfg, 1);
}
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* This should be exactly 20 bytes long */
*tramp_size = 20;
code = buf;
ARM_PUSH (code, 0x5fff);
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
/* Load the value from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
/* Branch to it */
ARM_BLX_REG (code, ARMREG_R1);
g_assert (code - buf == 16);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
/*
* Only one offset is needed, since the second one would be equal to the
* first one.
*/
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
//emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
#elif defined(TARGET_ARM64)
arm64_emit_specific_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code;
*tramp_size = 4;
code = buf;
/*
* PPC has no ip relative addressing, so we need to compute the address
* of the mscorlib got. That is slow and complex, so instead, we store it
* in the second got slot of every aot image. The caller already computed
* the address of its got and placed it into r30.
*/
emit_unset_mode (acfg);
/* Load mscorlib got address */
fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
/* Load generic trampoline address */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
/* Load trampoline argument */
/* On ppc, we pass it normally to the generic trampoline */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
/* Branch to generic trampoline */
fprintf (acfg->fp, "bctr\n");
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
*tramp_size = 10 * 4;
#else
*tramp_size = 9 * 4;
#endif
#elif defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
/* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Push trampoline argument */
x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
/* Load generic trampoline address */
x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to generic trampoline */
x86_jump_reg (code, X86_ECX);
emit_bytes (acfg, buf, code - buf);
*tramp_size = 17;
g_assert (code - buf == *tramp_size);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_unbox_trampoline:
*
* Emit code for the unbox trampoline for METHOD used in the full-aot case.
* CALL_TARGET is the symbol pointing to the native code of METHOD.
*
* See mono_aot_get_unbox_trampoline.
*/
static void
arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
{
#if defined(TARGET_AMD64)
guint8 buf [32];
guint8 *code;
int this_reg;
this_reg = mono_arch_get_this_arg_reg (NULL);
code = buf;
amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump <method> */
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "jmp %s\n", call_target);
} else {
emit_byte (acfg, '\xe9');
emit_symbol_diff (acfg, call_target, ".", -4);
}
#elif defined(TARGET_X86)
guint8 buf [32];
guint8 *code;
int this_pos = 4;
code = buf;
x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump <method> */
emit_byte (acfg, '\xe9');
emit_symbol_diff (acfg, call_target, ".", -4);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
if (acfg->thumb_mixed && cfg->compile_llvm) {
fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
fprintf (acfg->fp, "b %s\n", call_target);
fprintf (acfg->fp, ".arm\n");
fprintf (acfg->fp, ".align 2\n");
return;
}
code = buf;
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
/* jump to method */
if (acfg->thumb_mixed && cfg->compile_llvm)
fprintf (acfg->fp, "\n\tbx %s\n", call_target);
else
fprintf (acfg->fp, "\n\tb %s\n", call_target);
#elif defined(TARGET_ARM64)
arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
#elif defined(TARGET_POWERPC)
int this_pos = 3;
fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
fprintf (acfg->fp, "\n\tb %s\n", call_target);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_static_rgctx_trampoline:
*
* Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the rgctx argument, and the method to jump to.
* TRAMP_SIZE is set to the size of the emitted trampoline.
* These kinds of trampolines cannot be enumerated statically, since there could
* be one trampoline per method instantiation, so we emit the same code for all
* trampolines, and parameterize them using two GOT slots.
*/
static void
arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_AMD64)
/* This should be exactly 13 bytes long */
*tramp_size = 13;
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
} else {
/* mov <OFFSET>(%rip), %r10 */
emit_byte (acfg, '\x4d');
emit_byte (acfg, '\x8b');
emit_byte (acfg, '\x15');
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
/* jmp *<offset>(%rip) */
emit_byte (acfg, '\xff');
emit_byte (acfg, '\x25');
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
}
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* This should be exactly 24 bytes long */
*tramp_size = 24;
code = buf;
/* Load rgctx value */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
/* Load branch addr + branch */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
g_assert (code - buf == 16);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
#elif defined(TARGET_ARM64)
arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code;
*tramp_size = 4;
code = buf;
/*
* PPC has no ip relative addressing, so we need to compute the address
* of the mscorlib got. That is slow and complex, so instead, we store it
* in the second got slot of every aot image. The caller already computed
* the address of its got and placed it into r30.
*/
emit_unset_mode (acfg);
/* Load mscorlib got address */
fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
/* Load rgctx */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
/* Load target address */
fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
#endif
fprintf (acfg->fp, "mtctr 11\n");
/* Branch to the target address */
fprintf (acfg->fp, "bctr\n");
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
*tramp_size = 11 * 4;
#else
*tramp_size = 9 * 4;
#endif
#elif defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to the target address */
x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
emit_bytes (acfg, buf, code - buf);
*tramp_size = 15;
g_assert (code - buf == *tramp_size);
#else
g_assert_not_reached ();
#endif
}
/*
* arch_emit_imt_trampoline:
*
* Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
* points to an array of pointer pairs. The pairs of the form [key, ptr], where
* key is the IMT key, and ptr holds the address of a memory location holding
* the address to branch to if the IMT arg matches the key. The array is
* terminated by a pair whose key is NULL, and whose ptr is the address of the
* fail_tramp.
* TRAMP_SIZE is set to the size of the emitted trampoline.
*/
static void
arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_AMD64)
guint8 *buf, *code;
guint8 *labels [16];
guint8 mov_buf[3];
guint8 *mov_buf_ptr = mov_buf;
const int kSizeOfMove = 7;
code = buf = (guint8 *)g_malloc (256);
/* FIXME: Optimize this, i.e. use binary search etc. */
/* Maybe move the body into a separate function (slower, but much smaller) */
/* MONO_ARCH_IMT_SCRATCH_REG is a free register */
if (acfg->llvm) {
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
}
labels [0] = code;
amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
labels [1] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Check key */
amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
labels [2] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Loop footer */
amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
amd64_jump_code (code, labels [0]);
/* Match */
mono_amd64_patch (labels [2], code);
amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
/* No match */
mono_amd64_patch (labels [1], code);
/* Load fail tramp */
amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
/* Check if there is a fail tramp */
amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
labels [3] = code;
amd64_branch8 (code, X86_CC_Z, 0, FALSE);
/* Jump to fail tramp */
amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
/* Fail */
mono_amd64_patch (labels [3], code);
x86_breakpoint (code);
if (!acfg->llvm) {
/* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
*(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
}
emit_bytes (acfg, buf, code - buf);
*tramp_size = code - buf + kSizeOfMove;
g_free (buf);
#elif defined(TARGET_X86)
guint8 *buf, *code;
guint8 *labels [16];
code = buf = g_malloc (256);
/* Allocate a temporary stack slot */
x86_push_reg (code, X86_EAX);
/* Save EAX */
x86_push_reg (code, X86_EAX);
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
labels [0] = code;
x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
labels [1] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Check key */
x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
labels [2] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Loop footer */
x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
x86_jump_code (code, labels [0]);
/* Match */
mono_x86_patch (labels [2], code);
x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
/* Save the target address to the temporary stack location */
x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
/* Restore EAX */
x86_pop_reg (code, X86_EAX);
/* Jump to the target address */
x86_ret (code);
/* No match */
mono_x86_patch (labels [1], code);
/* Load fail tramp */
x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
labels [3] = code;
x86_branch8 (code, X86_CC_Z, FALSE, 0);
/* Jump to fail tramp */
x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
x86_pop_reg (code, X86_EAX);
x86_ret (code);
/* Fail */
mono_x86_patch (labels [3], code);
x86_breakpoint (code);
emit_bytes (acfg, buf, code - buf);
*tramp_size = code - buf;
g_free (buf);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code, *code2, *labels [16];
code = buf;
/* The IMT method is in v5 */
/* Need at least two free registers, plus a slot for storing the pc */
ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
labels [0] = code;
/* Load the parameter from the GOT */
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
labels [1] = code;
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
labels [2] = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* End-of-loop check */
ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
labels [3] = code;
ARM_B_COND (code, ARMCOND_EQ, 0);
/* Loop footer */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
labels [4] = code;
ARM_B (code, 0);
arm_patch (labels [4], labels [1]);
/* Match */
arm_patch (labels [2], code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
/* Save it to the third stack slot */
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
/* Restore the registers and branch */
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* No match */
arm_patch (labels [3], code);
ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
/* Fixup offset */
code2 = labels [0];
ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
*tramp_size = code - buf + 4;
#elif defined(TARGET_ARM64)
arm64_emit_imt_trampoline (acfg, offset, tramp_size);
#elif defined(TARGET_POWERPC)
guint8 buf [128];
guint8 *code, *labels [16];
code = buf;
/* Load the mscorlib got address */
ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
/* Load the parameter from the GOT */
ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
/* Load and check key */
labels [1] = code;
ppc_ldptr (code, ppc_r0, 0, ppc_r12);
ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
labels [2] = code;
ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
/* End-of-loop check */
ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
labels [3] = code;
ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
/* Loop footer */
ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
labels [4] = code;
ppc_b (code, 0);
mono_ppc_patch (labels [4], labels [1]);
/* Match */
mono_ppc_patch (labels [2], code);
ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
/* r12 now contains the value of the vtable slot */
/* this is not a function descriptor on ppc64 */
ppc_ldptr (code, ppc_r12, 0, ppc_r12);
ppc_mtctr (code, ppc_r12);
ppc_bcctr (code, PPC_BR_ALWAYS, 0);
/* Fail */
mono_ppc_patch (labels [3], code);
/* FIXME: */
ppc_break (code);
*tramp_size = code - buf;
emit_bytes (acfg, buf, code - buf);
#else
g_assert_not_reached ();
#endif
}
#if defined (TARGET_AMD64)
static void
amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
{
g_assert (acfg->fp);
emit_unset_mode (acfg);
fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
}
#endif
/*
* arch_emit_gsharedvt_arg_trampoline:
*
* Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
* two GOT slots which contain the argument, and the code to jump to.
* TRAMP_SIZE is set to the size of the emitted trampoline.
* These kinds of trampolines cannot be enumerated statically, since there could
* be one trampoline per method instantiation, so we emit the same code for all
* trampolines, and parameterize them using two GOT slots.
*/
static void
arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_X86)
guint8 buf [128];
guint8 *code;
/* Similar to the PPC code above */
g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
code = buf;
/* Load mscorlib got address */
x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
/* Load arg */
x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
/* Branch to the target address */
x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
emit_bytes (acfg, buf, code - buf);
*tramp_size = 15;
g_assert (code - buf == *tramp_size);
#elif defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
/* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
/* Similar to arch_emit_specific_trampoline () */
*tramp_size = 24;
code = buf;
ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
/* Load the arg value from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
/* Load the addr from the GOT */
ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
/* Branch to it */
ARM_BX (code, ARMREG_R1);
g_assert (code - buf == 20);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
#elif defined(TARGET_ARM64)
arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
#elif defined (TARGET_AMD64)
amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
fprintf (acfg->fp, "jmp *%%r11\n");
*tramp_size = 0x11;
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_ARM)
guint8 buf [128];
guint8 *code;
*tramp_size = 32;
code = buf;
/* Load target address and push it on stack */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
ARM_PUSH (code, 1 << ARMREG_IP);
/* Load argument in ARMREG_IP */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
/* Branch */
ARM_POP (code, 1 << ARMREG_PC);
g_assert (code - buf == 24);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
#else
g_assert_not_reached ();
#endif
}
static void
arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
{
#if defined(TARGET_ARM64)
emit_unset_mode (acfg);
fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
fprintf (acfg->fp, "br x17\n");
*tramp_size = 5 * 4;
#elif defined (TARGET_AMD64)
guint8 buf [32];
guint8 *code;
int this_reg;
this_reg = mono_arch_get_this_arg_reg (NULL);
code = buf;
amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
emit_bytes (acfg, buf, code - buf);
amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
fprintf (acfg->fp, "jmp *%%rax\n");
*tramp_size = 13;
#elif defined (TARGET_ARM)
guint8 buf [32];
guint8 *code, *label;
code = buf;
/* Unbox */
ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
label = code;
/* Calculate GOT slot */
ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
/* Load target addr into PC*/
ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
g_assert (code - buf == 12);
/* Emit it */
emit_bytes (acfg, buf, code - buf);
emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
*tramp_size = 4 * 4;
#else
g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
#endif
}
/* END OF ARCH SPECIFIC CODE */
static guint32
mono_get_field_token (MonoClassField *field)
{
MonoClass *klass = m_field_get_parent (field);
int i;
int fcount = mono_class_get_field_count (klass);
MonoClassField *klass_fields = m_class_get_fields (klass);
for (i = 0; i < fcount; ++i) {
if (field == &klass_fields [i])
return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
}
g_assert_not_reached ();
return 0;
}
static void
encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
//printf ("ENCODE: %d 0x%x.\n", value, value);
/*
* Same encoding as the one used in the metadata, extended to handle values
* greater than 0x1fffffff.
*/
if ((value >= 0) && (value <= 127))
*p++ = value;
else if ((value >= 0) && (value <= 16383)) {
p [0] = 0x80 | (value >> 8);
p [1] = value & 0xff;
p += 2;
} else if ((value >= 0) && (value <= 0x1fffffff)) {
p [0] = (value >> 24) | 0xc0;
p [1] = (value >> 16) & 0xff;
p [2] = (value >> 8) & 0xff;
p [3] = value & 0xff;
p += 4;
}
else {
p [0] = 0xff;
p [1] = (value >> 24) & 0xff;
p [2] = (value >> 16) & 0xff;
p [3] = (value >> 8) & 0xff;
p [4] = value & 0xff;
p += 5;
}
if (endbuf)
*endbuf = p;
}
static void
stream_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = (char *)g_malloc (4096);
/* So offsets are > 0 */
sh->data [0] = 0;
sh->index ++;
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
}
static guint32
add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
return idx;
}
/*
* add_to_blob:
*
* Add data to the binary blob inside the aot image. Returns the offset inside the
* blob where the data was stored.
*/
static guint32
add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
{
g_assert (!acfg->blob_closed);
if (acfg->blob.alloc_size == 0)
stream_init (&acfg->blob);
acfg->stats.blob_size += data_len;
return add_stream_data (&acfg->blob, (char*)data, data_len);
}
typedef struct {
guint8 *data;
int len, align;
guint32 offset;
} BlobItem;
static guint
blob_item_hash (gconstpointer key)
{
BlobItem *item = (BlobItem*)key;
guint i, a;
for (i = a = 0; i < item->len; ++i)
a ^= (((guint)item->data [i]) << (i & 0xf));
return a;
}
static gboolean
blob_item_equal (gconstpointer a, gconstpointer b)
{
BlobItem *item1 = (BlobItem*)a;
BlobItem *item2 = (BlobItem*)b;
if (item1->len != item2->len || item1->align != item2->align)
return FALSE;
return memcmp (item1->data, item2->data, item1->len) == 0;
}
static void
blob_item_free (gpointer val)
{
BlobItem *item = (BlobItem*)val;
g_free (item->data);
g_free (item);
}
static guint32
add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
{
char buf [4] = {0};
guint32 count;
if (acfg->blob.alloc_size == 0)
stream_init (&acfg->blob);
count = acfg->blob.index % align;
BlobItem tmp;
tmp.data = (guint8*)data;
tmp.len = data_len;
tmp.align = align;
if (!acfg->blob_hash)
acfg->blob_hash = g_hash_table_new_full (blob_item_hash, blob_item_equal, NULL, blob_item_free);
BlobItem *cached = g_hash_table_lookup (acfg->blob_hash, &tmp);
if (cached)
return cached->offset;
/* we assume the stream data will be aligned */
if (count)
add_stream_data (&acfg->blob, buf, 4 - count);
guint32 offset = add_stream_data (&acfg->blob, (char*)data, data_len);
BlobItem *item = g_new0 (BlobItem, 1);
item->data = g_malloc (data_len);
memcpy (item->data, data, data_len);
item->len = data_len;
item->align = align;
item->offset = offset;
g_hash_table_insert (acfg->blob_hash, item, item);
return offset;
}
/* Emit a table of data into the aot image */
static void
emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
{
if (acfg->data_outfile) {
acfg->table_offsets [(int)table] = acfg->datafile_offset;
fwrite (data,1, size, acfg->data_outfile);
acfg->datafile_offset += size;
// align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
int align = 8 - size % 8;
acfg->datafile_offset += align;
guint8 align_buf [16];
memset (&align_buf, 0, sizeof (align_buf));
fwrite (align_buf, align, 1, acfg->data_outfile);
} else if (acfg->llvm) {
mono_llvm_emit_aot_data (symbol, data, size);
} else {
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
emit_bytes (acfg, data, size);
}
}
/*
* emit_offset_table:
*
* Emit a table of increasing offsets in a compact form using differential encoding.
* There is an index entry for each GROUP_SIZE number of entries. The greater the
* group size, the more compact the table becomes, but the slower it becomes to compute
* a given entry. Returns the size of the table.
*/
static guint32
emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
{
gint32 current_offset;
int i, buf_size, ngroups, index_entry_size;
guint8 *p, *buf;
guint8 *data_p, *data_buf;
guint32 *index_offsets;
ngroups = (noffsets + (group_size - 1)) / group_size;
index_offsets = g_new0 (guint32, ngroups);
buf_size = noffsets * 4;
p = buf = (guint8 *)g_malloc0 (buf_size);
current_offset = 0;
for (i = 0; i < noffsets; ++i) {
//printf ("D: %d -> %d\n", i, offsets [i]);
if ((i % group_size) == 0) {
index_offsets [i / group_size] = p - buf;
/* Emit the full value for these entries */
encode_value (offsets [i], p, &p);
} else {
/* The offsets are allowed to be non-increasing */
//g_assert (offsets [i] >= current_offset);
encode_value (offsets [i] - current_offset, p, &p);
}
current_offset = offsets [i];
}
data_buf = buf;
data_p = p;
if (ngroups && index_offsets [ngroups - 1] < 65000)
index_entry_size = 2;
else
index_entry_size = 4;
buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
p = buf = (guint8 *)g_malloc0 (buf_size);
/* Emit the header */
encode_int (noffsets, p, &p);
encode_int (group_size, p, &p);
encode_int (ngroups, p, &p);
encode_int (index_entry_size, p, &p);
/* Emit the index */
for (i = 0; i < ngroups; ++i) {
if (index_entry_size == 2)
encode_int16 (index_offsets [i], p, &p);
else
encode_int (index_offsets [i], p, &p);
}
/* Emit the data */
memcpy (p, data_buf, data_p - data_buf);
p += data_p - data_buf;
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, table, symbol, buf, p - buf);
g_free (buf);
g_free (data_buf);
return (int)(p - buf);
}
static guint32
get_image_index (MonoAotCompile *cfg, MonoImage *image)
{
guint32 index;
index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
if (index)
return index - 1;
else {
index = g_hash_table_size (cfg->image_hash);
g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
g_ptr_array_add (cfg->image_table, image);
return index;
}
}
static guint32
find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
{
int i;
int len = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
/* FIXME: Search referenced images as well */
if (!acfg->typespec_classes) {
acfg->typespec_classes = g_hash_table_new (NULL, NULL);
for (i = 0; i < len; i++) {
ERROR_DECL (error);
int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
continue;
}
g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
}
}
return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
}
static void
encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
static void
encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
static void
encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
static void
encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
static guint32
get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
static void
encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
/*
* The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
* information.
*/
if (mono_class_is_ginst (klass)) {
guint32 token;
g_assert (m_class_get_type_token (klass));
/* Find a typespec for a class if possible */
token = find_typespec_for_class (acfg, klass);
if (token) {
encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
encode_value (token, p, &p);
} else {
MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
static int count = 0;
guint8 *p1 = p;
encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
encode_klass_ref (acfg, gclass, p, &p);
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
count += p - p1;
}
} else if (m_class_get_type_token (klass)) {
int iindex = get_image_index (acfg, m_class_get_image (klass));
g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
if (iindex == 0) {
encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
} else {
encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
}
} else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
encode_value (par->gshared_constraint ? 1 : 0, p, &p);
if (par->gshared_constraint) {
MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
encode_type (acfg, par->gshared_constraint, p, &p);
encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
} else {
encode_value (m_class_get_byval_arg (klass)->type, p, &p);
encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
encode_value (container->is_anonymous ? 0 : 1, p, &p);
if (!container->is_anonymous) {
encode_value (container->is_method, p, &p);
if (container->is_method)
encode_method_ref (acfg, container->owner.method, p, &p);
else
encode_klass_ref (acfg, container->owner.klass, p, &p);
}
}
} else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
} else {
/* Array class */
g_assert (m_class_get_rank (klass) > 0);
encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
encode_value (m_class_get_rank (klass), p, &p);
encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
}
acfg->stats.class_ref_count++;
acfg->stats.class_ref_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
{
guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
guint8 *buf2, *p;
if (!offset) {
buf2 = (guint8 *)g_malloc (1024);
p = buf2;
encode_klass_ref_inner (acfg, klass, p, &p);
g_assert (p - buf2 < 1024);
offset = add_to_blob (acfg, buf2, p - buf2);
g_free (buf2);
g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
/*
* encode_klass_ref:
*
* Encode a reference to KLASS. We use our home-grown encoding instead of the
* standard metadata encoding.
*/
static void
encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
{
gboolean shared = FALSE;
/*
* The encoding of generic instances is large so emit them only once.
*/
if (mono_class_is_ginst (klass)) {
guint32 token;
g_assert (m_class_get_type_token (klass));
/* Find a typespec for a class if possible */
token = find_typespec_for_class (acfg, klass);
if (!token)
shared = TRUE;
} else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
shared = TRUE;
}
if (shared) {
guint8 *p;
guint32 offset = get_shared_klass_ref (acfg, klass);
p = buf;
encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
encode_value (offset, p, &p);
*endbuf = p;
return;
}
encode_klass_ref_inner (acfg, klass, buf, endbuf);
}
static void
encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
{
guint32 token = mono_get_field_token (field);
guint8 *p = buf;
encode_klass_ref (cfg, m_field_get_parent (field), p, &p);
g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
*endbuf = p;
}
static void
encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
int i;
encode_value (inst->type_argc, p, &p);
for (i = 0; i < inst->type_argc; ++i)
encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
acfg->stats.ginst_count++;
acfg->stats.ginst_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
{
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
if (!offset) {
guint8 *buf2, *p2;
int len;
len = 1024 + (ginst->type_argc * 32);
buf2 = (guint8 *)g_malloc (len);
p2 = buf2;
encode_ginst (acfg, ginst, p2, &p2);
g_assert (p2 - buf2 < len);
offset = add_to_blob (acfg, buf2, p2 - buf2);
g_free (buf2);
g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
static void
encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
MonoGenericInst *inst;
guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
g_assert (flags);
encode_value (flags, p, &p);
inst = context->class_inst;
if (inst) {
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
}
inst = context->method_inst;
if (inst) {
guint32 offset = get_shared_ginst_ref (acfg, inst);
encode_value (offset, p, &p);
}
*endbuf = p;
}
static void
encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
if (t->has_cmods) {
int count = mono_type_custom_modifier_count (t);
*p = MONO_TYPE_CMOD_REQD;
++p;
encode_value (count, p, &p);
for (int i = 0; i < count; ++i) {
ERROR_DECL (error);
gboolean required;
MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
mono_error_assert_ok (error);
encode_value (required, p, &p);
encode_type (acfg, cmod_type, p, &p);
}
}
/* t->attrs can be ignored */
//g_assert (t->attrs == 0);
if (t->pinned) {
*p = MONO_TYPE_PINNED;
++p;
}
if (m_type_is_byref (t)) {
*p = MONO_TYPE_BYREF;
++p;
}
*p = t->type;
p ++;
switch (t->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:
encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
break;
case MONO_TYPE_SZARRAY:
encode_klass_ref (acfg, t->data.klass, p, &p);
break;
case MONO_TYPE_PTR:
encode_type (acfg, t->data.type, p, &p);
break;
case MONO_TYPE_FNPTR:
encode_signature (acfg, t->data.method, p, &p);
break;
case MONO_TYPE_GENERICINST: {
MonoClass *gclass = t->data.generic_class->container_class;
MonoGenericInst *inst = t->data.generic_class->context.class_inst;
encode_klass_ref (acfg, gclass, p, &p);
encode_ginst (acfg, inst, p, &p);
break;
}
case MONO_TYPE_ARRAY: {
MonoArrayType *array = t->data.array;
int i;
encode_klass_ref (acfg, array->eklass, p, &p);
encode_value (array->rank, p, &p);
encode_value (array->numsizes, p, &p);
for (i = 0; i < array->numsizes; ++i)
encode_value (array->sizes [i], p, &p);
encode_value (array->numlobounds, p, &p);
for (i = 0; i < array->numlobounds; ++i)
encode_value (array->lobounds [i], p, &p);
break;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
break;
default:
g_assert_not_reached ();
}
*endbuf = p;
}
static void
encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
guint32 flags = 0;
int i;
/* Similar to the metadata encoding */
if (sig->generic_param_count)
flags |= 0x10;
if (sig->hasthis)
flags |= 0x20;
if (sig->explicit_this)
flags |= 0x40;
if (sig->pinvoke)
flags |= 0x80;
flags |= (sig->call_convention & 0x0F);
*p = flags;
++p;
if (sig->generic_param_count)
encode_value (sig->generic_param_count, p, &p);
encode_value (sig->param_count, p, &p);
encode_type (acfg, sig->ret, p, &p);
for (i = 0; i < sig->param_count; ++i) {
if (sig->sentinelpos == i) {
*p = MONO_TYPE_SENTINEL;
++p;
}
encode_type (acfg, sig->params [i], p, &p);
}
*endbuf = p;
}
#define MAX_IMAGE_INDEX 250
static void
encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
{
guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
guint32 token = method->token;
MonoJumpInfoToken *ji;
guint8 *p = buf;
/*
* The encoding for most methods is as follows:
* - image index encoded as a leb128
* - token index encoded as a leb128
* Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
* types of method encodings.
*/
/* Mark methods which can't use aot trampolines because they need the further
* processing in mono_magic_trampoline () which requires a MonoMethod*.
*/
if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
if (method->wrapper_type) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
encode_value (method->wrapper_type, p, &p);
switch (method->wrapper_type) {
case MONO_WRAPPER_ALLOC: {
/* The GC name is saved once in MonoAotFileInfo */
g_assert (info->d.alloc.alloc_type != -1);
encode_value (info->d.alloc.alloc_type, p, &p);
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
g_assert (info);
break;
}
case MONO_WRAPPER_STELEMREF: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
encode_value (info->d.virtual_stelemref.kind, p, &p);
break;
}
case MONO_WRAPPER_OTHER: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
encode_klass_ref (acfg, method->klass, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
encode_signature (acfg, info->d.interp_in.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
encode_value (info->d.icall.jit_icall_id, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
encode_value (info->d.aot_init.subtype, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_LLVM_FUNC)
encode_value (info->d.llvm_func.subtype, p, &p);
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
encode_value (info->d.icall.jit_icall_id, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_INDIRECT) {
encode_klass_ref (acfg, info->d.native_func.klass, p, &p);
encode_signature (acfg, info->d.native_func.sig, p, &p);
} else {
g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m;
m = mono_marshal_method_from_wrapper (method);
g_assert (m);
g_assert (m != method);
encode_method_ref (acfg, m, p, &p);
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
encode_value (info->d.element_addr.rank, p, &p);
encode_value (info->d.element_addr.elem_size, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
} else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
encode_klass_ref (acfg, info->d.generic_array_helper.klass, p, &p);
encode_method_ref (acfg, info->d.generic_array_helper.method, p, &p);
int len = strlen (info->d.generic_array_helper.name);
guint32 idx = add_to_blob (acfg, (guint8*)info->d.generic_array_helper.name, len + 1);
encode_value (idx, p, &p);
} else {
g_assert_not_reached ();
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
g_assert (info);
encode_value (info->subtype, p, &p);
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
g_assert (info);
encode_value (info->subtype, p, &p);
if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
if (method->is_inflated) {
/* These wrappers are identified by their class */
encode_value (1, p, &p);
encode_klass_ref (acfg, method->klass, p, &p);
} else {
MonoMethodSignature *sig = mono_method_signature_internal (method);
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
encode_value (0, p, &p);
if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
encode_value (info ? info->subtype : 0, p, &p);
encode_signature (acfg, sig, p, &p);
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
g_assert (info);
encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
MonoClass *klass = info->d.native_to_managed.klass;
if (!klass) {
encode_value (0, p, &p);
} else {
encode_value (1, p, &p);
encode_klass_ref (acfg, klass, p, &p);
}
break;
}
default:
g_assert_not_reached ();
}
} else if (mono_method_signature_internal (method)->is_inflated) {
/*
* This is a generic method, find the original token which referenced it and
* encode that.
* Obtain the token from information recorded by the JIT.
*/
ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
if (ji) {
image_index = get_image_index (acfg, ji->image);
g_assert (image_index < MAX_IMAGE_INDEX);
token = ji->token;
encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (token, p, &p);
} else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
/* Already emitted as part of an rgctx fetch */
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
offset --;
encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
encode_value (offset, p, &p);
} else {
MonoMethod *declaring;
MonoGenericContext *context = mono_method_get_context (method);
g_assert (method->is_inflated);
declaring = ((MonoMethodInflated*)method)->declaring;
/*
* This might be a non-generic method of a generic instance, which
* doesn't have a token since the reference is generated by the JIT
* like Nullable:Box/Unbox, or by generic sharing.
*/
encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
/* Encode the klass */
encode_klass_ref (acfg, method->klass, p, &p);
/* Encode the method */
image_index = get_image_index (acfg, m_class_get_image (method->klass));
g_assert (image_index < MAX_IMAGE_INDEX);
g_assert (declaring->token);
token = declaring->token;
g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
encode_value (image_index, p, &p);
encode_value (mono_metadata_token_index (token), p, &p);
encode_generic_context (acfg, context, p, &p);
}
} else if (token == 0) {
/* This might be a method of a constructed type like int[,].Set */
/* Obtain the token from information recorded by the JIT */
ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
if (ji) {
image_index = get_image_index (acfg, ji->image);
g_assert (image_index < MAX_IMAGE_INDEX);
token = ji->token;
encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (token, p, &p);
} else {
/* Array methods */
g_assert (m_class_get_rank (method->klass));
/* Encode directly */
encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
encode_klass_ref (acfg, method->klass, p, &p);
if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
encode_value (0, p, &p);
else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
encode_value (1, p, &p);
else if (!strcmp (method->name, "Get"))
encode_value (2, p, &p);
else if (!strcmp (method->name, "Address"))
encode_value (3, p, &p);
else if (!strcmp (method->name, "Set"))
encode_value (4, p, &p);
else
g_assert_not_reached ();
}
} else {
g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
if (image_index >= MONO_AOT_METHODREF_MIN) {
encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
encode_value (image_index, p, &p);
encode_value (mono_metadata_token_index (token), p, &p);
} else {
encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
}
}
acfg->stats.method_ref_count++;
acfg->stats.method_ref_size += p - buf;
*endbuf = p;
}
static guint32
get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
{
guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
if (!offset) {
guint8 *buf2, *p2;
buf2 = (guint8 *)g_malloc (1024);
p2 = buf2;
encode_method_ref (acfg, method, p2, &p2);
g_assert (p2 - buf2 < 1024);
offset = add_to_blob (acfg, buf2, p2 - buf2);
g_free (buf2);
g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
} else {
offset --;
}
return offset;
}
static gint
compare_patches (gconstpointer a, gconstpointer b)
{
int i, j;
i = (*(MonoJumpInfo**)a)->ip.i;
j = (*(MonoJumpInfo**)b)->ip.i;
if (i < j)
return -1;
else
if (i > j)
return 1;
else
return 0;
}
static G_GNUC_UNUSED char*
patch_to_string (MonoJumpInfo *patch_info)
{
GString *str;
str = g_string_new ("");
g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
switch (patch_info->type) {
case MONO_PATCH_INFO_VTABLE:
mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
break;
default:
break;
}
g_string_append_printf (str, ")");
return g_string_free (str, FALSE);
}
/*
* is_plt_patch:
*
* Return whenever PATCH_INFO refers to a direct call, and thus requires a
* PLT entry.
*/
static gboolean
is_plt_patch (MonoJumpInfo *patch_info)
{
switch (patch_info->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return TRUE;
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
default:
return FALSE;
}
}
/*
* get_plt_symbol:
*
* Return the symbol identifying the plt entry PLT_OFFSET.
*/
static char*
get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
{
#ifdef TARGET_MACH
/*
* The Apple linker reorganizes object files, so it doesn't like branches to local
* labels, since those have no relocations.
*/
return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
#else
return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
#endif
}
/*
* get_plt_entry:
*
* Return a PLT entry which belongs to the method identified by PATCH_INFO.
*/
static MonoPltEntry*
get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
{
MonoPltEntry *res;
gboolean synchronized = FALSE;
static int synchronized_symbol_idx;
if (!is_plt_patch (patch_info))
return NULL;
if (!acfg->patch_to_plt_entry [patch_info->type])
acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
/*
* Allocate a separate PLT slot for each such patch, since some plt
* entries will refer to the method itself, and some will refer to the
* wrapper.
*/
res = NULL;
synchronized = TRUE;
}
if (!res) {
MonoJumpInfo *new_ji;
new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
res->plt_offset = acfg->plt_offset;
res->ji = new_ji;
res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
if (acfg->aot_opts.write_symbols)
res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
if (synchronized) {
/* Avoid duplicate symbols because we don't cache */
res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
if (res->debug_sym)
res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
synchronized_symbol_idx ++;
}
if (res->debug_sym)
res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
else
res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
/* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
char *tmp = res->llvm_symbol;
res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
g_free (tmp);
}
g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
//g_assert (mono_patch_info_equal (patch_info, new_ji));
//mono_print_ji (patch_info); printf ("\n");
//g_hash_table_print_stats (acfg->patch_to_plt_entry);
acfg->plt_offset ++;
}
return res;
}
static guint32
lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
{
guint32 got_offset;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
if (got_offset)
return got_offset - 1;
g_assert_not_reached ();
}
/**
* get_got_offset:
*
* Returns the offset of the GOT slot where the runtime object resulting from resolving
* JI could be found if it exists, otherwise allocates a new one.
*/
static guint32
get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
{
guint32 got_offset;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
if (got_offset)
return got_offset - 1;
if (llvm) {
got_offset = acfg->llvm_got_offset;
acfg->llvm_got_offset ++;
} else {
got_offset = acfg->got_offset;
acfg->got_offset ++;
}
acfg->stats.got_slots ++;
acfg->stats.got_slot_types [ji->type] ++;
g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
g_ptr_array_add (info->got_patches, ji);
return got_offset;
}
/* Add a method to the list of methods which need to be emitted */
static void
add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
{
g_assert (method);
if (!g_hash_table_lookup (acfg->method_indexes, method)) {
g_ptr_array_add (acfg->methods, method);
g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
acfg->nmethods = acfg->methods->len + 1;
while (acfg->nmethods >= acfg->cfgs_size) {
MonoCompile **new_cfgs;
int new_size;
new_size = acfg->cfgs_size ? acfg->cfgs_size * 2 : 128;
new_cfgs = g_new0 (MonoCompile*, new_size);
memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
g_free (acfg->cfgs);
acfg->cfgs = new_cfgs;
acfg->cfgs_size = new_size;
}
}
if (method->wrapper_type || extra) {
int token = mono_metadata_token_index (method->token) - 1;
if (token < 0)
acfg->nextra_methods++;
g_ptr_array_add (acfg->extra_methods, method);
}
}
static gboolean
prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
{
/* One instantiation with valuetypes is generated for each async method */
if (m_class_get_image (method->klass) == mono_defaults.corlib && (!strcmp (m_class_get_name (method->klass), "AsyncMethodBuilderCore") || !strcmp (m_class_get_name (method->klass), "AsyncVoidMethodBuilder")))
return TRUE;
else
return FALSE;
}
static guint32
get_method_index (MonoAotCompile *acfg, MonoMethod *method)
{
int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
g_assert (index);
return index - 1;
}
static int
add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
{
int index;
index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
if (index)
return index - 1;
index = acfg->method_index;
add_method_with_index (acfg, method, index, extra);
g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
acfg->method_index ++;
return index;
}
static int
add_method (MonoAotCompile *acfg, MonoMethod *method)
{
return add_method_full (acfg, method, FALSE, 0);
}
static void
mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
{
g_assert (acfg->dedup_stats);
char *name = mono_aot_get_mangled_method_name (method);
g_assert (name);
// For stats
char *stats_name = g_strdup (name);
g_assert (acfg->dedup_cache);
if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
// This AOTCompile owns this method
// We do this to decide whether to write it to disk
// during a dedup run (first phase, where we skip).
//
// If never changed, then maybe can avoid a recompile
// of the cache.
//
// Files not read in during last phase.
acfg->dedup_cache_changed = TRUE;
// owns name
g_hash_table_insert (acfg->dedup_cache, name, method);
} else {
// owns name
g_free (name);
}
guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
count++;
g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
}
static void
add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
{
ERROR_DECL (error);
if (method->is_generic && acfg->aot_opts.profile_only) {
// Add the fully shared version to its home image
// This has already been added just need to add it to profile_methods so its not skipped
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
g_hash_table_insert (acfg->profile_methods, method, method);
return;
}
if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
MonoMethod *orig = method;
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
if (!is_ok (error)) {
/* vtype constraint */
mono_error_cleanup (error);
return;
}
/* Add it to profile_methods so its not skipped later */
if (acfg->aot_opts.profile_only && g_hash_table_lookup (acfg->profile_methods, orig))
g_hash_table_insert (acfg->profile_methods, method, method);
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
/* Use the gsharedvt version */
method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
}
if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
mono_dedup_cache_method (acfg, method);
if (!acfg->dedup_emit_mode)
return;
}
if (acfg->aot_opts.log_generics)
aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
add_method_full (acfg, method, TRUE, depth);
}
static void
add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
{
add_extra_method_with_depth (acfg, method, 0);
}
static void
add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
{
if (!callinfo->sig)
return;
g_assert (callinfo->name && callinfo->func);
add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
}
#if ENABLE_LLVM
static void
add_lazy_init_wrappers (MonoAotCompile *acfg)
{
for (int i = 0; i < AOT_INIT_METHOD_NUM; ++i)
add_method (acfg, mono_marshal_get_aot_init_wrapper ((MonoAotInitSubtype)i));
}
#endif
static MonoMethod*
get_runtime_invoke_sig (MonoMethodSignature *sig)
{
MonoMethodBuilder *mb;
MonoMethod *m;
mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
m = mono_mb_create_method (mb, sig, 16);
MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
mono_mb_free (mb);
return invoke;
}
static MonoMethod*
get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
{
return mono_marshal_get_runtime_invoke (method, virtual_);
}
static gboolean
can_marshal_struct (MonoClass *klass)
{
MonoClassField *field;
gboolean can_marshal = TRUE;
gpointer iter = NULL;
MonoMarshalType *info;
int i;
if (mono_class_is_auto_layout (klass))
return FALSE;
info = mono_marshal_load_type_info (klass);
/* Only allow a few field types to avoid asserts in the marshalling code */
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
switch (field->type->type) {
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
break;
case MONO_TYPE_VALUETYPE:
if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
can_marshal = FALSE;
break;
case MONO_TYPE_SZARRAY: {
gboolean has_mspec = FALSE;
if (info) {
for (i = 0; i < info->num_fields; ++i) {
if (info->fields [i].field == field && info->fields [i].mspec)
has_mspec = TRUE;
}
}
if (!has_mspec)
can_marshal = FALSE;
break;
}
default:
can_marshal = FALSE;
break;
}
}
/* Special cases */
/* Its hard to compute whenever these can be marshalled or not */
if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
return TRUE;
return can_marshal;
}
static void
create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
{
/* Create a vtype instantiation */
MonoGenericContext shared_context;
MonoType **args;
MonoGenericInst *inst;
MonoGenericContainer *container;
MonoClass **constraints;
int i;
memset (ctx, 0, sizeof (MonoGenericContext));
if (mono_class_is_gtd (method->klass)) {
shared_context = mono_class_get_generic_container (method->klass)->context;
inst = shared_context.class_inst;
args = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
args [i] = mono_get_int_type ();
}
ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
}
if (method->is_generic) {
container = mono_method_get_generic_container (method);
g_assert (!container->is_anonymous && container->is_method);
shared_context = container->context;
inst = shared_context.method_inst;
args = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < container->type_argc; ++i) {
MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
gboolean ref_only = FALSE;
if (info && info->constraints) {
constraints = info->constraints;
while (*constraints) {
MonoClass *cklass = *constraints;
if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
/* Inflaring the method with our vtype would not be valid */
ref_only = TRUE;
constraints ++;
}
}
if (ref_only)
args [i] = mono_get_object_type ();
else
args [i] = mono_get_int_type ();
}
ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
}
}
static void
add_gc_wrappers (MonoAotCompile *acfg)
{
MonoMethod *m;
/* Managed Allocators */
int nallocators = mono_gc_get_managed_allocator_types ();
for (int i = 0; i < nallocators; ++i) {
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
add_method (acfg, m);
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
add_method (acfg, m);
if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
add_method (acfg, m);
}
/* write barriers */
if (mono_gc_is_moving ()) {
add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
}
}
static gboolean
contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
{
for (int i = 0; i < cattr->num_attrs; ++i) {
MonoCustomAttrEntry *attr = &cattr->attrs [i];
if (!attr->ctor)
return FALSE;
if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
return FALSE;
if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
return FALSE;
}
return TRUE;
}
gboolean
mono_aot_can_specialize (MonoMethod *method)
{
if (!method)
return FALSE;
if (method->wrapper_type != MONO_WRAPPER_NONE)
return FALSE;
// If it's not private, we can't specialize
if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
return FALSE;
// If it has the attribute disabling the specialization, we can't specialize
//
// Set by linker, indicates that the method can be found through reflection
// and that call-site specialization shouldn't be done.
//
// Important that this attribute is used for *nothing else*
//
// If future authors make use of it (to disable more optimizations),
// change this place to use a new attribute.
ERROR_DECL (cattr_error);
MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
if (!is_ok (cattr_error)) {
mono_error_cleanup (cattr_error);
goto cleanup_false;
} else if (cattr && contains_disable_reflection_attribute (cattr)) {
goto cleanup_true;
}
cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
if (!is_ok (cattr_error)) {
mono_error_cleanup (cattr_error);
goto cleanup_false;
} else if (cattr && contains_disable_reflection_attribute (cattr)) {
goto cleanup_true;
} else {
goto cleanup_false;
}
cleanup_false:
if (cattr)
mono_custom_attrs_free (cattr);
return FALSE;
cleanup_true:
if (cattr)
mono_custom_attrs_free (cattr);
return TRUE;
}
static gboolean
always_aot (MonoMethod *method)
{
/*
* Calls to these methods do not go through the normal call processing code so
* calling code cannot enter the interpreter. So always aot them even in profile guided aot mode.
*/
if (method->klass == mono_get_string_class () && (strstr (method->name, "memcpy") || strstr (method->name, "bzero")))
return TRUE;
if (method->string_ctor)
return TRUE;
return FALSE;
}
gboolean
mono_aot_can_enter_interp (MonoMethod *method)
{
MonoAotCompile *acfg = current_acfg;
g_assert (acfg);
if (always_aot (method))
return FALSE;
if (acfg->aot_opts.profile_only && !g_hash_table_lookup (acfg->profile_methods, method))
return TRUE;
return FALSE;
}
static void
add_wrappers (MonoAotCompile *acfg)
{
MonoMethod *method, *m;
int i, j;
MonoMethodSignature *sig, *csig;
guint32 token;
/*
* FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
* so there is only one wrapper of a given type, or inlining their contents into their
* callers.
*/
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
gboolean skip = FALSE;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT))
skip = TRUE;
/* Skip methods which can not be handled by get_runtime_invoke () */
sig = mono_method_signature_internal (method);
if (!sig)
continue;
if ((sig->ret->type == MONO_TYPE_PTR) ||
(sig->ret->type == MONO_TYPE_TYPEDBYREF))
skip = TRUE;
if (mono_class_is_open_constructed_type (sig->ret) || m_class_is_byreflike (mono_class_from_mono_type_internal (sig->ret)))
skip = TRUE;
for (j = 0; j < sig->param_count; j++) {
if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
skip = TRUE;
if (mono_class_is_open_constructed_type (sig->params [j]))
skip = TRUE;
}
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
{
MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
gboolean has_nullable = FALSE;
for (j = 0; j < sig->param_count; j++) {
if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
has_nullable = TRUE;
}
if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
/* Supported by the dynamic runtime-invoke wrapper */
skip = TRUE;
}
if (info)
mono_arch_dyn_call_free (info);
}
#endif
if (acfg->aot_opts.llvm_only)
/* Supported by the gsharedvt based runtime-invoke wrapper */
skip = TRUE;
if (!skip) {
//printf ("%s\n", mono_method_full_name (method, TRUE));
add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
}
}
if (mono_is_corlib_image (acfg->image->assembly->image)) {
/* Runtime invoke wrappers */
MonoType *void_type = mono_get_void_type ();
MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
/* void runtime-invoke () [.cctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->ret = void_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke () [Finalize] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->hasthis = 1;
csig->ret = void_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string, string) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
csig->params [1] = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* string runtime-invoke () [Exception.ToString ()] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
csig->hasthis = 1;
csig->ret = string_type;
add_method (acfg, get_runtime_invoke_sig (csig));
/* void runtime-invoke (string, Exception) [exception ctor] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
csig->hasthis = 1;
csig->ret = void_type;
csig->params [0] = string_type;
csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
add_method (acfg, get_runtime_invoke_sig (csig));
/* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
csig->hasthis = 1;
csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
csig->params [0] = string_type;
csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
add_method (acfg, get_runtime_invoke_sig (csig));
/* runtime-invoke used by finalizers */
add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
/* This is used by mono_runtime_capture_context () */
method = mono_get_context_capture_method ();
if (method)
add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (!acfg->aot_opts.llvm_only)
add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
#endif
/* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
if (acfg->aot_opts.llvm_only) {
int variants;
/* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
for (variants = 0; variants < 4; ++variants) {
for (i = 0; i < 40; ++i) {
sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
g_free (sig);
}
}
}
/* stelemref */
add_method (acfg, mono_marshal_get_stelemref ());
add_gc_wrappers (acfg);
/* Stelemref wrappers */
{
MonoMethod **wrappers;
int nwrappers;
wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
for (i = 0; i < nwrappers; ++i)
add_method (acfg, wrappers [i]);
g_free (wrappers);
}
/* castclass_with_check wrapper */
add_method (acfg, mono_marshal_get_castclass_with_cache ());
/* isinst_with_check wrapper */
add_method (acfg, mono_marshal_get_isinst_with_cache ());
/* JIT icall wrappers */
/* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
if (acfg->aot_opts.llvm_only) {
/* String ctors are called directly on llvmonly */
for (int i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (method && method->string_ctor) {
MonoMethod *w = get_runtime_invoke (acfg, method, FALSE);
add_method (acfg, w);
}
}
}
}
/*
* remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
* we use the original method instead at runtime.
* Since full-aot doesn't support remoting, this is not a problem.
*/
#if 0
/* remoting-invoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethodSignature *sig;
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
sig = mono_method_signature_internal (method);
if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
m = mono_marshal_get_remoting_invoke_with_check (method);
add_method (acfg, m);
}
}
#endif
/* delegate-invoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
continue;
if (!mono_class_is_gtd (klass)) {
method = mono_get_delegate_invoke_internal (klass);
m = mono_marshal_get_delegate_invoke (method, NULL);
add_method (acfg, m);
method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
if (method)
add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
if (method)
add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
MonoCustomAttrInfo *cattr;
cattr = mono_custom_attrs_from_class_checked (klass, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
g_assert (!cattr);
continue;
}
if (cattr) {
int j;
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && (!strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoNativeFunctionWrapperAttribute") || !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedFunctionPointerAttribute")))
break;
if (j < cattr->num_attrs) {
MonoMethod *invoke;
MonoMethod *wrapper;
MonoMethod *del_invoke;
/* Add wrappers needed by mono_ftnptr_to_delegate () */
invoke = mono_get_delegate_invoke_internal (klass);
wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
add_method (acfg, wrapper);
add_method (acfg, del_invoke);
}
mono_custom_attrs_free (cattr);
}
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *inst, *gshared;
/*
* Emit gsharedvt versions of the generic delegate-invoke wrappers
*/
/* Invoke */
method = mono_get_delegate_invoke_internal (klass);
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_invoke (inst, NULL);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
/* begin-invoke */
method = mono_get_delegate_begin_invoke_internal (klass);
if (method) {
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_begin_invoke (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
/* end-invoke */
method = mono_get_delegate_end_invoke_internal (klass);
if (method) {
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_delegate_end_invoke (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
}
}
/* array access wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_SPEC | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
MonoMethod *m, *wrapper;
/* Add runtime-invoke wrappers too */
m = get_method_nofail (klass, "Get", -1, 0);
g_assert (m);
wrapper = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, wrapper);
if (!acfg->aot_opts.llvm_only)
add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
m = get_method_nofail (klass, "Set", -1, 0);
g_assert (m);
wrapper = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, wrapper);
if (!acfg->aot_opts.llvm_only)
add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
}
}
/* Synchronized wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
if (method->is_generic) {
// FIXME:
} else if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *inst, *gshared, *m;
/*
* Create a generic wrapper for a generic instance, and AOT that.
*/
create_gsharedvt_inst (acfg, method, &ctx);
inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
m = mono_marshal_get_synchronized_wrapper (inst);
g_assert (m->is_inflated);
gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_method (acfg, gshared);
} else {
add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
}
}
}
/* pinvoke wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
}
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (acfg->aot_opts.llvm_only) {
/* The wrappers have a different signature (hasthis is not set) so need to add this too */
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
}
}
}
/* native-to-managed wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
MonoCustomAttrInfo *cattr;
int j;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
/*
* Only generate native-to-managed wrappers for methods which have an
* attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
* name to avoid defining a new assembly to contain it.
*/
cattr = mono_custom_attrs_from_method_checked (method, error);
if (!is_ok (error)) {
char *name = mono_method_get_full_name (method);
report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
g_free (name);
}
if (cattr) {
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
const char *p = (const char*)e->data;
const char *named;
int slen, num_named, named_type;
char *n;
MonoType *t;
MonoClass *klass;
char *export_name = NULL;
MonoMethod *wrapper;
/* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See https://docs.microsoft.com/xamarin/ios/internals/limitations#reverse-callbacks",
mono_method_full_name (method, TRUE));
exit (1);
}
g_assert (sig->param_count == 1);
g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
/*
* Decode the cattr manually since we can't create objects
* during aot compilation.
*/
/* Skip prolog */
p += 2;
/* From load_cattr_value () in reflection.c */
slen = mono_metadata_decode_value (p, &p);
n = (char *)g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name_checked (n, mono_alc_get_ambient (), acfg->image, error);
g_assert (t);
mono_error_assert_ok (error);
g_free (n);
klass = mono_class_from_mono_type_internal (t);
g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
p += slen;
num_named = read16 (p);
p += 2;
g_assert (num_named < 2);
if (num_named == 1) {
int name_len;
char *name;
/* parse ExportSymbol attribute */
named = p;
named_type = *named;
named += 1;
/* data_type = *named; */
named += 1;
name_len = mono_metadata_decode_blob_size (named, &named);
name = (char *)g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
g_assert (named_type == 0x54);
g_assert (!strcmp (name, "ExportSymbol"));
/* load_cattr_value (), string case */
MONO_DISABLE_WARNING (4310) // cast truncates constant value
g_assert (*named != (char)0xFF);
MONO_RESTORE_WARNING
slen = mono_metadata_decode_value (named, &named);
export_name = (char *)g_malloc (slen + 1);
memcpy (export_name, named, slen);
export_name [slen] = 0;
named += slen;
}
wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
mono_error_assert_ok (error);
add_method (acfg, wrapper);
if (export_name)
g_hash_table_insert (acfg->export_names, wrapper, export_name);
}
for (j = 0; j < cattr->num_attrs; ++j)
if (cattr->attrs [j].ctor && mono_is_corlib_image (m_class_get_image (cattr->attrs [j].ctor->klass)) && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedCallersOnlyAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
const char *named;
int slen;
char *export_name = NULL;
MonoMethod *wrapper;
if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [UnmanagedCallers].",
mono_method_full_name (method, TRUE));
exit (1);
}
gpointer *typed_args = NULL;
gpointer *named_args = NULL;
CattrNamedArg *named_arg_info = NULL;
int num_named_args = 0;
mono_reflection_create_custom_attr_data_args_noalloc (acfg->image, e->ctor, e->data, e->data_size, &typed_args, &named_args, &num_named_args, &named_arg_info, error);
mono_error_assert_ok (error);
for (j = 0; j < num_named_args; ++j) {
if (named_arg_info [j].field && !strcmp (named_arg_info [j].field->name, "EntryPoint")) {
named = named_args [j];
slen = mono_metadata_decode_value (named, &named);
export_name = (char *)g_malloc (slen + 1);
memcpy (export_name, named, slen);
export_name [slen] = 0;
}
}
g_free (named_args);
g_free (named_arg_info);
wrapper = mono_marshal_get_managed_wrapper (method, NULL, 0, error);
mono_error_assert_ok (error);
add_method (acfg, wrapper);
if (export_name)
g_hash_table_insert (acfg->export_names, wrapper, export_name);
}
g_free (cattr);
}
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
}
}
/* StructureToPtr/PtrToStructure wrappers */
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
!(m_class_get_nested_in (klass) && strstr (m_class_get_name (m_class_get_nested_in (klass)), "<PrivateImplementationDetails>") == m_class_get_name (m_class_get_nested_in (klass)))) {
add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
}
}
}
static gboolean
has_type_vars (MonoClass *klass)
{
if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
return TRUE;
if (m_class_get_rank (klass))
return has_type_vars (m_class_get_element_class (klass));
if (mono_class_is_ginst (klass)) {
MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
if (context->class_inst) {
int i;
for (i = 0; i < context->class_inst->type_argc; ++i)
if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
return TRUE;
}
}
if (mono_class_is_gtd (klass))
return TRUE;
return FALSE;
}
static gboolean
is_vt_inst (MonoGenericInst *inst)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
return TRUE;
}
return FALSE;
}
static gboolean
is_vt_inst_no_enum (MonoGenericInst *inst)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t))
return TRUE;
}
return FALSE;
}
static gboolean
method_has_type_vars (MonoMethod *method)
{
if (has_type_vars (method->klass))
return TRUE;
if (method->is_inflated) {
MonoGenericContext *context = mono_method_get_context (method);
if (context->method_inst) {
int i;
for (i = 0; i < context->method_inst->type_argc; ++i)
if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
return TRUE;
}
}
return FALSE;
}
static
gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
{
return opts->mode == MONO_AOT_MODE_FULL;
}
static
gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
{
return opts->interp;
}
static
gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
{
return opts->mode == MONO_AOT_MODE_HYBRID;
}
static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
static void
add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
{
/* This might lead to a huge code blowup so only do it if neccesary */
if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
return;
add_generic_class_with_depth (acfg, klass, 0, ref);
}
static gboolean
check_type_depth (MonoType *t, int depth)
{
int i;
if (depth > 8)
return TRUE;
switch (t->type) {
case MONO_TYPE_GENERICINST: {
MonoGenericClass *gklass = t->data.generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
if (ginst) {
for (i = 0; i < ginst->type_argc; ++i) {
if (check_type_depth (ginst->type_argv [i], depth + 1))
return TRUE;
}
}
break;
}
default:
break;
}
return FALSE;
}
static void
add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
static gboolean
inst_has_vtypes (MonoGenericInst *inst)
{
for (int i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if (MONO_TYPE_ISSTRUCT (t))
return TRUE;
}
return FALSE;
}
/*
* add_generic_class:
*
* Add all methods of a generic class.
*/
static void
add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
{
MonoMethod *method;
MonoClassField *field;
gpointer iter;
gboolean use_gsharedvt = FALSE;
gboolean use_gsharedvt_for_array = FALSE;
if (!acfg->ginst_hash)
acfg->ginst_hash = g_hash_table_new (NULL, NULL);
mono_class_init_internal (klass);
if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
return;
if (has_type_vars (klass))
return;
if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
return;
if (mono_class_has_failure (klass))
return;
if (!acfg->ginst_hash)
acfg->ginst_hash = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (acfg->ginst_hash, klass))
return;
if (check_type_depth (m_class_get_byval_arg (klass), 0))
return;
if (acfg->aot_opts.log_generics) {
char *s = mono_type_full_name (m_class_get_byval_arg (klass));
aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
g_free (s);
}
g_hash_table_insert (acfg->ginst_hash, klass, klass);
/*
* Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
* Enable this only for some classes since gsharedvt might not support all methods.
*/
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && m_class_get_image (klass) == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
(!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
use_gsharedvt = TRUE;
#ifdef TARGET_WASM
/*
* Use gsharedvt for instances with vtype arguments.
* WASM only since other platforms depend on the
* previous behavior.
*/
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst_no_enum (mono_class_get_generic_class (klass)->context.class_inst)) {
use_gsharedvt = TRUE;
use_gsharedvt_for_array = TRUE;
}
#endif
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if ((acfg->jit_opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
/*
* This is partial sharing, and we can't handle it yet
*/
continue;
}
if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
/* Already added */
add_types_from_method_header (acfg, method);
continue;
}
if (method->is_generic)
/* FIXME: */
continue;
/*
* FIXME: Instances which are referenced by these methods are not added,
* for example Array.Resize<int> for List<int>.Add ().
*/
add_extra_method_with_depth (acfg, method, depth + 1);
}
iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
if (field->type->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
}
if (m_class_is_delegate (klass)) {
method = mono_get_delegate_invoke_internal (klass);
method = mono_marshal_get_delegate_invoke (method, NULL);
if (acfg->aot_opts.log_generics)
aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
add_method (acfg, method);
}
/* Add superclasses */
if (m_class_get_parent (klass))
add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
const char *klass_name = m_class_get_name (klass);
const char *klass_name_space = m_class_get_name_space (klass);
const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
/*
* For ICollection<T>, add instances of the helper methods
* in Array, since a T[] could be cast to ICollection<T>.
*/
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
(!strcmp(klass_name, "ICollection`1") || !strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IList`1") || !strcmp (klass_name, "IEnumerator`1") || !strcmp (klass_name, "IReadOnlyList`1"))) {
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
gpointer iter;
char *name_prefix;
if (!strcmp (klass_name, "IEnumerator`1"))
name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
else
name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
iter = NULL;
while ((method = mono_class_get_methods (array_class, &iter))) {
if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, use_gsharedvt_for_array))
add_extra_method_with_depth (acfg, m, depth);
}
}
g_free (name_prefix);
}
/* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
ERROR_DECL (error);
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *icomparable, *gcomparer, *icomparable_inst;
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
MonoClass *gcomparer_inst;
gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
}
}
/* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
ERROR_DECL (error);
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoClass *iface, *gcomparer, *iface_inst;
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
g_assert (iface);
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
MonoClass *gcomparer_inst;
ERROR_DECL (error);
gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
}
}
/* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
MonoClass *enum_comparer;
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoGenericContext ctx;
if (m_class_is_enumtype (tclass)) {
MonoClass *enum_comparer_inst;
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
}
}
/* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
MonoClass *comparer;
MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
MonoGenericContext ctx;
if (m_class_is_enumtype (tclass)) {
MonoClass *comparer_inst;
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (tclass) };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
}
}
}
static void
add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
{
int i;
MonoGenericContext ctx;
if (acfg->aot_opts.no_instances)
return;
memset (&ctx, 0, sizeof (ctx));
for (i = 0; i < ninsts; ++i) {
ERROR_DECL (error);
MonoClass *generic_inst;
MonoType *args [ ] = { insts [i] };
ctx.class_inst = mono_metadata_get_generic_inst (1, args);
generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
add_generic_class (acfg, generic_inst, force, "");
}
}
static void
add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
{
ERROR_DECL (error);
MonoMethodHeader *header;
MonoMethodSignature *sig;
int j, depth;
depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
sig = mono_method_signature_internal (method);
if (sig) {
for (j = 0; j < sig->param_count; ++j)
if (sig->params [j]->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
}
header = mono_method_get_header_checked (method, error);
if (header) {
for (j = 0; j < header->num_locals; ++j)
if (header->locals [j]->type == MONO_TYPE_GENERICINST)
add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
mono_metadata_free_mh (header);
} else {
mono_error_cleanup (error); /* FIXME report the error */
}
}
/*
* add_generic_instances:
*
* Add instances referenced by the METHODSPEC/TYPESPEC table.
*/
static void
add_generic_instances (MonoAotCompile *acfg)
{
int i;
guint32 token;
MonoMethod *method;
MonoGenericContext *context;
if (acfg->aot_opts.no_instances)
return;
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHODSPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_METHOD_SPEC | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (!method) {
aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
continue;
}
if (m_class_get_image (method->klass) != acfg->image)
continue;
context = mono_method_get_context (method);
if (context && ((context->class_inst && context->class_inst->is_open)))
continue;
/*
* For open methods, create an instantiation which can be passed to the JIT.
* FIXME: Handle class_inst as well.
*/
if (context && context->method_inst && context->method_inst->is_open) {
ERROR_DECL (error);
MonoGenericContext shared_context;
MonoGenericInst *inst;
MonoType **type_argv;
int i;
MonoMethod *declaring_method;
gboolean supported = TRUE;
/* Check that the context doesn't contain open constructed types */
if (context->class_inst) {
inst = context->class_inst;
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
continue;
if (mono_class_is_open_constructed_type (inst->type_argv [i]))
supported = FALSE;
}
}
if (context->method_inst) {
inst = context->method_inst;
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
continue;
if (mono_class_is_open_constructed_type (inst->type_argv [i]))
supported = FALSE;
}
}
if (!supported)
continue;
memset (&shared_context, 0, sizeof (MonoGenericContext));
inst = context->class_inst;
if (inst) {
type_argv = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
type_argv [i] = mono_get_object_type ();
else
type_argv [i] = inst->type_argv [i];
}
shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
g_free (type_argv);
}
inst = context->method_inst;
if (inst) {
type_argv = g_new0 (MonoType*, inst->type_argc);
for (i = 0; i < inst->type_argc; ++i) {
if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
type_argv [i] = mono_get_object_type ();
else
type_argv [i] = inst->type_argv [i];
}
shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
g_free (type_argv);
}
if (method->is_generic || mono_class_is_gtd (method->klass))
declaring_method = method;
else
declaring_method = mono_method_get_declaring_generic_method (method);
method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
/*
* If the method is fully sharable, it was already added in place of its
* generic definition.
*/
if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
continue;
/*
* FIXME: Partially shared methods are not shared here, so we end up with
* many identical methods.
*/
add_extra_method (acfg, method);
}
rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPESPEC]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoClass *klass;
token = MONO_TOKEN_TYPE_SPEC | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass || m_class_get_rank (klass)) {
mono_error_cleanup (error);
continue;
}
add_generic_class (acfg, klass, FALSE, "typespec");
}
/* Add types of args/locals */
for (i = 0; i < acfg->methods->len; ++i) {
method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
add_types_from_method_header (acfg, method);
}
if (acfg->image == mono_defaults.corlib) {
MonoClass *klass;
MonoType *insts [256];
int ninsts = 0;
MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
MonoType *int32_type = mono_get_int32_type ();
MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
MonoType *object_type = mono_get_object_type ();
insts [ninsts ++] = byte_type;
insts [ninsts ++] = sbyte_type;
insts [ninsts ++] = int16_type;
insts [ninsts ++] = uint16_type;
insts [ninsts ++] = int32_type;
insts [ninsts ++] = uint32_type;
insts [ninsts ++] = int64_type;
insts [ninsts ++] = uint64_type;
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
/* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
/* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
{
MonoClass *k, *enum_comparer;
MonoType *insts [16];
int ninsts;
const char *enum_names [] = { "I8Enum", "I16Enum", "I32Enum", "I64Enum", "UI8Enum", "UI16Enum", "UI32Enum", "UI64Enum" };
ninsts = 0;
for (int i = 0; i < G_N_ELEMENTS (enum_names); ++i) {
k = mono_class_try_load_from_name (acfg->image, "Mono", enum_names [i]);
g_assert (k);
insts [ninsts ++] = m_class_get_byval_arg (k);
}
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
add_instances_of (acfg, enum_comparer, insts, ninsts, TRUE);
enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumComparer`1");
add_instances_of (acfg, enum_comparer, insts, ninsts, TRUE);
}
/* Add instances of the array generic interfaces for primitive types */
/* This will add instances of the InternalArray_ helper methods in Array too */
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
klass = mono_class_try_load_from_name (acfg->image, "System", "SZGenericArrayEnumerator`1");
if (klass)
add_instances_of (acfg, klass, insts, ninsts, TRUE);
/*
* Add a managed-to-native wrapper of Array.GetGenericValue_icall<object>, which is
* used for all instances of GetGenericValue_icall by the AOT runtime.
*/
{
ERROR_DECL (error);
MonoGenericContext ctx;
MonoMethod *get_method;
MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValue_icall", 3, 0, error);
mono_error_assert_ok (error);
if (get_method) {
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { object_type };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
mono_error_assert_ok (error); /* FIXME don't swallow the error */
}
}
/* object[] accessor wrappers. */
for (i = 1; i < 4; ++i) {
MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
MonoMethod *m;
m = get_method_nofail (obj_array_class, "Get", i, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
m = get_method_nofail (obj_array_class, "Address", i, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
add_extra_method (acfg, m);
}
}
}
static char *
decode_direct_icall_symbol_name_attribute (MonoMethod *method)
{
ERROR_DECL (error);
int j = 0;
char *symbol_name = NULL;
MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
if (is_ok(error) && cattr) {
for (j = 0; j < cattr->num_attrs; j++)
if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
break;
if (j < cattr->num_attrs) {
MonoCustomAttrEntry *e = &cattr->attrs [j];
MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
/*
* Decode the cattr manually since we can't create objects
* during aot compilation.
*/
/* Skip prolog */
const char *p = ((const char*)e->data) + 2;
int slen = mono_metadata_decode_value (p, &p);
symbol_name = (char *)g_memdup (p, slen + 1);
if (symbol_name)
symbol_name [slen] = 0;
}
}
}
return symbol_name;
}
static const char*
lookup_external_icall_symbol_name_aot (MonoMethod *method)
{
g_assert (method_to_external_icall_symbol_name);
gpointer key, value;
if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
return (const char*)value;
char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
return symbol_name;
}
static const char*
lookup_icall_symbol_name_aot (MonoMethod *method)
{
const char * symbol_name = mono_lookup_icall_symbol (method);
if (!symbol_name)
symbol_name = lookup_external_icall_symbol_name_aot (method);
return symbol_name;
}
gboolean
mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
{
gboolean enable_icall = FALSE;
if (cfg->compile_aot)
enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
else
enable_icall = FALSE;
return enable_icall;
}
/*
* method_is_externally_callable:
*
* Return whenever METHOD can be directly called from other AOT images
* without going through a PLT.
*/
static gboolean
method_is_externally_callable (MonoAotCompile *acfg, MonoMethod *method)
{
// FIXME: Unify
if (acfg->aot_opts.llvm_only) {
if (!acfg->aot_opts.static_link)
return FALSE;
if (method->wrapper_type == MONO_WRAPPER_ALLOC)
return TRUE;
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
return TRUE;
if (method->string_ctor)
return FALSE;
if (method->wrapper_type)
return FALSE;
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
return FALSE;
if (method->is_inflated)
return FALSE;
if (!((mono_class_get_flags (method->klass) & TYPE_ATTRIBUTE_PUBLIC) && (method->flags & METHOD_ATTRIBUTE_PUBLIC)))
return FALSE;
/* Can't enable this as the callee might fail llvm compilation */
//return TRUE;
return FALSE;
} else {
if (!acfg->aot_opts.direct_extern_calls)
return FALSE;
if (!acfg->llvm)
return FALSE;
if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)
return FALSE;
if (method->wrapper_type == MONO_WRAPPER_ALLOC)
return FALSE;
if (method->string_ctor)
return FALSE;
if (method->wrapper_type)
return FALSE;
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
return FALSE;
if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
return FALSE;
if (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)
return FALSE;
if (method->is_inflated)
return FALSE;
if (!((mono_class_get_flags (method->klass) & TYPE_ATTRIBUTE_PUBLIC) && (method->flags & METHOD_ATTRIBUTE_PUBLIC)))
return FALSE;
return TRUE;
}
}
/*
* is_direct_callable:
*
* Return whenever the method identified by JI is directly callable without
* going through the PLT.
*/
static gboolean
is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
{
if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
if (callee_cfg) {
gboolean direct_callable = TRUE;
if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
direct_callable = FALSE;
if (direct_callable && !acfg->llvm && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
direct_callable = FALSE;
if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
direct_callable = FALSE;
//
// FIXME: Support inflated methods, it asserts in mini_llvm_init_gshared_method_this () because the method is not in
// amodule->extra_methods.
//
if (direct_callable && callee_cfg->method->is_inflated)
direct_callable = FALSE;
if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
// FIXME: Maybe call the wrapper directly ?
direct_callable = FALSE;
if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
/* Disable this so all calls go through load_method (), see the
* mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
* mono_debugger_agent_init ().
*/
direct_callable = FALSE;
}
if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
/* sgen does some initialization when the allocator method is created */
direct_callable = FALSE;
if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
/* we don't know at compile time whether sgen is concurrent or not */
direct_callable = FALSE;
if (direct_callable)
return TRUE;
}
} else if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) != acfg->image)) {
/* Cross assembly calls */
return method_is_externally_callable (acfg, patch_info->data.method);
} else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
if (acfg->aot_opts.direct_pinvoke)
return TRUE;
} else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
if (acfg->aot_opts.direct_icalls)
return TRUE;
return FALSE;
}
return FALSE;
}
#ifdef MONO_ARCH_AOT_SUPPORTED
static const char *
get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
{
MonoImage *image = m_class_get_image (method->klass);
MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
MonoTableInfo *tables = image->tables;
MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
guint32 im_cols [MONO_IMPLMAP_SIZE];
char *import;
import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
if (import != NULL)
return import;
if (piinfo->implmap_idx == 0 || mono_metadata_table_bounds_check (image, MONO_TABLE_IMPLMAP, piinfo->implmap_idx))
return NULL;
mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
int module_idx = im_cols [MONO_IMPLMAP_SCOPE];
if (module_idx == 0 || mono_metadata_table_bounds_check (image, MONO_TABLE_MODULEREF, module_idx))
return NULL;
import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
return import;
}
#else
static const char *
get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
{
return NULL;
}
#endif
static gint
compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
{
if (a->native_offset == b->native_offset)
return a->il_offset - b->il_offset;
else
return a->native_offset - b->native_offset;
}
/*
* compute_line_numbers:
*
* Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
* entry.
*/
static MonoDebugSourceLocation**
compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
{
MonoDebugMethodInfo *minfo;
MonoDebugLineNumberEntry *ln_array;
MonoDebugSourceLocation *loc;
int i, prev_line, prev_il_offset;
int *native_to_il_offset = NULL;
MonoDebugSourceLocation **res;
gboolean first;
minfo = mono_debug_lookup_method (method);
if (!minfo)
return NULL;
// FIXME: This seems to happen when two methods have the same cfg->method_to_register
if (debug_info->code_size != code_size)
return NULL;
g_assert (code_size);
/* Compute the native->IL offset mapping */
ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
mono_qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
native_to_il_offset = g_new0 (int, code_size + 1);
for (i = 0; i < debug_info->num_line_numbers; ++i) {
int j;
MonoDebugLineNumberEntry *lne = &ln_array [i];
if (i == 0) {
for (j = 0; j < lne->native_offset; ++j)
native_to_il_offset [j] = -1;
}
if (i < debug_info->num_line_numbers - 1) {
MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
for (j = lne->native_offset; j < lne_next->native_offset; ++j)
native_to_il_offset [j] = lne->il_offset;
} else {
for (j = lne->native_offset; j < code_size; ++j)
native_to_il_offset [j] = lne->il_offset;
}
}
g_free (ln_array);
/* Compute the native->line number mapping */
res = g_new0 (MonoDebugSourceLocation*, code_size);
prev_il_offset = -1;
prev_line = -1;
first = TRUE;
for (i = 0; i < code_size; ++i) {
int il_offset = native_to_il_offset [i];
if (il_offset == -1 || il_offset == prev_il_offset)
continue;
prev_il_offset = il_offset;
loc = mono_debug_method_lookup_location (minfo, il_offset);
if (!(loc && loc->source_file))
continue;
if (loc->row == prev_line) {
mono_debug_free_source_location (loc);
continue;
}
prev_line = loc->row;
//printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
if (first)
/* This will cover the prolog too */
res [0] = loc;
else
res [i] = loc;
first = FALSE;
}
return res;
}
static int
get_file_index (MonoAotCompile *acfg, const char *source_file)
{
int findex;
// FIXME: Free these
if (!acfg->dwarf_ln_filenames)
acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
if (!findex) {
findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
emit_unset_mode (acfg);
fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
}
return findex;
}
#ifdef TARGET_ARM64
#define INST_LEN 4
#else
#define INST_LEN 1
#endif
static gboolean
never_direct_pinvoke (const char *pinvoke_symbol)
{
#if defined(TARGET_IOS) || defined (TARGET_TVOS) || defined (TARGET_OSX) || defined (TARGET_WATCHOS)
/* XI must be able to override the functions that start with objc_msgSend.
* (there are a few variants with the same prefix) */
return !strncmp (pinvoke_symbol, "objc_msgSend", 12);
#else
return FALSE;
#endif
}
/*
* emit_and_reloc_code:
*
* Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
* is true, calls are made through the GOT too. This is used for emitting trampolines
* in full-aot mode, since calls made from trampolines couldn't go through the PLT,
* since trampolines are needed to make PLT work.
*/
static void
emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
{
int i, pindex, start_index;
GPtrArray *patches;
MonoJumpInfo *patch_info;
MonoDebugSourceLocation **locs = NULL;
gboolean skip, prologue_end = FALSE;
#ifdef MONO_ARCH_AOT_SUPPORTED
gboolean direct_call, external_call;
guint32 got_slot;
const char *direct_call_target = 0;
const char *direct_pinvoke;
#endif
if (acfg->gas_line_numbers && method && debug_info) {
locs = compute_line_numbers (method, code_len, debug_info);
if (!locs) {
int findex = get_file_index (acfg, "<unknown>");
emit_unset_mode (acfg);
fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
}
}
/* Collect and sort relocations */
patches = g_ptr_array_new ();
for (patch_info = relocs; patch_info; patch_info = patch_info->next)
g_ptr_array_add (patches, patch_info);
g_ptr_array_sort (patches, compare_patches);
start_index = 0;
for (i = 0; i < code_len; i += INST_LEN) {
patch_info = NULL;
for (pindex = start_index; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->ip.i >= i)
break;
}
if (locs && locs [i]) {
MonoDebugSourceLocation *loc = locs [i];
int findex;
const char *options;
findex = get_file_index (acfg, loc->source_file);
emit_unset_mode (acfg);
if (!prologue_end)
options = " prologue_end";
else
options = "";
prologue_end = TRUE;
fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
mono_debug_free_source_location (loc);
}
skip = FALSE;
#ifdef MONO_ARCH_AOT_SUPPORTED
if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
start_index = pindex;
switch (patch_info->type) {
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_GOT_OFFSET: {
int code_size;
arch_emit_got_offset (acfg, code + i, &code_size);
i += code_size - INST_LEN;
skip = TRUE;
patch_info->type = MONO_PATCH_INFO_NONE;
break;
}
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
int code_size, index;
char *selector = (char *)patch_info->data.target;
if (!acfg->objc_selector_to_index)
acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
if (!acfg->objc_selectors)
acfg->objc_selectors = g_ptr_array_new ();
index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
if (index)
index --;
else {
index = acfg->objc_selector_index;
g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
acfg->objc_selector_index ++;
}
arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
i += code_size - INST_LEN;
skip = TRUE;
patch_info->type = MONO_PATCH_INFO_NONE;
break;
}
default: {
/*
* If this patch is a call, try emitting a direct call instead of
* through a PLT entry. This is possible if the called method is in
* the same assembly and requires no initialization.
*/
direct_call = FALSE;
external_call = FALSE;
if (patch_info->type == MONO_PATCH_INFO_METHOD) {
MonoMethod *cmethod = patch_info->data.method;
if (cmethod->wrapper_type == MONO_WRAPPER_OTHER && mono_marshal_get_wrapper_info (cmethod)->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
WrapperInfo *info = mono_marshal_get_wrapper_info (cmethod);
/*
* This is a call from a JITted method to the init wrapper emitted by LLVM.
*/
g_assert (acfg->aot_opts.llvm && acfg->aot_opts.direct_extern_calls);
const char *init_name = mono_marshal_get_aot_init_wrapper_name (info->d.aot_init.subtype);
char *symbol = g_strdup_printf ("%s%s_%s", acfg->user_symbol_prefix, acfg->global_prefix, init_name);
direct_call = TRUE;
direct_call_target = symbol;
patch_info->type = MONO_PATCH_INFO_NONE;
} else if ((m_class_get_image (patch_info->data.method->klass) == acfg->image) && !got_only && is_direct_callable (acfg, method, patch_info)) {
MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, cmethod);
// Don't compile inflated methods if we're doing dedup
if (acfg->aot_opts.dedup && !mono_aot_can_dedup (cmethod)) {
char *name = mono_aot_get_mangled_method_name (cmethod);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
g_free (name);
direct_call = TRUE;
direct_call_target = callee_cfg->asm_symbol;
patch_info->type = MONO_PATCH_INFO_NONE;
acfg->stats.direct_calls ++;
}
}
acfg->stats.all_calls ++;
} else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
if (!got_only && is_direct_callable (acfg, method, patch_info)) {
if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
else
direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
if (direct_pinvoke && !never_direct_pinvoke (direct_pinvoke)) {
direct_call = TRUE;
g_assert (strlen (direct_pinvoke) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
}
}
} else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
if (!got_only && sym && acfg->aot_opts.direct_icalls) {
/* Call to a C function implementing a jit icall */
direct_call = TRUE;
external_call = TRUE;
g_assert (strlen (sym) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
}
} else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
const char * const sym = info->c_symbol;
if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
/* Call to a jit icall without a wrapper */
direct_call = TRUE;
external_call = TRUE;
g_assert (strlen (sym) < 1000);
direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
}
}
if (direct_call) {
patch_info->type = MONO_PATCH_INFO_NONE;
acfg->stats.direct_calls ++;
}
if (!got_only && !direct_call) {
MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
if (plt_entry) {
/* This patch has a PLT entry, so we must emit a call to the PLT entry */
direct_call = TRUE;
direct_call_target = plt_entry->symbol;
/* Nullify the patch */
patch_info->type = MONO_PATCH_INFO_NONE;
plt_entry->jit_used = TRUE;
}
}
if (direct_call) {
int call_size;
arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
i += call_size - INST_LEN;
} else {
int code_size;
got_slot = get_got_offset (acfg, FALSE, patch_info);
arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
i += code_size - INST_LEN;
}
skip = TRUE;
}
}
}
#endif /* MONO_ARCH_AOT_SUPPORTED */
if (!skip) {
/* Find next patch */
patch_info = NULL;
for (pindex = start_index; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->ip.i >= i)
break;
}
/* Try to emit multiple bytes at once */
if (pindex < patches->len && patch_info->ip.i > i) {
int limit;
for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
if (locs && locs [limit])
break;
}
emit_code_bytes (acfg, code + i, limit - i);
i = limit - INST_LEN;
} else {
emit_code_bytes (acfg, code + i, INST_LEN);
}
}
}
g_ptr_array_free (patches, TRUE);
g_free (locs);
}
/*
* sanitize_symbol:
*
* Return a modified version of S which only includes characters permissible in symbols.
*/
static char*
sanitize_symbol (MonoAotCompile *acfg, char *s)
{
gboolean process = FALSE;
int i, len;
GString *gs;
char *res;
if (!s)
return s;
len = strlen (s);
for (i = 0; i < len; ++i)
if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
process = TRUE;
if (!process)
return s;
gs = g_string_sized_new (len);
for (i = 0; i < len; ++i) {
guint8 c = s [i];
if (c <= 0x7f && (isalnum (c) || c == '_')) {
g_string_append_c (gs, c);
} else if (c > 0x7f) {
/* multi-byte utf8 */
g_string_append_printf (gs, "_0x%x", c);
i ++;
c = s [i];
while (c >> 6 == 0x2) {
g_string_append_printf (gs, "%x", c);
i ++;
c = s [i];
}
g_string_append_printf (gs, "_");
i --;
} else {
g_string_append_c (gs, '_');
}
}
res = mono_mempool_strdup (acfg->mempool, gs->str);
g_string_free (gs, TRUE);
return res;
}
static char*
get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
{
char *name1, *name2, *cached;
int i, j, len, count;
MonoMethod *cached_method;
name1 = mono_method_full_name (method, TRUE);
#ifdef TARGET_MACH
// This is so that we don't accidentally create a local symbol (which starts with 'L')
if ((!prefix || !*prefix) && name1 [0] == 'L')
prefix = "_";
#endif
#if defined(TARGET_WIN32) && defined(TARGET_X86)
char adjustedPrefix [MAX_SYMBOL_SIZE];
prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
#endif
len = strlen (name1);
name2 = (char *) g_malloc (strlen (prefix) + len + 16);
memcpy (name2, prefix, strlen (prefix));
j = strlen (prefix);
for (i = 0; i < len; ++i) {
if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
name2 [j ++] = '_';
} else if (isalnum (name1 [i])) {
name2 [j ++] = name1 [i];
} else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
i += 2;
} else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
name2 [j ++] = '_';
i++;
} else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
} else
name2 [j ++] = '_';
}
name2 [j] = '\0';
g_free (name1);
count = 0;
while (TRUE) {
cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
if (!(cached_method && cached_method != method))
break;
sprintf (name2 + j, "_%d", count);
count ++;
}
cached = g_strdup (name2);
g_hash_table_insert (cache, cached, method);
return name2;
}
static void
emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
{
MonoMethod *method;
int method_index;
guint8 *code;
char *debug_sym = NULL;
char *symbol = NULL;
int func_alignment = AOT_FUNC_ALIGNMENT;
char *export_name;
g_assert (!ignore_cfg (cfg));
method = cfg->orig_method;
code = cfg->native_code;
method_index = get_method_index (acfg, method);
symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
/* Make the labels local */
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, func_alignment);
if (acfg->global_symbols && acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
emit_label (acfg, cfg->asm_symbol);
if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
/*
* Write a C style symbol for every method, this has two uses:
* - it works on platforms where the dwarf debugging info is not
* yet supported.
* - it allows the setting of breakpoints of aot-ed methods.
*/
// Enable to force dedup to link these symbols and forbid compiling
// in duplicated code. This is an "assert when linking if broken" trick.
#if 0
if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))
debug_sym = mono_aot_get_mangled_method_name (method);
else
#endif
debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
cfg->asm_debug_symbol = g_strdup (debug_sym);
if (acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
// Enable to force dedup to link these symbols and forbid compiling
// in duplicated code. This is an "assert when linking if broken" trick.
#if 0
if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))
emit_global_inner (acfg, debug_sym, TRUE);
else
#endif
emit_local_symbol (acfg, debug_sym, symbol, TRUE);
emit_label (acfg, debug_sym);
}
export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
if (export_name) {
/* Emit a global symbol for the method */
emit_global_inner (acfg, export_name, TRUE);
emit_label (acfg, export_name);
}
if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
acfg->stats.code_size += cfg->code_len;
acfg->cfgs [method_index]->got_offset = acfg->got_offset;
MonoDebugMethodJitInfo *jit_debug_info = mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ());
emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, jit_debug_info);
mono_debug_free_method_jit_info (jit_debug_info);
emit_line (acfg);
if (acfg->aot_opts.write_symbols) {
if (debug_sym)
emit_symbol_size (acfg, debug_sym, ".");
else
emit_symbol_size (acfg, cfg->asm_symbol, ".");
g_free (debug_sym);
}
emit_label (acfg, symbol);
arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
g_free (symbol);
}
/**
* encode_patch:
*
* Encode PATCH_INFO into its disk representation.
*/
static void
encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
switch (patch_info->type) {
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_IMAGE:
encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
break;
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
break;
case MONO_PATCH_INFO_SWITCH: {
gpointer *table = (gpointer *)patch_info->data.table->table;
int k;
encode_value (patch_info->data.table->table_size, p, &p);
for (k = 0; k < patch_info->data.table->table_size; k++)
encode_value ((int)(gssize)table [k], p, &p);
break;
}
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
encode_method_ref (acfg, patch_info->data.method, p, &p);
break;
case MONO_PATCH_INFO_AOT_JIT_INFO:
case MONO_PATCH_INFO_CASTCLASS_CACHE:
encode_value (patch_info->data.index, p, &p);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
encode_value (patch_info->data.jit_icall_id, p, &p);
break;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
encode_value (patch_info->data.uindex, p, &p);
break;
case MONO_PATCH_INFO_LDSTR_LIT: {
guint32 len = strlen (patch_info->data.name);
encode_value (len, p, &p);
memcpy (p, patch_info->data.name, len + 1);
p += len + 1;
break;
}
case MONO_PATCH_INFO_LDSTR: {
guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
guint32 token = patch_info->data.token->token;
g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
encode_value (image_index, p, &p);
encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
break;
}
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_DECLSEC:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
encode_value (patch_info->data.token->token, p, &p);
encode_value (patch_info->data.token->has_context, p, &p);
if (patch_info->data.token->has_context)
encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
break;
case MONO_PATCH_INFO_EXC_NAME: {
MonoClass *ex_class;
ex_class =
mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
"System", (const char *)patch_info->data.target);
encode_klass_ref (acfg, ex_class, p, &p);
break;
}
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT:
encode_value (*((guint32 *)patch_info->data.target), p, &p);
break;
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT:
encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
break;
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
encode_klass_ref (acfg, patch_info->data.klass, p, &p);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
if (patch_info->data.del_tramp->method) {
encode_value (1, p, &p);
encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
} else {
encode_value (0, p, &p);
}
encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
break;
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
encode_field_info (acfg, patch_info->data.field, p, &p);
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
break;
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
guint32 offset;
/*
* entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
* reference the same klass/method, so encode it only once.
* For patches which refer to got entries, this sharing is done by get_got_offset, but
* these are not got entries.
*/
if (entry->in_mrgctx) {
offset = get_shared_method_ref (acfg, entry->d.method);
} else {
offset = get_shared_klass_ref (acfg, entry->d.klass);
}
encode_value (offset, p, &p);
g_assert ((int)entry->info_type < 256);
g_assert (entry->data->type < 256);
encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
encode_patch (acfg, entry->data, p, &p);
break;
}
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_AOT_MODULE:
break;
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
int i;
encode_method_ref (acfg, info->method, p, &p);
encode_value (info->num_entries, p, &p);
for (i = 0; i < info->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
encode_value (template_->info_type, p, &p);
switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
case MONO_PATCH_INFO_CLASS:
encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
break;
case MONO_PATCH_INFO_FIELD:
encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
break;
case MONO_PATCH_INFO_METHOD:
encode_method_ref (acfg, (MonoMethod*)template_->data, p, &p);
break;
default:
g_assert_not_reached ();
break;
}
}
break;
}
case MONO_PATCH_INFO_VIRT_METHOD:
encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
break;
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
break;
default:
g_error ("unable to handle jump info %d", patch_info->type);
}
*endbuf = p;
}
static void
encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
{
guint8 *p = buf;
guint32 pindex, offset;
MonoJumpInfo *patch_info;
encode_value (n_patches, p, &p);
for (pindex = 0; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
/* Nothing to do */
continue;
/* This shouldn't allocate a new offset */
offset = lookup_got_offset (acfg, llvm, patch_info);
encode_value (offset, p, &p);
}
*endbuf = p;
}
static void
emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
{
MonoMethod *method;
int pindex, buf_size, n_patches;
GPtrArray *patches;
MonoJumpInfo *patch_info;
guint8 *p, *buf;
guint32 offset;
gboolean needs_ctx = FALSE;
method = cfg->orig_method;
(void)get_method_index (acfg, method);
/* Sort relocations */
patches = g_ptr_array_new ();
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
g_ptr_array_add (patches, patch_info);
if (!acfg->aot_opts.llvm_only)
g_ptr_array_sort (patches, compare_patches);
/**********************/
/* Encode method info */
/**********************/
guint32 *got_offsets = g_new0 (guint32, patches->len);
n_patches = 0;
for (pindex = 0; pindex < patches->len; ++pindex) {
patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
(patch_info->type == MONO_PATCH_INFO_NONE)) {
patch_info->type = MONO_PATCH_INFO_NONE;
/* Nothing to do */
continue;
}
if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
/* Stored in a GOT slot initialized at module load time */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
/* Stored in a GOT slot initialized at module load time */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
/* Calls are made through the PLT */
patch_info->type = MONO_PATCH_INFO_NONE;
continue;
}
if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
needs_ctx = TRUE;
/* This shouldn't allocate a new offset */
offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
if (offset >= acfg->nshared_got_entries)
got_offsets [n_patches ++] = offset;
}
if (n_patches)
g_assert (cfg->has_got_slots);
buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
p = buf = (guint8 *)g_malloc (buf_size);
MonoGenericContext *ctx = mono_method_get_context (cfg->method);
guint8 flags = 0;
if (mono_class_get_cctor (method->klass))
flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
if (n_patches)
flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
if (needs_ctx && ctx)
flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
if (cfg->interp_entry_only)
flags |= MONO_AOT_METHOD_FLAG_INTERP_ENTRY_ONLY;
/* Saved into another table so it can be accessed without having access to this data */
cfg->aot_method_flags = flags;
encode_int (cfg->method_index, p, &p);
if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
encode_klass_ref (acfg, method->klass, p, &p);
if (needs_ctx && ctx)
encode_generic_context (acfg, ctx, p, &p);
if (n_patches) {
encode_value (n_patches, p, &p);
for (int i = 0; i < n_patches; ++i)
encode_value (got_offsets [i], p, &p);
}
g_ptr_array_free (patches, TRUE);
g_free (got_offsets);
acfg->stats.method_info_size += p - buf;
g_assert (p - buf < buf_size);
if (cfg->compile_llvm) {
char *symbol = g_strdup_printf ("info_%s", cfg->llvm_method_name);
cfg->llvm_info_var = mono_llvm_emit_aot_data_aligned (symbol, buf, p - buf, 1);
g_free (symbol);
/* aot-runtime.c will use this to check whenever this is an llvm method */
cfg->method_info_offset = 0;
} else {
cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
}
g_free (buf);
}
static guint32
get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
{
guint32 cache_index;
guint32 offset;
/* Reuse the unwind module to canonize and store unwind info entries */
cache_index = mono_cache_unwind_info (encoded, encoded_len);
/* Use +/- 1 to distinguish 0s from missing entries */
offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
if (offset)
return offset - 1;
else {
guint8 buf [16];
guint8 *p;
/*
* It would be easier to use assembler symbols, but the caller needs an
* offset now.
*/
offset = acfg->unwind_info_offset;
g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
p = buf;
encode_value (encoded_len, p, &p);
acfg->unwind_info_offset += encoded_len + (p - buf);
return offset;
}
}
static void
emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
{
int i, k, buf_size;
guint32 debug_info_size, seq_points_size;
guint8 *code;
MonoMethodHeader *header;
guint8 *p, *buf, *debug_info;
MonoJitInfo *jinfo = cfg->jit_info;
guint32 flags;
gboolean use_unwind_ops = FALSE;
MonoSeqPointInfo *seq_points;
code = cfg->native_code;
header = cfg->header;
if (!acfg->aot_opts.nodebug) {
mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
} else {
debug_info = NULL;
debug_info_size = 0;
}
seq_points = cfg->seq_point_info;
seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
buf_size += table->num_holes * 16;
}
p = buf = (guint8 *)g_malloc (buf_size);
use_unwind_ops = cfg->unwind_ops != NULL;
flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
encode_value (flags, p, &p);
if (use_unwind_ops) {
guint32 encoded_len;
guint8 *encoded;
guint32 unwind_desc;
encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
encode_value (unwind_desc, p, &p);
g_free (encoded);
} else {
encode_value (jinfo->unwind_info, p, &p);
}
/*Encode the number of holes before the number of clauses to make decoding easier*/
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
encode_value (table->num_holes, p, &p);
}
if (jinfo->has_arch_eh_info) {
/*
* In AOT mode, the code length is calculated from the address of the previous method,
* which could include alignment padding, so calculating the start of the epilog as
* code_len - epilog_size is correct any more. Save the real code len as a workaround.
*/
encode_value (jinfo->code_size, p, &p);
}
/* Exception table */
if (cfg->compile_llvm) {
/*
* When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
* since the information is only available to llc. Instead, we let llc save the data
* into the LSDA, and read it from there at runtime.
*/
/* The assembly might be CIL stripped so emit the data ourselves */
if (header->num_clauses)
encode_value (header->num_clauses, p, &p);
for (k = 0; k < header->num_clauses; ++k) {
MonoExceptionClause *clause;
clause = &header->clauses [k];
encode_value (clause->flags, p, &p);
if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
if (clause->data.catch_class) {
guint8 *buf2, *p2;
int len;
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
} else {
encode_value (0, p, &p);
}
}
/* Emit the IL ranges too, since they might not be available at runtime */
encode_value (clause->try_offset, p, &p);
encode_value (clause->try_len, p, &p);
encode_value (clause->handler_offset, p, &p);
encode_value (clause->handler_len, p, &p);
/* Emit a list of nesting clauses */
for (i = 0; i < header->num_clauses; ++i) {
gint32 cindex1 = k;
MonoExceptionClause *clause1 = &header->clauses [cindex1];
gint32 cindex2 = i;
MonoExceptionClause *clause2 = &header->clauses [cindex2];
if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
encode_value (i, p, &p);
}
encode_value (-1, p, &p);
}
} else {
if (jinfo->num_clauses)
encode_value (jinfo->num_clauses, p, &p);
for (k = 0; k < jinfo->num_clauses; ++k) {
MonoJitExceptionInfo *ei = &jinfo->clauses [k];
encode_value (ei->flags, p, &p);
#ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
/* Not used for catch clauses */
if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
encode_value (ei->exvar_offset, p, &p);
#else
encode_value (ei->exvar_offset, p, &p);
#endif
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
else {
if (ei->data.catch_class) {
guint8 *buf2, *p2;
int len;
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
} else {
encode_value (0, p, &p);
}
}
encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
}
}
if (jinfo->has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
for (i = 0; i < table->num_holes; ++i) {
MonoTryBlockHoleJitInfo *hole = &table->holes [i];
encode_value (hole->clause, p, &p);
encode_value (hole->length, p, &p);
encode_value (hole->offset, p, &p);
}
}
if (jinfo->has_arch_eh_info) {
MonoArchEHJitInfo *eh_info;
eh_info = mono_jit_info_get_arch_eh_info (jinfo);
encode_value (eh_info->stack_size, p, &p);
encode_value (eh_info->epilog_size, p, &p);
}
if (jinfo->has_generic_jit_info) {
MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
guint8 *buf2, *p2;
int len;
encode_value (gi->nlocs, p, &p);
if (gi->nlocs) {
for (i = 0; i < gi->nlocs; ++i) {
MonoDwarfLocListEntry *entry = &gi->locations [i];
encode_value (entry->is_reg ? 1 : 0, p, &p);
encode_value (entry->reg, p, &p);
if (!entry->is_reg)
encode_value (entry->offset, p, &p);
if (i == 0)
g_assert (entry->from == 0);
else
encode_value (entry->from, p, &p);
encode_value (entry->to, p, &p);
}
} else {
if (!cfg->compile_llvm) {
encode_value (gi->has_this ? 1 : 0, p, &p);
encode_value (gi->this_reg, p, &p);
encode_value (gi->this_offset, p, &p);
}
}
/*
* Need to encode jinfo->method too, since it is not equal to 'method'
* when using generic sharing.
*/
buf2 = (guint8 *)g_malloc (4096);
p2 = buf2;
encode_method_ref (acfg, jinfo->d.method, p2, &p2);
len = p2 - buf2;
g_assert (len < 4096);
encode_value (len, p, &p);
memcpy (p, buf2, len);
p += p2 - buf2;
g_free (buf2);
if (gsctx && gsctx->is_gsharedvt) {
encode_value (1, p, &p);
} else {
encode_value (0, p, &p);
}
}
if (seq_points_size)
p += mono_seq_point_info_write (seq_points, p);
g_assert (debug_info_size < buf_size);
encode_value (debug_info_size, p, &p);
if (debug_info_size) {
memcpy (p, debug_info, debug_info_size);
p += debug_info_size;
g_free (debug_info);
}
/* GC Map */
if (cfg->gc_map) {
encode_value (cfg->gc_map_size, p, &p);
/* The GC map requires 4 bytes of alignment */
while ((gsize)p % 4)
p ++;
memcpy (p, cfg->gc_map, cfg->gc_map_size);
p += cfg->gc_map_size;
}
acfg->stats.ex_info_size += p - buf;
g_assert (p - buf < buf_size);
/* Emit info */
/* The GC Map requires 4 byte alignment */
cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
g_free (buf);
}
static guint32
emit_klass_info (MonoAotCompile *acfg, guint32 token)
{
ERROR_DECL (error);
MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
guint8 *p, *buf;
int i, buf_size, res;
gboolean no_special_static, cant_encode;
gpointer iter = NULL;
if (!klass) {
mono_error_cleanup (error);
buf_size = 16;
p = buf = (guint8 *)g_malloc (buf_size);
/* Mark as unusable */
encode_value (-1, p, &p);
res = add_to_blob (acfg, buf, p - buf);
g_free (buf);
return res;
}
buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
p = buf = (guint8 *)g_malloc (buf_size);
g_assert (klass);
mono_class_init_internal (klass);
mono_class_get_nested_types (klass, &iter);
g_assert (m_class_is_nested_classes_inited (klass));
mono_class_setup_vtable (klass);
/*
* Emit all the information which is required for creating vtables so
* the runtime does not need to create the MonoMethod structures which
* take up a lot of space.
*/
no_special_static = !mono_class_has_special_static_fields (klass);
/* Check whenever we have enough info to encode the vtable */
cant_encode = FALSE;
MonoMethod **klass_vtable = m_class_get_vtable (klass);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm = klass_vtable [i];
if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
cant_encode = TRUE;
}
mono_class_has_finalizer (klass);
if (mono_class_has_failure (klass))
cant_encode = TRUE;
if (mono_class_is_gtd (klass) || cant_encode) {
encode_value (-1, p, &p);
} else {
gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
encode_value (m_class_get_vtable_size (klass), p, &p);
encode_value ((m_class_has_weak_fields (klass) << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (m_class_has_static_refs (klass) << 6) | (m_class_has_references (klass) << 5) | ((m_class_is_blittable (klass) << 4) | (has_nested ? 1 : 0) << 3) | (m_class_has_cctor (klass) << 2) | (m_class_has_finalize (klass) << 1) | m_class_is_ghcimpl (klass), p, &p);
if (m_class_has_cctor (klass))
encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
if (m_class_has_finalize (klass))
encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
encode_value (m_class_get_instance_size (klass), p, &p);
encode_value (mono_class_data_size (klass), p, &p);
encode_value (m_class_get_packing_size (klass), p, &p);
encode_value (m_class_get_min_align (klass), p, &p);
for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
MonoMethod *cm = klass_vtable [i];
if (cm)
encode_method_ref (acfg, cm, p, &p);
else
encode_value (0, p, &p);
}
}
acfg->stats.class_info_size += p - buf;
g_assert (p - buf < buf_size);
res = add_to_blob (acfg, buf, p - buf);
g_free (buf);
return res;
}
static char*
get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
{
char *debug_sym = NULL;
char *prefix;
if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
/* Need to add a prefix to create unique symbols */
prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
} else {
#if defined(TARGET_WIN32) && defined(TARGET_X86)
prefix = mangle_symbol_alloc ("plt_");
#else
prefix = g_strdup ("plt_");
#endif
}
switch (ji->type) {
case MONO_PATCH_INFO_METHOD:
debug_sym = get_debug_sym (ji->data.method, prefix, cache);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
break;
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
char *s = get_debug_sym (ji->data.method, "", cache);
debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
g_free (s);
break;
}
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, (gulong)ji->data.uindex);
break;
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
default:
break;
}
g_free (prefix);
return sanitize_symbol (acfg, debug_sym);
}
/*
* Calls made from AOTed code are routed through a table of jumps similar to the
* ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
* control to the AOT runtime through a trampoline.
*/
static void
emit_plt (MonoAotCompile *acfg)
{
int i;
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->plt_offset == 1);
return;
}
emit_line (acfg);
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 16);
emit_info_symbol (acfg, "plt", TRUE);
emit_label (acfg, acfg->plt_symbol);
for (i = 0; i < acfg->plt_offset; ++i) {
char *debug_sym = NULL;
MonoPltEntry *plt_entry = NULL;
if (i == 0)
/*
* The first plt entry is unused.
*/
continue;
plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
debug_sym = plt_entry->debug_sym;
if (acfg->thumb_mixed && !plt_entry->jit_used)
/* Emit only a thumb version */
continue;
/* Skip plt entries not actually called */
if (!plt_entry->jit_used && !plt_entry->llvm_used)
continue;
if (acfg->llvm && !acfg->thumb_mixed) {
emit_label (acfg, plt_entry->llvm_symbol);
if (acfg->llvm) {
emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
#if defined(TARGET_MACH)
fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
#endif
}
}
if (debug_sym) {
if (acfg->need_no_dead_strip) {
emit_unset_mode (acfg);
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
}
emit_local_symbol (acfg, debug_sym, NULL, TRUE);
emit_label (acfg, debug_sym);
}
emit_label (acfg, plt_entry->symbol);
arch_emit_plt_entry (acfg, acfg->got_symbol, i, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
if (debug_sym)
emit_symbol_size (acfg, debug_sym, ".");
}
if (acfg->thumb_mixed) {
/* Make sure the ARM symbols don't alias the thumb ones */
emit_zero_bytes (acfg, 16);
/*
* Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
* code.
*/
for (i = 0; i < acfg->plt_offset; ++i) {
char *debug_sym = NULL;
MonoPltEntry *plt_entry = NULL;
if (i == 0)
continue;
plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
/* Skip plt entries not actually called by LLVM code */
if (!plt_entry->llvm_used)
continue;
if (acfg->aot_opts.write_symbols) {
if (plt_entry->debug_sym)
debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
}
if (debug_sym) {
#if defined(TARGET_MACH)
fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
#endif
emit_local_symbol (acfg, debug_sym, NULL, TRUE);
emit_label (acfg, debug_sym);
}
fprintf (acfg->fp, "\n.thumb_func\n");
emit_label (acfg, plt_entry->llvm_symbol);
if (acfg->llvm)
emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, i, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
if (debug_sym) {
emit_symbol_size (acfg, debug_sym, ".");
g_free (debug_sym);
}
}
}
emit_symbol_size (acfg, acfg->plt_symbol, ".");
emit_info_symbol (acfg, "plt_end", TRUE);
arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
}
/*
* emit_trampoline_full:
*
* If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
* create_jit_info_for_trampoline ().
*/
static G_GNUC_UNUSED void
emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
{
char start_symbol [MAX_SYMBOL_SIZE];
char end_symbol [MAX_SYMBOL_SIZE];
char symbol [MAX_SYMBOL_SIZE];
guint32 buf_size, info_offset;
MonoJumpInfo *patch_info;
guint8 *buf, *p;
GPtrArray *patches;
char *name;
guint8 *code;
guint32 code_size;
MonoJumpInfo *ji;
GSList *unwind_ops;
g_assert (info);
name = info->name;
code = (guint8*)MINI_FTNPTR_TO_ADDR (info->code);
code_size = info->code_size;
ji = info->ji;
unwind_ops = info->unwind_ops;
/* Emit code */
sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
emit_section_change (acfg, ".text", 0);
emit_global (acfg, start_symbol, TRUE);
emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
emit_label (acfg, start_symbol);
sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
emit_label (acfg, symbol);
/*
* The code should access everything through the GOT, so we pass
* TRUE here.
*/
emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
emit_symbol_size (acfg, start_symbol, ".");
if (emit_tinfo) {
sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
emit_label (acfg, end_symbol);
}
/* Emit info */
/* Sort relocations */
patches = g_ptr_array_new ();
for (patch_info = ji; patch_info; patch_info = patch_info->next)
if (patch_info->type != MONO_PATCH_INFO_NONE)
g_ptr_array_add (patches, patch_info);
g_ptr_array_sort (patches, compare_patches);
buf_size = patches->len * 128 + 128;
buf = (guint8 *)g_malloc (buf_size);
p = buf;
encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
g_assert (p - buf < buf_size);
g_ptr_array_free (patches, TRUE);
sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
info_offset = add_to_blob (acfg, buf, p - buf);
emit_section_change (acfg, RODATA_SECT, 0);
emit_global (acfg, symbol, FALSE);
emit_label (acfg, symbol);
emit_int32 (acfg, info_offset);
if (emit_tinfo) {
guint8 *encoded;
guint32 encoded_len;
guint32 uw_offset;
/*
* Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
*/
encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
g_free (encoded);
emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
emit_int32 (acfg, uw_offset);
}
/* Emit debug info */
if (unwind_ops) {
char symbol2 [MAX_SYMBOL_SIZE];
sprintf (symbol, "%s", name);
sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
if (acfg->dwarf)
mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
}
g_free (buf);
}
static G_GNUC_UNUSED void
emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
{
emit_trampoline_full (acfg, info, TRUE);
}
static void
emit_trampolines (MonoAotCompile *acfg)
{
char symbol [MAX_SYMBOL_SIZE];
char end_symbol [MAX_SYMBOL_SIZE + 2];
int i, tramp_got_offset;
int ntype;
#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
int tramp_type;
#endif
if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
return;
if (acfg->aot_opts.llvm_only)
return;
g_assert (acfg->image->assembly);
/* Currently, we emit most trampolines into the mscorlib AOT image. */
if (mono_is_corlib_image(acfg->image->assembly->image)) {
#ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
MonoTrampInfo *info;
/*
* Emit the generic trampolines.
*
* We could save some code by treating the generic trampolines as a wrapper
* method, but that approach has its own complexities, so we choose the simpler
* method.
*/
for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
/* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
}
/* Emit the exception related code pieces */
mono_arch_get_restore_context (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_call_filter (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_throw_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_rethrow_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_rethrow_preserve_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_get_throw_corlib_exception (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#endif
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
mono_arch_get_gsharedvt_trampoline (&info, TRUE);
if (info) {
emit_trampoline_full (acfg, info, TRUE);
/* Create a separate out trampoline for more information in stack traces */
info->name = g_strdup ("gsharedvt_out_trampoline");
emit_trampoline_full (acfg, info, TRUE);
mono_tramp_info_free (info);
}
#endif
#if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
{
GSList *l = mono_arch_get_trampolines (TRUE);
while (l) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
emit_trampoline (acfg, info);
l = l->next;
}
}
#endif
for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
int offset;
offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
}
#ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
emit_trampoline (acfg, info);
mono_tramp_info_free (info);
#endif
{
GSList *l;
/* delegate_invoke_impl trampolines */
l = mono_arch_get_delegate_invoke_impls ();
while (l) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
emit_trampoline (acfg, info);
l = l->next;
}
}
if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
mono_arch_get_interp_to_native_trampoline (&info);
emit_trampoline (acfg, info);
#ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
mono_arch_get_native_to_interp_trampoline (&info);
emit_trampoline (acfg, info);
#endif
}
#endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
/* Emit trampolines which are numerous */
/*
* These include the following:
* - specific trampolines
* - static rgctx invoke trampolines
* - imt trampolines
* These trampolines have the same code, they are parameterized by GOT
* slots.
* They are defined in this file, in the arch_... routines instead of
* in tramp-<ARCH>.c, since it is easier to do it this way.
*/
/*
* When running in aot-only mode, we can't create specific trampolines at
* runtime, so we create a few, and save them in the AOT file.
* Normal trampolines embed their argument as a literal inside the
* trampoline code, we can't do that here, so instead we embed an offset
* which needs to be added to the trampoline address to get the address of
* the GOT slot which contains the argument value.
* The generated trampolines jump to the generic trampolines using another
* GOT slot, which will be setup by the AOT loader to point to the
* generic trampoline code of the given type.
*/
/*
* FIXME: Maybe we should use more specific trampolines (i.e. one class init for
* each class).
*/
emit_section_change (acfg, ".text", 0);
tramp_got_offset = acfg->got_offset;
for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
switch (ntype) {
case MONO_AOT_TRAMP_SPECIFIC:
sprintf (symbol, "specific_trampolines");
break;
case MONO_AOT_TRAMP_STATIC_RGCTX:
sprintf (symbol, "static_rgctx_trampolines");
break;
case MONO_AOT_TRAMP_IMT:
sprintf (symbol, "imt_trampolines");
break;
case MONO_AOT_TRAMP_GSHAREDVT_ARG:
sprintf (symbol, "gsharedvt_arg_trampolines");
break;
case MONO_AOT_TRAMP_FTNPTR_ARG:
sprintf (symbol, "ftnptr_arg_trampolines");
break;
case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
sprintf (symbol, "unbox_arbitrary_trampolines");
break;
default:
g_assert_not_reached ();
}
sprintf (end_symbol, "%s_e", symbol);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, end_symbol, TRUE);
emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
emit_info_symbol (acfg, symbol, TRUE);
acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
int tramp_size = 0;
switch (ntype) {
case MONO_AOT_TRAMP_SPECIFIC:
arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_STATIC_RGCTX:
arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_IMT:
arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 1;
break;
case MONO_AOT_TRAMP_GSHAREDVT_ARG:
arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_FTNPTR_ARG:
arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 2;
break;
case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
tramp_got_offset += 1;
break;
default:
g_assert_not_reached ();
}
if (!acfg->trampoline_size [ntype]) {
g_assert (tramp_size);
acfg->trampoline_size [ntype] = tramp_size;
}
}
emit_label (acfg, end_symbol);
emit_int32 (acfg, 0);
}
arch_emit_specific_trampoline_pages (acfg);
/* Reserve some entries at the end of the GOT for our use */
acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
}
acfg->got_offset += acfg->num_trampoline_got_entries;
}
static gboolean
str_begins_with (const char *str1, const char *str2)
{
int len = strlen (str2);
return strncmp (str1, str2, len) == 0;
}
void*
mono_aot_readonly_field_override (MonoClassField *field)
{
ReadOnlyValue *rdv;
for (rdv = readonly_values; rdv; rdv = rdv->next) {
char *p = rdv->name;
int len;
MonoClass *field_parent = m_field_get_parent (field);
len = strlen (m_class_get_name_space (field_parent));
if (strncmp (p, m_class_get_name_space (field_parent), len))
continue;
p += len;
if (*p++ != '.')
continue;
len = strlen (m_class_get_name (field_parent));
if (strncmp (p, m_class_get_name (field_parent), len))
continue;
p += len;
if (*p++ != '.')
continue;
if (strcmp (p, field->name))
continue;
switch (rdv->type) {
case MONO_TYPE_I1:
return &rdv->value.i1;
case MONO_TYPE_I2:
return &rdv->value.i2;
case MONO_TYPE_I4:
return &rdv->value.i4;
default:
break;
}
}
return NULL;
}
static void
add_readonly_value (MonoAotOptions *opts, const char *val)
{
ReadOnlyValue *rdv;
const char *fval;
const char *tval;
/* the format of val is:
* namespace.typename.fieldname=type/value
* type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
*/
fval = strrchr (val, '/');
if (!fval) {
fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
exit (1);
}
tval = strrchr (val, '=');
if (!tval) {
fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
exit (1);
}
rdv = g_new0 (ReadOnlyValue, 1);
rdv->name = (char *)g_malloc0 (tval - val + 1);
memcpy (rdv->name, val, tval - val);
tval++;
fval++;
if (strncmp (tval, "i1", 2) == 0) {
rdv->value.i1 = atoi (fval);
rdv->type = MONO_TYPE_I1;
} else if (strncmp (tval, "i2", 2) == 0) {
rdv->value.i2 = atoi (fval);
rdv->type = MONO_TYPE_I2;
} else if (strncmp (tval, "i4", 2) == 0) {
rdv->value.i4 = atoi (fval);
rdv->type = MONO_TYPE_I4;
} else {
fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
exit (1);
}
rdv->next = readonly_values;
readonly_values = rdv;
}
static gchar *
clean_path (gchar * path)
{
if (!path)
return NULL;
if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
return path;
gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, (const char*)NULL);
g_free (path);
return clean;
}
static const gchar *
wrap_path (const gchar * path)
{
int len;
if (!path)
return NULL;
// If the string contains no spaces, just return the original string.
if (strstr (path, " ") == NULL)
return path;
// If the string is already wrapped in quotes, return it.
len = strlen (path);
if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
return path;
// If the string contains spaces, then wrap it in quotes.
gchar *clean = g_strdup_printf ("\"%s\"", path);
return clean;
}
// Duplicate a char range and add it to a ptrarray, but only if it is nonempty
static void
ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
{
ptrdiff_t len = end-start;
if (len > 0)
g_ptr_array_add (args, g_strndup (start, len));
}
static GPtrArray *
mono_aot_split_options (const char *aot_options)
{
enum MonoAotOptionState {
MONO_AOT_OPTION_STATE_DEFAULT,
MONO_AOT_OPTION_STATE_STRING,
MONO_AOT_OPTION_STATE_ESCAPE,
};
GPtrArray *args = g_ptr_array_new ();
enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
gchar const *opt_start = aot_options;
gboolean end_of_string = FALSE;
gchar cur;
g_return_val_if_fail (aot_options != NULL, NULL);
while ((cur = *aot_options) != '\0') {
if (state == MONO_AOT_OPTION_STATE_ESCAPE)
goto next;
switch (cur) {
case '"':
// If we find a quote, then if we're in the default case then
// it means we've found the start of a string, if not then it
// means we've found the end of the string and should switch
// back to the default case.
switch (state) {
case MONO_AOT_OPTION_STATE_DEFAULT:
state = MONO_AOT_OPTION_STATE_STRING;
break;
case MONO_AOT_OPTION_STATE_STRING:
state = MONO_AOT_OPTION_STATE_DEFAULT;
break;
case MONO_AOT_OPTION_STATE_ESCAPE:
g_assert_not_reached ();
break;
}
break;
case '\\':
// If we've found an escaping operator, then this means we
// should not process the next character if inside a string.
if (state == MONO_AOT_OPTION_STATE_STRING)
state = MONO_AOT_OPTION_STATE_ESCAPE;
break;
case ',':
// If we're in the default state then this means we've found
// an option, store it for later processing.
if (state == MONO_AOT_OPTION_STATE_DEFAULT)
goto new_opt;
break;
}
next:
aot_options++;
restart:
// If the next character is end of string, then process the last option.
if (*(aot_options) == '\0') {
end_of_string = TRUE;
goto new_opt;
}
continue;
new_opt:
ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
opt_start = ++aot_options;
if (end_of_string)
break;
goto restart; // Check for null and continue loop
}
return args;
}
static gboolean
parse_cpu_features (const gchar *attr)
{
if (!attr || strlen (attr) < 2) {
fprintf (stderr, "Invalid attribute");
return FALSE;
}
//+foo - enable foo
//foo - enable foo
//-foo - disable foo
gboolean enabled = TRUE;
if (attr [0] == '-')
enabled = FALSE;
int prefix = (attr [0] == '-' || attr [0] == '+') ? 1 : 0;
MonoCPUFeatures feature = (MonoCPUFeatures) 0;
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// e.g.:
// `mattr=+sse3` = +sse,+sse2,+sse3
// `mattr=-sse3` = -sse3,-ssse3,-sse4.1,-sse4.2,-popcnt,-avx,-avx2,-fma
if (!strcmp (attr + prefix, "sse"))
feature = MONO_CPU_X86_SSE_COMBINED;
else if (!strcmp (attr + prefix, "sse2"))
feature = MONO_CPU_X86_SSE2_COMBINED;
else if (!strcmp (attr + prefix, "sse3"))
feature = MONO_CPU_X86_SSE3_COMBINED;
else if (!strcmp (attr + prefix, "ssse3"))
feature = MONO_CPU_X86_SSSE3_COMBINED;
else if (!strcmp (attr + prefix, "sse4.1"))
feature = MONO_CPU_X86_SSE41_COMBINED;
else if (!strcmp (attr + prefix, "sse4.2"))
feature = MONO_CPU_X86_SSE42_COMBINED;
else if (!strcmp (attr + prefix, "avx"))
feature = MONO_CPU_X86_AVX_COMBINED;
else if (!strcmp (attr + prefix, "avx2"))
feature = MONO_CPU_X86_AVX2_COMBINED;
else if (!strcmp (attr + prefix, "pclmul"))
feature = MONO_CPU_X86_PCLMUL_COMBINED;
else if (!strcmp (attr + prefix, "aes"))
feature = MONO_CPU_X86_AES_COMBINED;
else if (!strcmp (attr + prefix, "popcnt"))
feature = MONO_CPU_X86_POPCNT_COMBINED;
else if (!strcmp (attr + prefix, "fma"))
feature = MONO_CPU_X86_FMA_COMBINED;
// these are independent
else if (!strcmp (attr + prefix, "lzcnt")) // technically, it'a a part of BMI but only on Intel
feature = MONO_CPU_X86_LZCNT;
else if (!strcmp (attr + prefix, "bmi")) // NOTE: it's not "bmi1"
feature = MONO_CPU_X86_BMI1;
else if (!strcmp (attr + prefix, "bmi2"))
feature = MONO_CPU_X86_BMI2; // BMI2 doesn't imply BMI1
else {
// we don't have a flag for it but it's probably recognized by opt/llc so let's don't fire an error here
// printf ("Unknown cpu feature: %s\n", attr);
}
// if we disable a feature from the SSE-AVX tree we also need to disable all dependencies
if (!enabled && (feature & MONO_CPU_X86_FULL_SSEAVX_COMBINED))
feature = (MonoCPUFeatures) (MONO_CPU_X86_FULL_SSEAVX_COMBINED & ~feature);
#elif defined(TARGET_ARM64)
// MONO_CPU_ARM64_BASE is unconditionally set in mini_get_cpu_features.
if (!strcmp (attr + prefix, "crc"))
feature = MONO_CPU_ARM64_CRC;
else if (!strcmp (attr + prefix, "crypto"))
feature = MONO_CPU_ARM64_CRYPTO;
else if (!strcmp (attr + prefix, "neon"))
feature = MONO_CPU_ARM64_NEON;
else if (!strcmp (attr + prefix, "rdm"))
feature = MONO_CPU_ARM64_RDM;
else if (!strcmp (attr + prefix, "dotprod"))
feature = MONO_CPU_ARM64_DP;
#elif defined(TARGET_WASM)
if (!strcmp (attr + prefix, "simd"))
feature = MONO_CPU_WASM_SIMD;
#else
(void)prefix; // unused
#endif
if (enabled)
mono_cpu_features_enabled = (MonoCPUFeatures) (mono_cpu_features_enabled | feature);
else
mono_cpu_features_disabled = (MonoCPUFeatures) (mono_cpu_features_disabled | feature);
return TRUE;
}
static void
mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
{
GPtrArray* args;
args = mono_aot_split_options (aot_options ? aot_options : "");
for (int i = 0; i < args->len; ++i) {
const char *arg = (const char *)g_ptr_array_index (args, i);
if (str_begins_with (arg, "outfile=")) {
opts->outfile = g_strdup (arg + strlen ("outfile="));
} else if (str_begins_with (arg, "llvm-outfile=")) {
opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
} else if (str_begins_with (arg, "temp-path=")) {
opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
} else if (str_begins_with (arg, "save-temps")) {
opts->save_temps = TRUE;
} else if (str_begins_with (arg, "keep-temps")) {
opts->save_temps = TRUE;
} else if (str_begins_with (arg, "write-symbols")) {
opts->write_symbols = TRUE;
} else if (str_begins_with (arg, "no-write-symbols")) {
opts->write_symbols = FALSE;
// Intentionally undocumented -- one-off experiment
} else if (str_begins_with (arg, "metadata-only")) {
opts->metadata_only = TRUE;
} else if (str_begins_with (arg, "bind-to-runtime-version")) {
opts->bind_to_runtime_version = TRUE;
} else if (str_begins_with (arg, "full")) {
opts->mode = MONO_AOT_MODE_FULL;
} else if (str_begins_with (arg, "hybrid")) {
opts->mode = MONO_AOT_MODE_HYBRID;
} else if (str_begins_with (arg, "interp")) {
opts->interp = TRUE;
} else if (str_begins_with (arg, "threads=")) {
opts->nthreads = atoi (arg + strlen ("threads="));
} else if (str_begins_with (arg, "static")) {
opts->static_link = TRUE;
opts->no_dlsym = TRUE;
} else if (str_begins_with (arg, "asmonly")) {
opts->asm_only = TRUE;
} else if (str_begins_with (arg, "asmwriter")) {
opts->asm_writer = TRUE;
} else if (str_begins_with (arg, "nodebug")) {
opts->nodebug = TRUE;
} else if (str_begins_with (arg, "dwarfdebug")) {
opts->dwarf_debug = TRUE;
// Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
} else if (str_begins_with (arg, "nopagetrampolines")) {
opts->use_trampolines_page = FALSE;
} else if (str_begins_with (arg, "ntrampolines=")) {
opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
} else if (str_begins_with (arg, "nrgctx-trampolines=")) {
opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
} else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
} else if (str_begins_with (arg, "nimt-trampolines=")) {
opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
} else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
} else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
} else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
} else if (str_begins_with (arg, "tool-prefix=")) {
opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
} else if (str_begins_with (arg, "ld-flags=")) {
opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
} else if (str_begins_with (arg, "ld-name=")) {
opts->ld_name = g_strdup (arg + strlen ("ld-name="));
} else if (str_begins_with (arg, "soft-debug")) {
opts->soft_debug = TRUE;
// Intentionally undocumented x2-- deprecated
} else if (str_begins_with (arg, "gen-seq-points-file=")) {
fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
} else if (str_begins_with (arg, "gen-seq-points-file")) {
fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
} else if (str_begins_with (arg, "msym-dir=")) {
mini_debug_options.no_seq_points_compact_data = FALSE;
opts->gen_msym_dir = TRUE;
opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
} else if (str_begins_with (arg, "direct-pinvoke")) {
opts->direct_pinvoke = TRUE;
} else if (str_begins_with (arg, "direct-icalls")) {
opts->direct_icalls = TRUE;
} else if (str_begins_with (arg, "direct-extern-calls")) {
opts->direct_extern_calls = TRUE;
} else if (str_begins_with (arg, "no-direct-calls")) {
opts->no_direct_calls = TRUE;
} else if (str_begins_with (arg, "print-skipped")) {
opts->print_skipped_methods = TRUE;
} else if (str_begins_with (arg, "stats")) {
opts->stats = TRUE;
// Intentionally undocumented-- has no known function other than to debug the compiler
} else if (str_begins_with (arg, "no-instances")) {
opts->no_instances = TRUE;
// Intentionally undocumented x4-- Used for internal debugging of compiler
} else if (str_begins_with (arg, "log-generics")) {
opts->log_generics = TRUE;
} else if (str_begins_with (arg, "log-instances=")) {
opts->log_instances = TRUE;
opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
} else if (str_begins_with (arg, "log-instances")) {
opts->log_instances = TRUE;
} else if (str_begins_with (arg, "internal-logfile=")) {
opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
} else if (str_begins_with (arg, "dedup-skip")) {
opts->dedup = TRUE;
} else if (str_begins_with (arg, "dedup-include=")) {
opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
} else if (str_begins_with (arg, "mtriple=")) {
opts->mtriple = g_strdup (arg + strlen ("mtriple="));
} else if (str_begins_with (arg, "llvm-path=")) {
opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
} else if (!strcmp (arg, "try-llvm")) {
// If we can load LLVM, use it
// Note: if you call this function from anywhere but mono_compile_assembly,
// this will only set the try_llvm attribute and not do the probing / set the
// attribute.
opts->try_llvm = TRUE;
} else if (!strcmp (arg, "llvm")) {
opts->llvm = TRUE;
} else if (str_begins_with (arg, "readonly-value=")) {
add_readonly_value (opts, arg + strlen ("readonly-value="));
} else if (str_begins_with (arg, "info")) {
printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
exit (0);
// Intentionally undocumented: Used for precise stack maps, which are not available yet
} else if (str_begins_with (arg, "gc-maps")) {
mini_gc_enable_gc_maps_for_aot ();
// Intentionally undocumented: Used for internal debugging
} else if (str_begins_with (arg, "dump")) {
opts->dump_json = TRUE;
} else if (str_begins_with (arg, "llvmonly")) {
opts->mode = MONO_AOT_MODE_FULL;
opts->llvm = TRUE;
opts->llvm_only = TRUE;
} else if (str_begins_with (arg, "data-outfile=")) {
opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
} else if (str_begins_with (arg, "profile=")) {
opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
} else if (!strcmp (arg, "profile-only")) {
opts->profile_only = TRUE;
} else if (!strcmp (arg, "verbose")) {
opts->verbose = TRUE;
} else if (!strcmp (arg, "allow-errors")) {
opts->allow_errors = TRUE;
} else if (str_begins_with (arg, "llvmopts=")){
if (opts->llvm_opts) {
char *s = g_strdup_printf ("%s %s", opts->llvm_opts, arg + strlen ("llvmopts="));
g_free (opts->llvm_opts);
opts->llvm_opts = s;
} else {
opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
}
} else if (str_begins_with (arg, "llvmllc=")){
opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
} else if (!strcmp (arg, "deterministic")) {
opts->deterministic = TRUE;
} else if (!strcmp (arg, "no-opt")) {
opts->no_opt = TRUE;
} else if (str_begins_with (arg, "clangxx=")) {
opts->clangxx = g_strdup (arg + strlen ("clangxx="));
} else if (str_begins_with (arg, "mcpu=")) {
if (!strcmp(arg, "mcpu=native")) {
opts->use_current_cpu = TRUE;
} else if (!strcmp(arg, "mcpu=generic")) {
opts->use_current_cpu = FALSE;
} else {
printf ("mcpu can only be 'native' or 'generic' (default).\n");
exit (0);
}
} else if (str_begins_with (arg, "mattr=")) {
gchar* attr = g_strdup (arg + strlen ("mattr="));
if (!parse_cpu_features (attr))
exit (0);
// mattr can be declared more than once, e.g.
// `mattr=avx2,mattr=lzcnt,mattr=bmi2`
if (!opts->llvm_cpu_attr)
opts->llvm_cpu_attr = attr;
else {
char* old_attrs = opts->llvm_cpu_attr;
opts->llvm_cpu_attr = g_strdup_printf ("%s,%s", opts->llvm_cpu_attr, attr);
g_free (old_attrs);
}
} else if (str_begins_with (arg, "depfile=")) {
opts->depfile = g_strdup (arg + strlen ("depfile="));
} else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
printf ("Supported options for --aot:\n");
printf (" asmonly\n");
printf (" bind-to-runtime-version\n");
printf (" bitcode\n");
printf (" data-outfile=\n");
printf (" direct-icalls\n");
printf (" direct-pinvoke\n");
printf (" dwarfdebug\n");
printf (" full\n");
printf (" hybrid\n");
printf (" info\n");
printf (" keep-temps\n");
printf (" llvm\n");
printf (" llvmonly\n");
printf (" llvm-outfile=\n");
printf (" llvm-path=\n");
printf (" msym-dir=\n");
printf (" mtriple\n");
printf (" nimt-trampolines=\n");
printf (" nodebug\n");
printf (" no-direct-calls\n");
printf (" no-write-symbols\n");
printf (" nrgctx-trampolines=\n");
printf (" nrgctx-fetch-trampolines=\n");
printf (" ngsharedvt-trampolines=\n");
printf (" nftnptr-arg-trampolines=\n");
printf (" nunbox-arbitrary-trampolines=\n");
printf (" ntrampolines=\n");
printf (" outfile=\n");
printf (" profile=\n");
printf (" profile-only\n");
printf (" print-skipped-methods\n");
printf (" readonly-value=\n");
printf (" save-temps\n");
printf (" soft-debug\n");
printf (" static\n");
printf (" stats\n");
printf (" temp-path=\n");
printf (" tool-prefix=\n");
printf (" threads=\n");
printf (" write-symbols\n");
printf (" verbose\n");
printf (" allow-errors\n");
printf (" no-opt\n");
printf (" llvmopts=\n");
printf (" llvmllc=\n");
printf (" clangxx=\n");
printf (" depfile=\n");
printf (" mcpu=\n");
printf (" mattr=\n");
printf (" help/?\n");
exit (0);
} else {
fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
exit (1);
}
g_free ((gpointer) arg);
}
if (opts->use_trampolines_page) {
opts->ntrampolines = 0;
opts->nrgctx_trampolines = 0;
opts->nimt_trampolines = 0;
opts->ngsharedvt_arg_trampolines = 0;
opts->nftnptr_arg_trampolines = 0;
opts->nunbox_arbitrary_trampolines = 0;
}
g_ptr_array_free (args, /*free_seg=*/TRUE);
}
static void
add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
{
MonoMethod *method = (MonoMethod*)key;
MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
MonoAotCompile *acfg = (MonoAotCompile *)user_data;
MonoJumpInfoToken *new_ji;
new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
new_ji->image = ji->image;
new_ji->token = ji->token;
g_hash_table_insert (acfg->token_info_hash, method, new_ji);
}
static gboolean
can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
{
if (m_class_get_type_token (klass))
return TRUE;
if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR))
return TRUE;
if (m_class_get_rank (klass))
return can_encode_class (acfg, m_class_get_element_class (klass));
return FALSE;
}
static gboolean
can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
{
if (method->wrapper_type) {
switch (method->wrapper_type) {
case MONO_WRAPPER_NONE:
case MONO_WRAPPER_STELEMREF:
case MONO_WRAPPER_ALLOC:
case MONO_WRAPPER_OTHER:
case MONO_WRAPPER_WRITE_BARRIER:
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE:
case MONO_WRAPPER_SYNCHRONIZED:
case MONO_WRAPPER_MANAGED_TO_NATIVE:
break;
case MONO_WRAPPER_MANAGED_TO_MANAGED:
case MONO_WRAPPER_NATIVE_TO_MANAGED:
case MONO_WRAPPER_CASTCLASS: {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info)
return TRUE;
else
return FALSE;
break;
}
default:
//printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
return FALSE;
}
} else {
if (!method->token) {
/* The method is part of a constructed type like Int[,].Set (). */
if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
if (m_class_get_rank (method->klass))
return TRUE;
return FALSE;
}
}
}
return TRUE;
}
static gboolean
can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
{
switch (patch_info->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
MonoMethod *method = patch_info->data.method;
return can_encode_method (acfg, method);
}
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
if (!can_encode_class (acfg, patch_info->data.klass)) {
//printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
return FALSE;
}
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
//printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
return FALSE;
}
break;
}
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
if (entry->in_mrgctx) {
if (!can_encode_method (acfg, entry->d.method))
return FALSE;
} else {
if (!can_encode_class (acfg, entry->d.klass))
return FALSE;
}
if (!can_encode_patch (acfg, entry->data))
return FALSE;
break;
}
default:
break;
}
return TRUE;
}
static gboolean
is_concrete_type (MonoType *t)
{
MonoClass *klass;
int i;
if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
return FALSE;
if (t->type == MONO_TYPE_GENERICINST) {
MonoGenericContext *orig_ctx;
MonoGenericInst *inst;
MonoType *arg;
if (!MONO_TYPE_ISSTRUCT (t))
return TRUE;
klass = mono_class_from_mono_type_internal (t);
orig_ctx = &mono_class_get_generic_class (klass)->context;
inst = orig_ctx->class_inst;
if (inst) {
for (i = 0; i < inst->type_argc; ++i) {
arg = mini_get_underlying_type (inst->type_argv [i]);
if (!is_concrete_type (arg))
return FALSE;
}
}
inst = orig_ctx->method_inst;
if (inst) {
for (i = 0; i < inst->type_argc; ++i) {
arg = mini_get_underlying_type (inst->type_argv [i]);
if (!is_concrete_type (arg))
return FALSE;
}
}
}
return TRUE;
}
static MonoMethodSignature*
get_concrete_sig (MonoMethodSignature *sig)
{
gboolean concrete = TRUE;
if (!sig->has_type_parameters)
return sig;
/* For signatures created during generic sharing, convert them to a concrete signature if possible */
MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
int i;
//printf ("%s\n", mono_signature_full_name (sig));
if (m_type_is_byref (sig->ret))
copy->ret = mono_class_get_byref_type (mono_defaults.int_class);
else
copy->ret = mini_get_underlying_type (sig->ret);
if (!is_concrete_type (copy->ret))
concrete = FALSE;
for (i = 0; i < sig->param_count; ++i) {
if (m_type_is_byref (sig->params [i])) {
MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
t = mini_get_underlying_type (t);
copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
} else {
copy->params [i] = mini_get_underlying_type (sig->params [i]);
}
if (!is_concrete_type (copy->params [i]))
concrete = FALSE;
}
copy->has_type_parameters = 0;
if (!concrete)
return NULL;
return copy;
}
/* LOCKING: Assumes the loader lock is held */
static void
add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
{
MonoMethod *wrapper;
gboolean add_in = gsharedvt_in;
gboolean add_out = gsharedvt_out;
if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
add_in = FALSE;
if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
add_out = FALSE;
if (!add_in && !add_out && !interp_in)
return;
if (mini_is_gsharedvt_variable_signature (sig))
return;
if (add_in)
g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
if (add_out)
g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
sig = get_concrete_sig (sig);
if (!sig)
return;
//printf ("%s\n", mono_signature_full_name (sig));
if (gsharedvt_in) {
wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
add_extra_method (acfg, wrapper);
}
if (gsharedvt_out) {
wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
add_extra_method (acfg, wrapper);
}
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
if (interp_in) {
wrapper = mini_get_interp_in_wrapper (sig);
add_extra_method (acfg, wrapper);
}
#endif
}
/*
* compile_method:
*
* AOT compile a given method.
* This function might be called by multiple threads, so it must be thread-safe.
*/
static void
compile_method (MonoAotCompile *acfg, MonoMethod *method)
{
MonoCompile *cfg;
MonoJumpInfo *patch_info;
gboolean skip;
int index, depth;
MonoMethod *wrapped;
gint64 jit_time_start;
JitFlags flags;
if (acfg->aot_opts.metadata_only)
return;
mono_acfg_lock (acfg);
index = get_method_index (acfg, method);
mono_acfg_unlock (acfg);
/* fixme: maybe we can also precompile wrapper methods */
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
//printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
return;
}
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
return;
wrapped = mono_marshal_method_from_wrapper (method);
if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
// FIXME: The wrapper should be generic too, but it is not
return;
if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
return;
if (acfg->aot_opts.profile_only && !g_hash_table_lookup (acfg->profile_methods, method)) {
if (acfg->aot_opts.llvm_only) {
gboolean keep = FALSE;
if (method->wrapper_type) {
/* Keep most wrappers */
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
switch (info->subtype) {
case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
break;
default:
keep = TRUE;
break;
}
}
if (always_aot (method))
keep = TRUE;
if (!keep)
return;
} else {
if (!method->is_inflated)
return;
}
}
mono_atomic_inc_i32 (&acfg->stats.mcount);
#if 0
if (method->is_generic || mono_class_is_gtd (method->klass)) {
mono_atomic_inc_i32 (&acfg->stats.genericcount);
return;
}
#endif
//acfg->aot_opts.print_skipped_methods = TRUE;
/*
* Since these methods are the only ones which are compiled with
* AOT support, and they are not used by runtime startup/shutdown code,
* the runtime will not see AOT methods during AOT compilation,so it
* does not need to support them by creating a fake GOT etc.
*/
flags = JIT_FLAG_AOT;
if (mono_aot_mode_is_full (&acfg->aot_opts))
flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
if (acfg->llvm)
flags = (JitFlags)(flags | JIT_FLAG_LLVM);
if (acfg->aot_opts.llvm_only)
flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
if (acfg->aot_opts.no_direct_calls)
flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
if (acfg->aot_opts.direct_pinvoke)
flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
if (acfg->aot_opts.interp)
flags = (JitFlags)(flags | JIT_FLAG_INTERP);
if (acfg->aot_opts.use_current_cpu)
flags = (JitFlags)(flags | JIT_FLAG_USE_CURRENT_CPU);
if (method_is_externally_callable (acfg, method))
flags = (JitFlags)(flags | JIT_FLAG_SELF_INIT);
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)
flags = (JitFlags)(flags | JIT_FLAG_CODE_EXEC_ONLY);
jit_time_start = mono_time_track_start ();
cfg = mini_method_compile (method, acfg->jit_opts, flags, 0, index);
mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
mono_atomic_inc_i32 (&acfg->stats.genericcount);
return;
}
if (cfg->exception_type != MONO_EXCEPTION_NONE) {
/* Some instances cannot be JITted due to constraints etc. */
if (!method->is_inflated)
report_loader_error (acfg, cfg->error, FALSE, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (cfg->error));
/* Let the exception happen at runtime */
return;
}
if (cfg->disable_aot) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
mono_atomic_inc_i32 (&acfg->stats.ocount);
return;
}
cfg->method_index = index;
/* Nullify patches which need no aot processing */
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_LABEL:
case MONO_PATCH_INFO_BB:
patch_info->type = MONO_PATCH_INFO_NONE;
break;
default:
break;
}
}
/* Collect method->token associations from the cfg */
mono_acfg_lock (acfg);
g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
mono_acfg_unlock (acfg);
g_hash_table_destroy (cfg->token_info_hash);
cfg->token_info_hash = NULL;
/*
* Check for absolute addresses.
*/
skip = FALSE;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_ABS:
/* unable to handle this */
skip = TRUE;
break;
default:
break;
}
}
if (skip) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
mono_atomic_inc_i32 (&acfg->stats.abscount);
return;
}
/* Lock for the rest of the code */
mono_acfg_lock (acfg);
if (cfg->gsharedvt)
acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
else if (cfg->gshared)
acfg->stats.method_categories [METHOD_CAT_INST] ++;
else if (cfg->method->wrapper_type)
acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
else
acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
/*
* Check for methods/klasses we can't encode.
*/
skip = FALSE;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
if (!can_encode_patch (acfg, patch_info))
skip = TRUE;
}
if (skip) {
if (acfg->aot_opts.print_skipped_methods)
printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
acfg->stats.ocount++;
mono_acfg_unlock (acfg);
return;
}
if (!cfg->compile_llvm)
acfg->has_jitted_code = TRUE;
if (method->is_inflated && acfg->aot_opts.log_instances) {
if (acfg->instances_logfile)
fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
else
printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
}
/* Adds generic instances referenced by this method */
/*
* The depth is used to avoid infinite loops when generic virtual recursion is
* encountered.
*/
depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_METHOD_RGCTX: {
MonoMethod *m = NULL;
if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
m = e->data->data.method;
} else {
m = patch_info->data.method;
}
if (!m)
break;
if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
if (!(mono_class_generic_sharing_enabled (m->klass) &&
mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
(!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
} else {
add_extra_method_with_depth (acfg, m, depth + 1);
add_types_from_method_header (acfg, m);
}
}
add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
}
if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
WrapperInfo *info = mono_marshal_get_wrapper_info (m);
if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
add_extra_method_with_depth (acfg, m, depth + 1);
}
break;
}
case MONO_PATCH_INFO_VTABLE: {
MonoClass *klass = patch_info->data.klass;
if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
break;
}
case MONO_PATCH_INFO_SFLDA: {
MonoClass *klass = m_field_get_parent (patch_info->data.field);
/* The .cctor needs to run at runtime. */
if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
break;
}
default:
break;
}
}
}
/* Determine whenever the method has GOT slots */
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_NONE:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
break;
case MONO_PATCH_INFO_IMAGE:
/* The assembly is stored in GOT slot 0 */
if (patch_info->data.image != acfg->image)
cfg->has_got_slots = TRUE;
break;
default:
if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
cfg->has_got_slots = TRUE;
break;
}
}
if (!cfg->has_got_slots)
mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
/* Add gsharedvt wrappers for signatures used by the method */
if (acfg->aot_opts.llvm_only) {
GSList *l;
if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
/* These only need out wrappers */
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
for (l = cfg->signatures; l; l = l->next) {
MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
/* These only need in wrappers */
add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
if (mono_aot_mode_is_interp (&acfg->aot_opts) && sig->param_count > MAX_INTERP_ENTRY_ARGS)
/* See below */
add_gsharedvt_wrappers (acfg, sig, FALSE, FALSE, TRUE);
}
for (l = cfg->interp_in_signatures; l; l = l->next) {
MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
/*
* Interpreter methods in llvmonly+interp mode are called using gsharedvt_in wrappers,
* since we already generate those in llvmonly mode. But methods with a large
* number of arguments need special processing (see interp_create_method_pointer_llvmonly),
* which only interp_in wrappers do.
*/
if (sig->param_count > MAX_INTERP_ENTRY_ARGS)
add_gsharedvt_wrappers (acfg, sig, FALSE, FALSE, TRUE);
else
add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
}
} else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
/* The interpreter uses these wrappers to call aot-ed code */
if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
}
if (cfg->llvm_only)
acfg->stats.llvm_count ++;
if (acfg->llvm && !cfg->compile_llvm && method_is_externally_callable (acfg, cfg->method)) {
/*
* This is a JITted fallback method for a method which failed LLVM compilation, emit a global
* symbol for it with the same name the LLVM method would get.
*/
char *name = mono_aot_get_mangled_method_name (cfg->method);
char *export_name = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, name);
g_hash_table_insert (acfg->export_names, cfg->method, export_name);
}
/*
* FIXME: Instead of this mess, allocate the patches from the aot mempool.
*/
/* Make a copy of the patch info which is in the mempool */
{
MonoJumpInfo *patches = NULL, *patches_end = NULL;
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
if (!patches)
patches = new_patch_info;
else
patches_end->next = new_patch_info;
patches_end = new_patch_info;
}
cfg->patch_info = patches;
}
/* Make a copy of the unwind info */
{
GSList *l, *unwind_ops;
MonoUnwindOp *op;
unwind_ops = NULL;
for (l = cfg->unwind_ops; l; l = l->next) {
op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
memcpy (op, l->data, sizeof (MonoUnwindOp));
unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
}
cfg->unwind_ops = g_slist_reverse (unwind_ops);
}
/* Make a copy of the argument/local info */
{
ERROR_DECL (error);
MonoInst **args, **locals;
MonoMethodSignature *sig;
MonoMethodHeader *header;
int i;
sig = mono_method_signature_internal (method);
args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
memcpy (args [i], cfg->args [i], sizeof (MonoInst));
}
cfg->args = args;
header = mono_method_get_header_checked (method, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
for (i = 0; i < header->num_locals; ++i) {
locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
}
mono_metadata_free_mh (header);
cfg->locals = locals;
}
/* Free some fields used by cfg to conserve memory */
mono_empty_compile (cfg);
//printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
acfg->cfgs [index] = cfg;
g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
/* Update global stats while holding a lock. */
mono_update_jit_stats (cfg);
/*
if (cfg->orig_method->wrapper_type)
g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
*/
mono_acfg_unlock (acfg);
mono_atomic_inc_i32 (&acfg->stats.ccount);
}
static mono_thread_start_return_t WINAPI
compile_thread_main (gpointer user_data)
{
MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
GPtrArray *methods = ((GPtrArray **)user_data) [1];
int i;
mono_thread_set_name_constant_ignore_error (mono_thread_internal_current (), "AOT compiler", MonoSetThreadNameFlag_Permanent);
for (i = 0; i < methods->len; ++i)
compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
return 0;
}
/* Used by the LLVM backend */
guint32
mono_aot_get_got_offset (MonoJumpInfo *ji)
{
return get_got_offset (llvm_acfg, TRUE, ji);
}
/*
* mono_aot_is_shared_got_offset:
*
* Return whenever OFFSET refers to a GOT slot which is preinitialized
* when the AOT image is loaded.
*/
gboolean
mono_aot_is_shared_got_offset (int offset)
{
return offset < llvm_acfg->nshared_got_entries;
}
gboolean
mono_aot_is_externally_callable (MonoMethod *cmethod)
{
return method_is_externally_callable (llvm_acfg, cmethod);
}
char*
mono_aot_get_method_name (MonoCompile *cfg)
{
MonoMethod *method = cfg->orig_method;
/* Use the mangled name if possible */
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
char *name, *s;
name = mono_aot_get_mangled_method_name (method);
if (llvm_acfg->aot_opts.static_link) {
/* Include the assembly name too to avoid duplicate symbol errors */
s = g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, name);
g_free (name);
return s;
} else {
return name;
}
}
}
if (llvm_acfg->aot_opts.static_link)
/* Include the assembly name too to avoid duplicate symbol errors */
return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
else
return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
}
static gboolean
append_mangled_type (GString *s, MonoType *t)
{
if (m_type_is_byref (t))
g_string_append_printf (s, "b");
switch (t->type) {
case MONO_TYPE_VOID:
g_string_append_printf (s, "void");
break;
case MONO_TYPE_BOOLEAN:
g_string_append_printf (s, "bool");
break;
case MONO_TYPE_CHAR:
g_string_append_printf (s, "char");
break;
case MONO_TYPE_I1:
g_string_append_printf (s, "i1");
break;
case MONO_TYPE_U1:
g_string_append_printf (s, "u1");
break;
case MONO_TYPE_I2:
g_string_append_printf (s, "i2");
break;
case MONO_TYPE_U2:
g_string_append_printf (s, "u2");
break;
case MONO_TYPE_I4:
g_string_append_printf (s, "i4");
break;
case MONO_TYPE_U4:
g_string_append_printf (s, "u4");
break;
case MONO_TYPE_I8:
g_string_append_printf (s, "i8");
break;
case MONO_TYPE_U8:
g_string_append_printf (s, "u8");
break;
case MONO_TYPE_I:
g_string_append_printf (s, "ii");
break;
case MONO_TYPE_U:
g_string_append_printf (s, "ui");
break;
case MONO_TYPE_R4:
g_string_append_printf (s, "fl");
break;
case MONO_TYPE_R8:
g_string_append_printf (s, "do");
break;
case MONO_TYPE_OBJECT:
g_string_append_printf (s, "obj");
break;
default: {
char *fullname = mono_type_full_name (t);
char *name = fullname;
GString *temp;
char *temps;
gboolean is_system = FALSE;
int i, len;
len = strlen ("System.");
if (strncmp (fullname, "System.", len) == 0) {
name = fullname + len;
is_system = TRUE;
}
/*
* Have to create a mangled name which is:
* - a valid symbol
* - unique
*/
temp = g_string_new ("");
len = strlen (name);
for (i = 0; i < len; ++i) {
char c = name [i];
if (isalnum (c)) {
g_string_append_c (temp, c);
} else if (c == '_') {
g_string_append_c (temp, '_');
g_string_append_c (temp, '_');
} else {
g_string_append_c (temp, '_');
if (c == '.')
g_string_append_c (temp, 'd');
else
g_string_append_printf (temp, "%x", (int)c);
}
}
temps = g_string_free (temp, FALSE);
/* Include the length to avoid different length type names aliasing each other */
g_string_append_printf (s, "cl%s%x_%s_", is_system ? "s" : "", (int)strlen (temps), temps);
g_free (temps);
g_free (fullname);
}
}
if (t->attrs)
g_string_append_printf (s, "_attrs_%d", t->attrs);
return TRUE;
}
static gboolean
append_mangled_signature (GString *s, MonoMethodSignature *sig)
{
int i;
gboolean supported;
if (sig->pinvoke)
g_string_append_printf (s, "pinvoke_");
supported = append_mangled_type (s, sig->ret);
if (!supported)
return FALSE;
g_string_append_printf (s, "_");
if (sig->hasthis)
g_string_append_printf (s, "this_");
for (i = 0; i < sig->param_count; ++i) {
supported = append_mangled_type (s, sig->params [i]);
if (!supported)
return FALSE;
}
return TRUE;
}
static void
append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
{
const char *label;
switch (wrapper_type) {
case MONO_WRAPPER_ALLOC:
label = "alloc";
break;
case MONO_WRAPPER_WRITE_BARRIER:
label = "write_barrier";
break;
case MONO_WRAPPER_STELEMREF:
label = "stelemref";
break;
case MONO_WRAPPER_OTHER:
label = "unknown";
break;
case MONO_WRAPPER_MANAGED_TO_NATIVE:
label = "man2native";
break;
case MONO_WRAPPER_SYNCHRONIZED:
label = "synch";
break;
case MONO_WRAPPER_MANAGED_TO_MANAGED:
label = "man2man";
break;
case MONO_WRAPPER_CASTCLASS:
label = "castclass";
break;
case MONO_WRAPPER_RUNTIME_INVOKE:
label = "run_invoke";
break;
case MONO_WRAPPER_DELEGATE_INVOKE:
label = "del_inv";
break;
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
label = "del_beg_inv";
break;
case MONO_WRAPPER_DELEGATE_END_INVOKE:
label = "del_end_inv";
break;
case MONO_WRAPPER_NATIVE_TO_MANAGED:
label = "native2man";
break;
default:
g_assert_not_reached ();
}
g_string_append_printf (s, "%s_", label);
}
static void
append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
{
const char *label;
switch (subtype)
{
case WRAPPER_SUBTYPE_NONE:
return;
case WRAPPER_SUBTYPE_ELEMENT_ADDR:
label = "elem_addr";
break;
case WRAPPER_SUBTYPE_STRING_CTOR:
label = "str_ctor";
break;
case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
label = "virt_stelem";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
label = "fast_mon_enter";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
label = "fast_mon_enter_4";
break;
case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
label = "fast_monitor_exit";
break;
case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
label = "ptr2struct";
break;
case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
label = "struct2ptr";
break;
case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
label = "castclass_w_cache";
break;
case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
label = "isinst_w_cache";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
label = "run_inv_norm";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
label = "run_inv_dyn";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
label = "run_inv_dir";
break;
case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
label = "run_inv_vir";
break;
case WRAPPER_SUBTYPE_ICALL_WRAPPER:
label = "icall";
break;
case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
label = "native_func_aot";
break;
case WRAPPER_SUBTYPE_PINVOKE:
label = "pinvoke";
break;
case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
label = "synch_inner";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_IN:
label = "gshared_in";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
label = "gshared_out";
break;
case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
label = "array_acc";
break;
case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
label = "generic_arry_help";
break;
case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
label = "del_inv_virt";
break;
case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
label = "del_inv_bound";
break;
case WRAPPER_SUBTYPE_INTERP_IN:
label = "interp_in";
break;
case WRAPPER_SUBTYPE_INTERP_LMF:
label = "interp_lmf";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
label = "gsharedvt_in_sig";
break;
case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
label = "gsharedvt_out_sig";
break;
case WRAPPER_SUBTYPE_AOT_INIT:
label = "aot_init";
break;
case WRAPPER_SUBTYPE_LLVM_FUNC:
label = "llvm_func";
break;
default:
g_assert_not_reached ();
}
g_string_append_printf (s, "%s_", label);
}
static char *
sanitize_mangled_string (const char *input)
{
GString *s = g_string_new ("");
for (int i=0; input [i] != '\0'; i++) {
char c = input [i];
switch (c) {
case '.':
g_string_append (s, "_dot_");
break;
case ' ':
g_string_append (s, "_");
break;
case '`':
g_string_append (s, "_bt_");
break;
case '<':
g_string_append (s, "_le_");
break;
case '>':
g_string_append (s, "_gt_");
break;
case '/':
g_string_append (s, "_sl_");
break;
case '[':
g_string_append (s, "_lbrack_");
break;
case ']':
g_string_append (s, "_rbrack_");
break;
case '(':
g_string_append (s, "_lparen_");
break;
case '-':
g_string_append (s, "_dash_");
break;
case ')':
g_string_append (s, "_rparen_");
break;
case ',':
g_string_append (s, "_comma_");
break;
case ':':
g_string_append (s, "_colon_");
break;
case '|':
g_string_append (s, "_verbar_");
break;
default:
g_string_append_c (s, c);
}
}
return g_string_free (s, FALSE);
}
static gboolean
append_mangled_klass (GString *s, MonoClass *klass)
{
char *klass_desc = mono_class_full_name (klass);
g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
g_free (klass_desc);
// Success
return TRUE;
}
static const char*
get_assembly_prefix (MonoImage *image)
{
if (mono_is_corlib_image (image))
return "corlib";
else if (!strcmp (image->assembly->aname.name, "corlib"))
return "__corlib__";
else
return image->assembly->aname.name;
}
static gboolean
append_mangled_method (GString *s, MonoMethod *method);
static gboolean
append_mangled_wrapper (GString *s, MonoMethod *method)
{
gboolean success = TRUE;
gboolean append_sig = TRUE;
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
gboolean is_corlib = mono_is_corlib_image (m_class_get_image (method->klass));
g_string_append_printf (s, "wrapper_");
/* Most wrappers are in mscorlib */
if (!is_corlib)
g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
append_mangled_wrapper_type (s, method->wrapper_type);
switch (method->wrapper_type) {
case MONO_WRAPPER_ALLOC: {
/* The GC name is saved once in MonoAotFileInfo */
g_assert (info->d.alloc.alloc_type != -1);
g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
// SlowAlloc, etc
g_string_append_printf (s, "%s_", method->name);
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
g_string_append_printf (s, "%s_", method->name);
break;
}
case MONO_WRAPPER_STELEMREF: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
else if (info->subtype == WRAPPER_SUBTYPE_LLVM_FUNC)
g_string_append_printf (s, "%d", info->d.llvm_func.subtype);
break;
}
case MONO_WRAPPER_OTHER: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
success = success && append_mangled_klass (s, method->klass);
else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
success = success && append_mangled_method (s, info->d.synchronized_inner.method);
else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
success = success && append_mangled_method (s, info->d.array_accessor.method);
else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
append_mangled_signature (s, info->d.interp_in.sig);
else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
append_mangled_signature (s, info->d.gsharedvt.sig);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
append_mangled_signature (s, info->d.gsharedvt.sig);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
g_string_append_printf (s, "%s", method->name);
else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
g_string_append_printf (s, "%s_%d_", get_assembly_prefix (m_class_get_image (method->klass)), info->d.aot_init.subtype);
append_sig = FALSE;
}
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
const char *name = method->name;
const char *prefix = "__icall_wrapper_";
if (strstr (name, prefix) == name)
name += strlen (prefix);
g_string_append_printf (s, "%s", name);
append_sig = FALSE;
} else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
success = success && append_mangled_method (s, info->d.managed_to_native.method);
} else {
g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
success = success && append_mangled_method (s, info->d.managed_to_native.method);
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m;
m = mono_marshal_method_from_wrapper (method);
g_assert (m);
g_assert (m != method);
success = success && append_mangled_method (s, m);
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
g_string_append_printf (s, "%d_", info->d.element_addr.rank);
g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
} else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
success = success && append_mangled_method (s, info->d.string_ctor.method);
} else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
success = success && append_mangled_method (s, info->d.generic_array_helper.method);
} else {
success = FALSE;
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
append_mangled_wrapper_subtype (s, info->subtype);
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
append_mangled_wrapper_subtype (s, info->subtype);
if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
success = success && append_mangled_method (s, info->d.runtime_invoke.method);
else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
if (method->is_inflated) {
/* These wrappers are identified by their class */
g_string_append_printf (s, "i_");
success = success && append_mangled_klass (s, method->klass);
} else {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
g_string_append_printf (s, "u_");
if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
append_mangled_wrapper_subtype (s, info->subtype);
g_string_append_printf (s, "u_sigstart");
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
g_assert (info);
success = success && append_mangled_method (s, info->d.native_to_managed.method);
success = success && append_mangled_klass (s, method->klass);
break;
}
default:
g_assert_not_reached ();
}
if (success && append_sig)
success = append_mangled_signature (s, mono_method_signature_internal (method));
return success;
}
static void
append_mangled_ginst (GString *str, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
if (i > 0)
g_string_append (str, ", ");
MonoType *type = ginst->type_argv [i];
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR: {
MonoType *constraint = NULL;
if (type->data.generic_param)
constraint = type->data.generic_param->gshared_constraint;
if (constraint) {
g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
g_string_append (str, "gshared:");
mono_type_get_desc (str, constraint, TRUE);
break;
}
// Else falls through to common case
}
default:
mono_type_get_desc (str, type, TRUE);
}
}
}
static void
append_mangled_context (GString *str, MonoGenericContext *context)
{
GString *res = g_string_new ("");
g_string_append_printf (res, "gens_");
g_string_append (res, "00");
gboolean good = context->class_inst && context->class_inst->type_argc > 0;
good = good || (context->method_inst && context->method_inst->type_argc > 0);
g_assert (good);
if (context->class_inst)
append_mangled_ginst (res, context->class_inst);
if (context->method_inst) {
if (context->class_inst)
g_string_append (res, "11");
append_mangled_ginst (res, context->method_inst);
}
g_string_append_printf (str, "gens_%s", res->str);
g_free (res);
}
static gboolean
append_mangled_method (GString *s, MonoMethod *method)
{
if (method->wrapper_type)
return append_mangled_wrapper (s, method);
if (method->is_inflated) {
g_string_append_printf (s, "inflated_");
MonoMethodInflated *imethod = (MonoMethodInflated*) method;
g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
append_mangled_context (s, &imethod->context);
g_string_append_printf (s, "_declared_by_%s_", get_assembly_prefix (m_class_get_image (imethod->declaring->klass)));
append_mangled_method (s, imethod->declaring);
} else if (method->is_generic) {
g_string_append_printf (s, "%s_", get_assembly_prefix (m_class_get_image (method->klass)));
g_string_append_printf (s, "generic_");
append_mangled_klass (s, method->klass);
g_string_append_printf (s, "_%s_", method->name);
MonoGenericContainer *container = mono_method_get_generic_container (method);
g_string_append_printf (s, "_");
append_mangled_context (s, &container->context);
return append_mangled_signature (s, mono_method_signature_internal (method));
} else {
g_string_append_printf (s, "%s", get_assembly_prefix (m_class_get_image (method->klass)));
append_mangled_klass (s, method->klass);
g_string_append_printf (s, "_%s_", method->name);
if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
g_string_free (s, TRUE);
return FALSE;
}
}
return TRUE;
}
/*
* mono_aot_get_mangled_method_name:
*
* Return a unique mangled name for METHOD, or NULL.
*/
char*
mono_aot_get_mangled_method_name (MonoMethod *method)
{
// FIXME: use static cache (mempool?)
// We call this a *lot*
GString *s = g_string_new ("aot_");
if (!append_mangled_method (s, method)) {
g_string_free (s, TRUE);
return NULL;
} else {
char *out = g_string_free (s, FALSE);
// Scrub method and class names
char *cleaned = sanitize_mangled_string (out);
g_free (out);
return cleaned;
}
}
gboolean
mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
{
return is_direct_callable (llvm_acfg, NULL, patch_info);
}
void
mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
{
MonoPltEntry *plt_entry;
plt_entry = get_plt_entry (llvm_acfg, patch_info);
plt_entry->llvm_used = FALSE;
}
char*
mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
{
const char *sym = NULL;
if (llvm_acfg->aot_opts.direct_icalls) {
if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
/* Call to a C function implementing a jit icall */
sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
} else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
MonoMethod *method = (MonoMethod *)data;
if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
sym = lookup_icall_symbol_name_aot (method);
else if (llvm_acfg->aot_opts.direct_pinvoke)
sym = get_pinvoke_import (llvm_acfg, method);
} else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
char const * const name = info->c_symbol;
if (name && info->func == info->wrapper)
sym = name;
}
if (sym)
return g_strdup (sym);
}
return NULL;
}
char*
mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
{
MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
MonoPltEntry *plt_entry;
const char *sym = NULL;
ji->type = type;
ji->data.target = data;
if (!can_encode_patch (llvm_acfg, ji))
return NULL;
if (llvm_acfg->aot_opts.direct_icalls) {
if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
/* Call to a C function implementing a jit icall */
sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
} else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
MonoMethod *method = (MonoMethod *)data;
if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
sym = lookup_icall_symbol_name_aot (method);
}
if (sym)
return g_strdup (sym);
}
plt_entry = get_plt_entry (llvm_acfg, ji);
plt_entry->llvm_used = TRUE;
#if defined(TARGET_MACH)
return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
#else
return g_strdup (plt_entry->llvm_symbol);
#endif
}
int
mono_aot_get_method_index (MonoMethod *method)
{
g_assert (llvm_acfg);
return get_method_index (llvm_acfg, method);
}
MonoJumpInfo*
mono_aot_patch_info_dup (MonoJumpInfo* ji)
{
MonoJumpInfo *res;
mono_acfg_lock (llvm_acfg);
res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
mono_acfg_unlock (llvm_acfg);
return res;
}
static int
execute_system (const char * command)
{
int status = 0;
#if defined (HOST_WIN32)
// We need an extra set of quotes around the whole command to properly handle commands
// with spaces since internally the command is called through "cmd /c.
char * quoted_command = g_strdup_printf ("\"%s\"", command);
int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
status = _wsystem (wstr);
g_free (wstr);
g_free (quoted_command);
#elif defined (HAVE_SYSTEM)
status = system (command);
#else
g_assert_not_reached ();
#endif
return status;
}
#ifdef ENABLE_LLVM
/*
* emit_llvm_file:
*
* Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
* tools.
*/
static gboolean
emit_llvm_file (MonoAotCompile *acfg)
{
char *command, *opts, *tempbc, *optbc, *output_fname;
if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
if (acfg->aot_opts.no_opt)
tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
else
tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
optbc = g_strdup (acfg->aot_opts.llvm_outfile);
} else {
tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
}
mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
if (acfg->aot_opts.no_opt)
return TRUE;
/*
* FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
* a lot of time, and doesn't seem to save much space.
* The following optimizations cannot be enabled:
* - 'tailcallelim'
* - 'jump-threading' changes our blockaddress references to int constants.
* - 'basiccg' fails because it contains:
* if (CS && !isa<IntrinsicInst>(II)) {
* and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
* - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
* The opt list below was produced by taking the output of:
* llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
* then removing tailcallelim + the global opts.
* strip-dead-prototypes deletes unused intrinsics definitions.
*/
/* The dse pass is disabled because of #13734 and #17616 */
/*
* The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
* // If we have no DataLayout information around, then the size of the store
* // is inferrable from the pointee type. If they are the same type, then
* // we know that the store is safe.
* if (AA.getDataLayout() == 0 &&
* Later.Ptr->getType() == Earlier.Ptr->getType()) {
* return OverwriteComplete;
* Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
*/
if (acfg->aot_opts.llvm_only) {
// FIXME: This doesn't work yet
opts = g_strdup ("");
} else {
opts = g_strdup ("-disable-tail-calls -place-safepoints -spp-all-backedges");
}
if (acfg->aot_opts.llvm_opts) {
opts = g_strdup_printf ("%s %s", acfg->aot_opts.llvm_opts, opts);
} else if (!acfg->aot_opts.llvm_only) {
opts = g_strdup_printf ("-O2 %s", opts);
}
if (acfg->aot_opts.use_current_cpu) {
opts = g_strdup_printf ("%s -mcpu=native", opts);
}
if (acfg->aot_opts.llvm_cpu_attr) {
opts = g_strdup_printf ("%s -mattr=%s", opts, acfg->aot_opts.llvm_cpu_attr);
}
if (mono_use_fast_math) {
// same parameters are passed to llc and LLVM JIT
opts = g_strdup_printf ("%s -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math", opts);
}
command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
aot_printf (acfg, "Executing opt: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
g_free (opts);
if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
/* Nothing else to do */
return TRUE;
if (acfg->aot_opts.llvm_only) {
/* Use the stock clang from xcode */
// FIXME: arch
command = g_strdup_printf ("%s -fexceptions -fpic -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
aot_printf (acfg, "Executing clang: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
return TRUE;
}
if (!acfg->llc_args)
acfg->llc_args = g_string_new ("");
/* Verbose asm slows down llc greatly */
g_string_append (acfg->llc_args, " -asm-verbose=false");
if (acfg->aot_opts.mtriple)
g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
#if defined(TARGET_X86_64_WIN32_MSVC)
if (!acfg->aot_opts.mtriple)
g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
#endif
g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
#if defined(TARGET_AMD64) || defined(TARGET_X86)
/* This generates stack adjustments in the middle of functions breaking unwind info */
g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
#endif
#if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC) || defined(TARGET_ANDROID)
g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
#else
if (llvm_acfg->aot_opts.static_link)
g_string_append_printf (acfg->llc_args, " -relocation-model=static");
else
g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
#endif
if (acfg->llvm_owriter) {
/* Emit an object file directly */
output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
g_string_append_printf (acfg->llc_args, " -filetype=obj");
} else {
output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
}
if (acfg->aot_opts.llvm_llc) {
g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
}
if (acfg->aot_opts.use_current_cpu) {
g_string_append (acfg->llc_args, " -mcpu=native");
}
if (acfg->aot_opts.llvm_cpu_attr) {
g_string_append_printf (acfg->llc_args, " -mattr=%s", acfg->aot_opts.llvm_cpu_attr);
}
command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
g_free (output_fname);
aot_printf (acfg, "Executing llc: %s\n", command);
if (execute_system (command) != 0)
return FALSE;
return TRUE;
}
#endif
/* Set the skip flag for methods which do not need to be emitted because of dedup */
static void
dedup_skip_methods (MonoAotCompile *acfg)
{
int oindex, i;
if (acfg->aot_opts.llvm_only)
return;
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
MonoCompile *cfg;
MonoMethod *method;
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
cfg = acfg->cfgs [i];
if (!cfg)
continue;
method = cfg->orig_method;
gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
gboolean dedupable = mono_aot_can_dedup (method);
// cfg->skip is vital for LLVM to work, can't just continue in this loop
if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
mono_dedup_cache_method (acfg, method);
// Don't compile inflated methods if we're in first phase of
// dedup
//
// In second phase, we emit methods that
// are dedupable. We also emit later methods
// which are referenced by them and added later.
// For this reason, when in the dedup_include mode,
// we never set skip.
if (acfg->aot_opts.dedup)
cfg->skip = TRUE;
}
// Don't compile anything in this mode
if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
cfg->skip = TRUE;
// Compile everything in this mode
if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
cfg->skip = FALSE;
/*if (dedup_collect) {*/
/*char *name = mono_aot_get_mangled_method_name (method);*/
/*if (ignore_cfg (cfg))*/
/*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
/*else*/
/*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
/*g_free (name);*/
/*}*/
}
}
static void
emit_code (MonoAotCompile *acfg)
{
int oindex, i, prev_index;
gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
char symbol [MAX_SYMBOL_SIZE];
if (acfg->aot_opts.llvm_only)
return;
#if defined(TARGET_POWERPC64)
sprintf (symbol, ".Lgot_addr");
emit_section_change (acfg, ".text", 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
emit_pointer (acfg, acfg->got_symbol);
#endif
/*
* This global symbol is used to compute the address of each method using the
* code_offsets array. It is also used to compute the memory ranges occupied by
* AOT code, so it must be equal to the address of the first emitted method.
*/
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, "jit_code_start", TRUE);
/*
* Emit some padding so the local symbol for the first method doesn't have the
* same address as 'methods'.
*/
emit_padding (acfg, 16);
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
MonoCompile *cfg;
MonoMethod *method;
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
cfg = acfg->cfgs [i];
if (!cfg)
continue;
method = cfg->orig_method;
if (ignore_cfg (cfg))
continue;
/* Emit unbox trampoline */
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
sprintf (symbol, "ut_%d", get_method_index (acfg, method));
emit_section_change (acfg, ".text", 0);
if (acfg->thumb_mixed && cfg->compile_llvm) {
emit_set_thumb_mode (acfg);
fprintf (acfg->fp, "\n.thumb_func\n");
}
emit_label (acfg, symbol);
arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
if (acfg->thumb_mixed && cfg->compile_llvm)
emit_set_arm_mode (acfg);
if (!saved_unbox_info) {
char user_symbol [128];
GSList *unwind_ops;
sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
emit_label (acfg, "ut_end");
unwind_ops = mono_unwind_get_cie_program ();
save_unwind_info (acfg, user_symbol, unwind_ops);
mono_free_unwind_info (unwind_ops);
/* Save the unbox trampoline size */
#ifdef TARGET_AMD64
// LLVM unbox trampolines vary in size, 6 or 9 bytes,
// due to the last instruction being 2 or 5 bytes.
// There is no need to describe interior bytes of instructions
// however, so state the size as if the last instruction is size 1.
emit_int32 (acfg, 5);
#else
emit_symbol_diff (acfg, "ut_end", symbol, 0);
#endif
saved_unbox_info = TRUE;
}
}
if (cfg->compile_llvm) {
acfg->stats.llvm_count ++;
} else {
emit_method_code (acfg, cfg);
}
}
emit_section_change (acfg, ".text", 0);
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, "jit_code_end", TRUE);
/* To distinguish it from the next symbol */
emit_padding (acfg, 4);
/*
* Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
* from optimizing them away, since it doesn't see that code_offsets references them.
* JITted methods don't need this since they are referenced using assembler local
* symbols.
* FIXME: This is why write-symbols doesn't work on OSX ?
*/
if (acfg->llvm && acfg->need_no_dead_strip) {
fprintf (acfg->fp, "\n");
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
}
}
/*
* To work around linker issues, we emit a table of branches, and disassemble them at runtime.
* This is PIE code, and the linker can update it if needed.
*/
#if defined(TARGET_ANDROID) || defined(__linux__)
gboolean is_func = FALSE;
#else
gboolean is_func = TRUE;
#endif
sprintf (symbol, "method_addresses");
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
/* Emit the method address table as a table of pointers */
emit_section_change (acfg, ".data", 0);
} else {
emit_section_change (acfg, RODATA_REL_SECT, !!is_func);
}
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, symbol, is_func);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, "method_addresses_end", is_func);
emit_unset_mode (acfg);
if (acfg->need_no_dead_strip)
fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
for (i = 0; i < acfg->nmethods; ++i) {
#ifdef MONO_ARCH_AOT_SUPPORTED
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
if (!ignore_cfg (acfg->cfgs [i]))
emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
else
emit_pointer (acfg, NULL);
} else {
if (!ignore_cfg (acfg->cfgs [i])) {
arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &acfg->call_table_entry_size);
} else {
arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &acfg->call_table_entry_size);
}
}
#endif
}
sprintf (symbol, "method_addresses_end");
emit_label (acfg, symbol);
emit_line (acfg);
/* Emit a sorted table mapping methods to the index of their unbox trampolines */
sprintf (symbol, "unbox_trampolines");
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, FALSE);
prev_index = -1;
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
int index;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
index = get_method_index (acfg, method);
emit_int32 (acfg, index);
/* Make sure the table is sorted by index */
g_assert (index > prev_index);
prev_index = index;
}
}
sprintf (symbol, "unbox_trampolines_end");
emit_info_symbol (acfg, symbol, FALSE);
emit_int32 (acfg, 0);
/* Emit a separate table with the trampoline addresses/offsets */
sprintf (symbol, "unbox_trampoline_addresses");
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
/* Emit the unbox trampoline address table as a table of pointers */
emit_section_change (acfg, ".data", 0);
} else {
emit_section_change (acfg, ".text", 0);
}
emit_alignment_code (acfg, 8);
emit_info_symbol (acfg, symbol, TRUE);
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
(void)method;
if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
#ifdef MONO_ARCH_AOT_SUPPORTED
const int index = get_method_index (acfg, method);
sprintf (symbol, "ut_%d", index);
if (acfg->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
emit_pointer (acfg, symbol);
} else {
int call_size;
arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
}
#endif
}
}
emit_int32 (acfg, 0);
}
static void
emit_method_info_table (MonoAotCompile *acfg)
{
int oindex, i;
gint32 *offsets;
guint8 *method_flags;
offsets = g_new0 (gint32, acfg->nmethods);
for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
if (acfg->cfgs [i]) {
emit_method_info (acfg, acfg->cfgs [i]);
offsets [i] = acfg->cfgs [i]->method_info_offset;
} else {
offsets [i] = 0;
}
}
acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
g_free (offsets);
/* Emit a separate table for method flags, its needed at runtime */
method_flags = g_new0 (guint8, acfg->nmethods);
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i])
method_flags [acfg->cfgs [i]->method_index] = acfg->cfgs [i]->aot_method_flags;
}
emit_aot_data (acfg, MONO_AOT_TABLE_METHOD_FLAGS_TABLE, "method_flags_table", method_flags, acfg->nmethods);
}
#endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) { \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define mono_final(a,b,c) { \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
static guint
mono_aot_type_hash (MonoType *t1)
{
guint hash = t1->type;
hash |= m_type_is_byref (t1) << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.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) ^ 0;
default:
return hash;
}
}
/*
* mono_aot_method_hash:
*
* Return a hash code for methods which only depends on metadata.
*/
guint32
mono_aot_method_hash (MonoMethod *method)
{
MonoMethodSignature *sig;
MonoClass *klass;
int i, hindex;
int hashes_count;
guint32 *hashes_start, *hashes;
guint32 a, b, c;
MonoGenericInst *class_ginst = NULL;
MonoGenericInst *ginst = NULL;
/* Similar to the hash in mono_method_get_imt_slot () */
sig = mono_method_signature_internal (method);
if (mono_class_is_ginst (method->klass))
class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
if (method->is_inflated)
ginst = ((MonoMethodInflated*)method)->context.method_inst;
hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
hashes = hashes_start;
/* Some wrappers are assigned to random classes */
if (!method->wrapper_type)
klass = method->klass;
else
klass = mono_defaults.object_class;
if (!method->wrapper_type) {
char *full_name;
if (mono_class_is_ginst (klass))
full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
else
full_name = mono_type_full_name (m_class_get_byval_arg (klass));
hashes [0] = mono_metadata_str_hash (full_name);
hashes [1] = 0;
g_free (full_name);
} else {
hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
}
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && mono_marshal_get_wrapper_info (method)->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER)
/* The name might not be set correctly if DISABLE_JIT is set */
hashes [2] = mono_marshal_get_wrapper_info (method)->d.icall.jit_icall_id;
else
hashes [2] = mono_metadata_str_hash (method->name);
hashes [3] = method->wrapper_type;
hashes [4] = mono_aot_type_hash (sig->ret);
hindex = 5;
for (i = 0; i < sig->param_count; i++) {
hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
}
if (class_ginst) {
for (i = 0; i < class_ginst->type_argc; ++i)
hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
}
if (ginst) {
for (i = 0; i < ginst->type_argc; ++i)
hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
}
g_assert (hindex == hashes_count);
/* Setup internal state */
a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
/* Handle most of the hashes */
while (hashes_count > 3) {
a += hashes [0];
b += hashes [1];
c += hashes [2];
mix (a,b,c);
hashes_count -= 3;
hashes += 3;
}
/* Handle the last 3 hashes (all the case statements fall through) */
switch (hashes_count) {
case 3 : c += hashes [2];
case 2 : b += hashes [1];
case 1 : a += hashes [0];
mono_final (a,b,c);
case 0: /* nothing left to add */
break;
}
g_free (hashes_start);
return c;
}
#undef rot
#undef mix
#undef mono_final
/*
* mono_aot_get_array_helper_from_wrapper;
*
* Get the helper method in Array called by an array wrapper method.
*/
MonoMethod*
mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
{
MonoMethod *m;
const char *prefix;
MonoGenericContext ctx;
char *mname, *iname, *s, *s2, *helper_name = NULL;
prefix = "System.Collections.Generic";
s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
s2 = strstr (s, "`1.");
g_assert (s2);
s2 [0] = '\0';
iname = s;
mname = s2 + 3;
//printf ("X: %s %s\n", iname, mname);
if (!strcmp (iname, "IList"))
helper_name = g_strdup_printf ("InternalArray__%s", mname);
else
helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
g_assert (m);
g_free (helper_name);
g_free (s);
if (m->is_generic) {
ERROR_DECL (error);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (m_class_get_element_class (method->klass)) };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
m = mono_class_inflate_generic_method_checked (m, &ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
return m;
}
#if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
typedef struct HashEntry {
guint32 key, value, index;
struct HashEntry *next;
} HashEntry;
/*
* emit_extra_methods:
*
* Emit methods which are not in the METHOD table, like wrappers.
*/
static void
emit_extra_methods (MonoAotCompile *acfg)
{
int i, table_size, buf_size;
guint8 *p, *buf;
guint32 *info_offsets;
guint32 hash;
GPtrArray *table;
HashEntry *entry, *new_entry;
int nmethods, max_chain_length;
int *chain_lengths;
info_offsets = g_new0 (guint32, acfg->extra_methods->len);
/* Emit method info */
nmethods = 0;
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
if (ignore_cfg (cfg))
continue;
buf_size = 10240;
p = buf = (guint8 *)g_malloc (buf_size);
nmethods ++;
method = cfg->method_to_register;
encode_method_ref (acfg, method, p, &p);
g_assert ((p - buf) < buf_size);
info_offsets [i] = add_to_blob (acfg, buf, p - buf);
g_free (buf);
}
/*
* Construct a chained hash table for mapping indexes in extra_method_info to
* method indexes.
*/
table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
chain_lengths = g_new0 (int, table_size);
max_chain_length = 0;
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
guint32 key, value;
if (ignore_cfg (cfg))
continue;
key = info_offsets [i];
value = get_method_index (acfg, method);
hash = mono_aot_method_hash (method) % table_size;
//printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
chain_lengths [hash] ++;
max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
new_entry->key = key;
new_entry->value = value;
entry = (HashEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
g_free (chain_lengths);
//printf ("MAX: %d\n", max_chain_length);
buf_size = table->len * 12 + 4;
p = buf = (guint8 *)g_malloc (buf_size);
encode_int (table_size, p, &p);
for (i = 0; i < table->len; ++i) {
HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
encode_int (0, p, &p);
encode_int (0, p, &p);
encode_int (0, p, &p);
} else {
//g_assert (entry->key > 0);
encode_int (entry->key, p, &p);
encode_int (entry->value, p, &p);
if (entry->next)
encode_int (entry->next->index, p, &p);
else
encode_int (0, p, &p);
}
}
g_assert (p - buf <= buf_size);
/* Emit the table */
emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
g_free (buf);
/*
* Emit a table reverse mapping method indexes to their index in extra_method_info.
* This is used by mono_aot_find_jit_info ().
*/
buf_size = acfg->extra_methods->len * 8 + 4;
p = buf = (guint8 *)g_malloc (buf_size);
encode_int (acfg->extra_methods->len, p, &p);
for (i = 0; i < acfg->extra_methods->len; ++i) {
MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
encode_int (get_method_index (acfg, method), p, &p);
encode_int (info_offsets [i], p, &p);
}
emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
g_free (buf);
g_free (info_offsets);
g_ptr_array_free (table, TRUE);
}
static void
generate_aotid (guint8* aotid)
{
gpointer rand_handle;
ERROR_DECL (error);
mono_rand_open ();
rand_handle = mono_rand_init (NULL, 0);
mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
mono_error_assert_ok (error);
mono_rand_close (rand_handle);
}
static void
emit_exception_info (MonoAotCompile *acfg)
{
int i;
gint32 *offsets;
SeqPointData sp_data;
gboolean seq_points_to_file = FALSE;
offsets = g_new0 (gint32, acfg->nmethods);
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i]) {
MonoCompile *cfg = acfg->cfgs [i];
// By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
// As it is not possible to load debug data from a file its is also not possible to store it in a file.
gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
offsets [i] = cfg->ex_info_offset;
if (method_seq_points_to_file) {
if (!seq_points_to_file) {
mono_seq_point_data_init (&sp_data, acfg->nmethods);
seq_points_to_file = TRUE;
}
mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
}
} else {
offsets [i] = 0;
}
}
if (seq_points_to_file) {
char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, (const char*)NULL);
char *image_basename = g_path_get_basename (acfg->image->name);
char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
char *aot_file_path = g_build_filename (dir, aot_file, (const char*)NULL);
if (g_ensure_directory_exists (aot_file_path) == FALSE) {
fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
exit (1);
}
mono_seq_point_data_write (&sp_data, aot_file_path);
mono_seq_point_data_free (&sp_data);
g_free (aotid);
g_free (dir);
g_free (image_basename);
g_free (aot_file);
g_free (aot_file_path);
}
acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
g_free (offsets);
}
static void
emit_unwind_info (MonoAotCompile *acfg)
{
int i;
char symbol [128];
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->unwind_ops->len == 0);
return;
}
/*
* The unwind info contains a lot of duplicates so we emit each unique
* entry once, and only store the offset from the start of the table in the
* exception info.
*/
sprintf (symbol, "unwind_info");
emit_section_change (acfg, RODATA_SECT, 1);
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, TRUE);
for (i = 0; i < acfg->unwind_ops->len; ++i) {
guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
guint8 *unwind_info;
guint32 unwind_info_len;
guint8 buf [16];
guint8 *p;
unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
p = buf;
encode_value (unwind_info_len, p, &p);
emit_bytes (acfg, buf, p - buf);
emit_bytes (acfg, unwind_info, unwind_info_len);
acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
}
}
static void
emit_class_info (MonoAotCompile *acfg)
{
int i;
gint32 *offsets;
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
offsets = g_new0 (gint32, rows);
for (i = 0; i < rows; ++i)
offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, rows, 10, offsets);
g_free (offsets);
}
typedef struct ClassNameTableEntry {
guint32 token, index;
struct ClassNameTableEntry *next;
} ClassNameTableEntry;
static void
emit_class_name_table (MonoAotCompile *acfg)
{
int i, table_size, buf_size;
guint32 token, hash;
MonoClass *klass;
GPtrArray *table;
char *full_name;
guint8 *buf, *p;
ClassNameTableEntry *entry, *new_entry;
/*
* Construct a chained hash table for mapping class names to typedef tokens.
*/
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_TYPEDEF]);
table_size = g_spaced_primes_closest ((int)(rows * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
token = MONO_TOKEN_TYPE_DEF | (i + 1);
klass = mono_class_get_checked (acfg->image, token, error);
if (!klass) {
mono_error_cleanup (error);
continue;
}
full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
hash = mono_metadata_str_hash (full_name) % table_size;
g_free (full_name);
/* FIXME: Allocate from the mempool */
new_entry = g_new0 (ClassNameTableEntry, 1);
new_entry->token = token;
entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
/* Emit the table */
buf_size = table->len * 4 + 4;
p = buf = (guint8 *)g_malloc0 (buf_size);
/* FIXME: Optimize memory usage */
g_assert (table_size < 65000);
encode_int16 (table_size, p, &p);
g_assert (table->len < 65000);
for (i = 0; i < table->len; ++i) {
ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
encode_int16 (0, p, &p);
encode_int16 (0, p, &p);
} else {
encode_int16 (mono_metadata_token_index (entry->token), p, &p);
if (entry->next)
encode_int16 (entry->next->index, p, &p);
else
encode_int16 (0, p, &p);
}
g_free (entry);
}
g_assert (p - buf <= buf_size);
g_ptr_array_free (table, TRUE);
emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
g_free (buf);
}
static void
emit_image_table (MonoAotCompile *acfg)
{
int i, buf_size;
guint8 *buf, *p;
/*
* The image table is small but referenced in a lot of places.
* So we emit it at once, and reference its elements by an index.
*/
buf_size = acfg->image_table->len * 28 + 4;
for (i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
MonoAssemblyName *aname = &image->assembly->aname;
buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
}
buf = p = (guint8 *)g_malloc0 (buf_size);
encode_int (acfg->image_table->len, p, &p);
for (i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
MonoAssemblyName *aname = &image->assembly->aname;
/* FIXME: Support multi-module assemblies */
g_assert (image->assembly->image == image);
encode_string (image->assembly_name, p, &p);
encode_string (image->guid, p, &p);
encode_string (aname->culture ? aname->culture : "", p, &p);
encode_string ((const char*)aname->public_key_token, p, &p);
while (GPOINTER_TO_UINT (p) % 8 != 0)
p ++;
encode_int (aname->flags, p, &p);
encode_int (aname->major, p, &p);
encode_int (aname->minor, p, &p);
encode_int (aname->build, p, &p);
encode_int (aname->revision, p, &p);
}
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
g_free (buf);
}
static void
emit_weak_field_indexes (MonoAotCompile *acfg)
{
#ifdef ENABLE_WEAK_ATTR
GHashTable *indexes;
GHashTableIter iter;
gpointer key, value;
int buf_size;
guint8 *buf, *p;
/* Emit a table of weak field indexes, since computing these at runtime is expensive */
mono_assembly_init_weak_fields (acfg->image);
indexes = acfg->image->weak_field_indexes;
g_assert (indexes);
buf_size = (g_hash_table_size (indexes) + 1) * 4;
buf = p = (guint8 *)g_malloc0 (buf_size);
encode_int (g_hash_table_size (indexes), p, &p);
g_hash_table_iter_init (&iter, indexes);
while (g_hash_table_iter_next (&iter, &key, &value)) {
guint32 index = GPOINTER_TO_UINT (key);
encode_int (index, p, &p);
}
g_assert (p - buf <= buf_size);
emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
g_free (buf);
#else
guint8 buf [4];
guint8 *p = &buf[0];
encode_int (0, p, &p);
emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
#endif
}
static void
emit_got_info (MonoAotCompile *acfg, gboolean llvm)
{
int i, first_plt_got_patch = 0, buf_size;
guint8 *p, *buf;
guint32 *got_info_offsets;
GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
/* Add the patches needed by the PLT to the GOT */
if (!llvm) {
acfg->plt_got_offset_base = acfg->got_offset;
acfg->plt_got_info_offset_base = info->got_patches->len;
first_plt_got_patch = acfg->plt_got_info_offset_base;
for (i = 1; i < acfg->plt_offset; ++i) {
MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
g_ptr_array_add (info->got_patches, plt_entry->ji);
acfg->stats.got_slot_types [plt_entry->ji->type] ++;
}
acfg->got_offset += acfg->plt_offset;
}
/**
* FIXME:
* - optimize offsets table.
* - reduce number of exported symbols.
* - emit info for a klass only once.
* - determine when a method uses a GOT slot which is guaranteed to be already
* initialized.
* - clean up and document the code.
* - use String.Empty in class libs.
*/
/* Encode info required to decode shared GOT entries */
buf_size = info->got_patches->len * 128;
p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
if (!llvm) {
acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
/* Unused */
if (acfg->plt_offset)
acfg->plt_got_info_offsets [0] = 0;
}
for (i = 0; i < info->got_patches->len; ++i) {
MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
guint8 *p2;
p = buf;
encode_value (ji->type, p, &p);
p2 = p;
encode_patch (acfg, ji, p, &p);
acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
g_assert (p - buf <= buf_size);
got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
if (!llvm && i >= first_plt_got_patch)
acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
acfg->stats.got_info_size += p - buf;
}
/* Emit got_info_offsets table */
#ifdef MONO_ARCH_CODE_EXEC_ONLY
int got_info_offsets_to_emit = info->got_patches->len;
#else
/* No need to emit offsets for the got plt entries, the plt embeds them directly */
int got_info_offsets_to_emit = first_plt_got_patch;
#endif
acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : got_info_offsets_to_emit, 10, (gint32*)got_info_offsets);
}
static void
emit_got (MonoAotCompile *acfg)
{
char symbol [MAX_SYMBOL_SIZE];
if (acfg->aot_opts.llvm_only)
return;
/* Don't make GOT global so accesses to it don't need relocations */
sprintf (symbol, "%s", acfg->got_symbol);
#ifdef TARGET_MACH
emit_unset_mode (acfg);
fprintf (acfg->fp, ".section __DATA, __bss\n");
emit_alignment (acfg, 8);
if (acfg->llvm)
emit_info_symbol (acfg, "jit_got", FALSE);
fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
#else
emit_section_change (acfg, ".bss", 0);
emit_alignment (acfg, 8);
if (acfg->aot_opts.write_symbols)
emit_local_symbol (acfg, symbol, "got_end", FALSE);
emit_label (acfg, symbol);
if (acfg->llvm)
emit_info_symbol (acfg, "jit_got", FALSE);
if (acfg->got_offset > 0)
emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
#endif
sprintf (symbol, "got_end");
emit_label (acfg, symbol);
}
typedef struct GlobalsTableEntry {
guint32 value, index;
struct GlobalsTableEntry *next;
} GlobalsTableEntry;
#ifdef TARGET_WIN32_MSVC
#define DLL_ENTRY_POINT "DllMain"
static void
emit_library_info (MonoAotCompile *acfg)
{
// Only include for shared libraries linked directly from generated object.
if (link_shared_library (acfg)) {
char *name = NULL;
char symbol [MAX_SYMBOL_SIZE];
// Ask linker to export all global symbols.
emit_section_change (acfg, ".drectve", 0);
for (guint i = 0; i < acfg->globals->len; ++i) {
name = (char *)g_ptr_array_index (acfg->globals, i);
g_assert (name != NULL);
sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
emit_string (acfg, symbol);
}
// Emit DLLMain function, needed by MSVC linker for DLL's.
// NOTE, DllMain should not go into exports above.
emit_section_change (acfg, ".text", 0);
emit_global (acfg, DLL_ENTRY_POINT, TRUE);
emit_label (acfg, DLL_ENTRY_POINT);
// Simple implementation of DLLMain, just returning TRUE.
// For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
fprintf (acfg->fp, "movl $1, %%eax\n");
fprintf (acfg->fp, "ret\n");
// Inform linker about our dll entry function.
emit_section_change (acfg, ".drectve", 0);
emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
return;
}
}
#else
static void
emit_library_info (MonoAotCompile *acfg)
{
return;
}
#endif
static void
emit_globals (MonoAotCompile *acfg)
{
int i, table_size;
guint32 hash;
GPtrArray *table;
char symbol [1024];
GlobalsTableEntry *entry, *new_entry;
if (!acfg->aot_opts.static_link)
return;
if (acfg->aot_opts.llvm_only) {
g_assert (acfg->globals->len == 0);
return;
}
/*
* When static linking, we emit a table containing our globals.
*/
/*
* Construct a chained hash table for mapping global names to their index in
* the globals table.
*/
table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
table = g_ptr_array_sized_new (table_size);
for (i = 0; i < table_size; ++i)
g_ptr_array_add (table, NULL);
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
hash = mono_metadata_str_hash (name) % table_size;
/* FIXME: Allocate from the mempool */
new_entry = g_new0 (GlobalsTableEntry, 1);
new_entry->value = i;
entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
if (entry == NULL) {
new_entry->index = hash;
g_ptr_array_index (table, hash) = new_entry;
} else {
while (entry->next)
entry = entry->next;
entry->next = new_entry;
new_entry->index = table->len;
g_ptr_array_add (table, new_entry);
}
}
/* Emit the table */
sprintf (symbol, ".Lglobals_hash");
emit_section_change (acfg, RODATA_SECT, 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
/* FIXME: Optimize memory usage */
g_assert (table_size < 65000);
emit_int16 (acfg, table_size);
for (i = 0; i < table->len; ++i) {
GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
if (entry == NULL) {
emit_int16 (acfg, 0);
emit_int16 (acfg, 0);
} else {
emit_int16 (acfg, entry->value + 1);
if (entry->next)
emit_int16 (acfg, entry->next->index);
else
emit_int16 (acfg, 0);
}
}
/* Emit the names */
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
sprintf (symbol, "name_%d", i);
emit_section_change (acfg, RODATA_SECT, 1);
#ifdef TARGET_MACH
emit_alignment (acfg, 4);
#endif
emit_label (acfg, symbol);
emit_string (acfg, name);
}
/* Emit the globals table */
sprintf (symbol, "globals");
emit_section_change (acfg, ".data", 0);
/* This is not a global, since it is accessed by the init function */
emit_alignment (acfg, 8);
emit_info_symbol (acfg, symbol, FALSE);
sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
emit_pointer (acfg, symbol);
for (i = 0; i < acfg->globals->len; ++i) {
char *name = (char *)g_ptr_array_index (acfg->globals, i);
sprintf (symbol, "name_%d", i);
emit_pointer (acfg, symbol);
g_assert (strlen (name) < sizeof (symbol));
sprintf (symbol, "%s", name);
emit_pointer (acfg, symbol);
}
/* Null terminate the table */
emit_int32 (acfg, 0);
emit_int32 (acfg, 0);
}
static void
emit_mem_end (MonoAotCompile *acfg)
{
char symbol [128];
if (acfg->aot_opts.llvm_only)
return;
sprintf (symbol, "mem_end");
emit_section_change (acfg, ".text", 1);
emit_alignment_code (acfg, 8);
emit_label (acfg, symbol);
}
static void
init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
{
int i;
info->version = MONO_AOT_FILE_VERSION;
info->plt_got_offset_base = acfg->plt_got_offset_base;
info->plt_got_info_offset_base = acfg->plt_got_info_offset_base;
info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
info->llvm_got_size = acfg->llvm_got_offset * sizeof (target_mgreg_t);
info->plt_size = acfg->plt_offset;
info->nmethods = acfg->nmethods;
info->call_table_entry_size = acfg->call_table_entry_size;
info->nextra_methods = acfg->nextra_methods;
info->flags = acfg->flags;
info->opts = acfg->jit_opts;
info->simd_opts = acfg->simd_opts;
info->gc_name_index = acfg->gc_name_offset;
info->datafile_size = acfg->datafile_offset;
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
info->table_offsets [i] = acfg->table_offsets [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->num_trampolines [i] = acfg->num_trampolines [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->trampoline_size [i] = acfg->trampoline_size [i];
info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
int card_table_shift_bits = 0;
target_mgreg_t card_table_mask = 0;
mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
/*
* Sanity checking variables used to make sure the host and target
* environment matches when cross compiling.
*/
info->double_align = MONO_ABI_ALIGNOF (double);
info->long_align = MONO_ABI_ALIGNOF (gint64);
info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
info->card_table_shift_bits = card_table_shift_bits;
info->card_table_mask = card_table_mask;
info->tramp_page_size = acfg->tramp_page_size;
info->nshared_got_entries = acfg->nshared_got_entries;
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
memcpy(&info->aotid, acfg->image->aotid, 16);
}
static void
emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
{
char symbol [MAX_SYMBOL_SIZE];
int i, sindex;
const char **symbols;
symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
sindex = 0;
symbols [sindex ++] = acfg->got_symbol;
if (acfg->llvm) {
symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
} else {
symbols [sindex ++] = NULL;
}
/* llvm_get_method */
symbols [sindex ++] = NULL;
/* llvm_get_unbox_tramp */
symbols [sindex ++] = NULL;
/* llvm_init_aotconst */
symbols [sindex ++] = NULL;
if (!acfg->aot_opts.llvm_only) {
symbols [sindex ++] = "jit_code_start";
symbols [sindex ++] = "jit_code_end";
symbols [sindex ++] = "method_addresses";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
if (acfg->data_outfile) {
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
symbols [sindex ++] = NULL;
} else {
symbols [sindex ++] = "blob";
symbols [sindex ++] = "class_name_table";
symbols [sindex ++] = "class_info_offsets";
symbols [sindex ++] = "method_info_offsets";
symbols [sindex ++] = "ex_info_offsets";
symbols [sindex ++] = "extra_method_info_offsets";
symbols [sindex ++] = "extra_method_table";
symbols [sindex ++] = "got_info_offsets";
if (acfg->llvm)
symbols [sindex ++] = "llvm_got_info_offsets";
else
symbols [sindex ++] = NULL;
symbols [sindex ++] = "image_table";
symbols [sindex ++] = "weak_field_indexes";
symbols [sindex ++] = "method_flags_table";
}
symbols [sindex ++] = "mem_end";
symbols [sindex ++] = "assembly_guid";
symbols [sindex ++] = "runtime_version";
if (acfg->num_trampoline_got_entries) {
symbols [sindex ++] = "specific_trampolines";
symbols [sindex ++] = "static_rgctx_trampolines";
symbols [sindex ++] = "imt_trampolines";
symbols [sindex ++] = "gsharedvt_arg_trampolines";
symbols [sindex ++] = "ftnptr_arg_trampolines";
symbols [sindex ++] = "unbox_arbitrary_trampolines";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
if (acfg->aot_opts.static_link) {
symbols [sindex ++] = "globals";
} else {
symbols [sindex ++] = NULL;
}
symbols [sindex ++] = "assembly_name";
symbols [sindex ++] = "plt";
symbols [sindex ++] = "plt_end";
symbols [sindex ++] = "unwind_info";
if (!acfg->aot_opts.llvm_only) {
symbols [sindex ++] = "unbox_trampolines";
symbols [sindex ++] = "unbox_trampolines_end";
symbols [sindex ++] = "unbox_trampoline_addresses";
} else {
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
symbols [sindex ++] = NULL;
}
g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
emit_section_change (acfg, ".data", 0);
emit_alignment (acfg, 8);
emit_label (acfg, symbol);
if (!acfg->aot_opts.static_link)
emit_global (acfg, symbol, FALSE);
/* The data emitted here must match MonoAotFileInfo. */
emit_int32 (acfg, info->version);
emit_int32 (acfg, info->dummy);
/*
* We emit pointers to our data structures instead of emitting global symbols which
* point to them, to reduce the number of globals, and because using globals leads to
* various problems (i.e. arm/thumb).
*/
for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
emit_pointer (acfg, symbols [i]);
emit_int32 (acfg, info->plt_got_offset_base);
emit_int32 (acfg, info->plt_got_info_offset_base);
emit_int32 (acfg, info->got_size);
emit_int32 (acfg, info->llvm_got_size);
emit_int32 (acfg, info->plt_size);
emit_int32 (acfg, info->nmethods);
emit_int32 (acfg, info->nextra_methods);
emit_int32 (acfg, info->flags);
emit_int32 (acfg, info->opts);
emit_int32 (acfg, info->simd_opts);
emit_int32 (acfg, info->gc_name_index);
emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
emit_int32 (acfg, info->double_align);
emit_int32 (acfg, info->long_align);
emit_int32 (acfg, info->generic_tramp_num);
emit_int32 (acfg, info->card_table_shift_bits);
emit_int32 (acfg, info->card_table_mask);
emit_int32 (acfg, info->tramp_page_size);
emit_int32 (acfg, info->call_table_entry_size);
emit_int32 (acfg, info->nshared_got_entries);
emit_int32 (acfg, info->datafile_size);
emit_int32 (acfg, 0);
emit_int32 (acfg, 0);
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
emit_int32 (acfg, info->table_offsets [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->num_trampolines [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->trampoline_got_offset_base [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->trampoline_size [i]);
for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
emit_int32 (acfg, info->tramp_page_code_offsets [i]);
emit_bytes (acfg, info->aotid, 16);
if (acfg->aot_opts.static_link) {
emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
emit_alignment (acfg, sizeof (target_mgreg_t));
emit_label (acfg, acfg->static_linking_symbol);
emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
}
}
/*
* Emit a structure containing all the information not stored elsewhere.
*/
static void
emit_file_info (MonoAotCompile *acfg)
{
char *build_info;
MonoAotFileInfo *info;
if (acfg->aot_opts.bind_to_runtime_version) {
build_info = mono_get_runtime_build_info ();
emit_string_symbol (acfg, "runtime_version", build_info);
g_free (build_info);
} else {
emit_string_symbol (acfg, "runtime_version", "");
}
emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
/* Emit a string holding the assembly name */
emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
info = g_new0 (MonoAotFileInfo, 1);
init_aot_file_info (acfg, info);
if (acfg->aot_opts.static_link) {
char symbol [MAX_SYMBOL_SIZE];
char *p;
/*
* Emit a global symbol which can be passed by an embedding app to
* mono_aot_register_module (). The symbol points to a pointer to the the file info
* structure.
*/
sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
/* Get rid of characters which cannot occur in symbols */
p = symbol;
for (p = symbol; *p; ++p) {
if (!(isalnum (*p) || *p == '_'))
*p = '_';
}
acfg->static_linking_symbol = g_strdup (symbol);
}
if (acfg->llvm)
mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
else
emit_aot_file_info (acfg, info);
}
static void
emit_blob (MonoAotCompile *acfg)
{
acfg->blob_closed = TRUE;
emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
}
static void
emit_objc_selectors (MonoAotCompile *acfg)
{
int i;
char symbol [128];
if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
return;
/*
* From
* cat > foo.m << EOF
* void *ret ()
* {
* return @selector(print:);
* }
* EOF
*/
mono_img_writer_emit_unset_mode (acfg->w);
g_assert (acfg->fp);
fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
fprintf (acfg->fp, ".align 3\n");
for (i = 0; i < acfg->objc_selectors->len; ++i) {
sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
emit_label (acfg, symbol);
sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
emit_pointer (acfg, symbol);
}
fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
for (i = 0; i < acfg->objc_selectors->len; ++i) {
fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
}
fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
fprintf (acfg->fp, ".align 3\n");
fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
fprintf (acfg->fp, ".long 0\n");
fprintf (acfg->fp, ".long 16\n");
}
static void
emit_dwarf_info (MonoAotCompile *acfg)
{
#ifdef EMIT_DWARF_INFO
int i;
char symbol2 [128];
/* DIEs for methods */
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
// FIXME: LLVM doesn't define .Lme_...
if (cfg->compile_llvm)
continue;
sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
MonoDebugMethodJitInfo *jit_debug_info = mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ());
mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, jit_debug_info);
mono_debug_free_method_jit_info (jit_debug_info);
}
#endif
}
#ifdef EMIT_WIN32_CODEVIEW_INFO
typedef struct _CodeViewSubSectionData
{
gchar *start_section;
gchar *end_section;
gchar *start_section_record;
gchar *end_section_record;
int section_type;
int section_record_type;
int section_id;
} CodeViewSubsectionData;
typedef struct _CodeViewCompilerVersion
{
gint major;
gint minor;
gint revision;
gint patch;
} CodeViewCompilerVersion;
#define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
#define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
#define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
#define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
#define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
#define CODEVIEW_CPU_TYPE 0x0
#define CODEVIEW_MAGIC_HEADER 0x4
static void
codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
{
g_free (section_data->start_section);
g_free (section_data->end_section);
g_free (section_data->start_section_record);
g_free (section_data->end_section_record);
memset (section_data, 0, sizeof (CodeViewSubsectionData));
}
static void
codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
{
gint values[4] = { 0 };
gint *value = values;
while (*version && (value < values + G_N_ELEMENTS (values))) {
if (isdigit (*version)) {
*value *= 10;
*value += *version - '0';
}
else if (*version == '.') {
value++;
}
version++;
}
data->major = values[0];
data->minor = values[1];
data->revision = values[2];
data->patch = values[3];
}
static void
emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
{
// Starting a new subsection, clear old data.
codeview_clear_subsection_data (section_data);
// Keep subsection data.
section_data->section_id = section_id;
section_data->section_type = section_type;
section_data->section_record_type = section_record_type;
// Allocate all labels used in subsection.
section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
// Subsection type, function symbol.
emit_int32 (acfg, section_data->section_type);
// Subsection size.
emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
emit_label (acfg, section_data->start_section);
// Subsection record size.
fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
emit_label (acfg, section_data->start_section_record);
// Subsection record type.
emit_int16 (acfg, section_record_type);
}
static void
emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
{
g_assert (section_data->start_section);
g_assert (section_data->end_section);
g_assert (section_data->start_section_record);
g_assert (section_data->end_section_record);
emit_label (acfg, section_data->end_section_record);
if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
// Emit record length.
emit_int16 (acfg, 2);
// Emit specific record type end.
emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
}
emit_label (acfg, section_data->end_section);
// Next subsection needs to be 4 byte aligned.
emit_alignment (acfg, 4);
*section_id = section_data->section_id + 1;
codeview_clear_subsection_data (section_data);
}
inline static void
emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
{
emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
}
inline static void
emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
{
emit_codeview_end_subsection (acfg, section_data, section_id);
}
static void
emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
{
CodeViewSubsectionData section_data = { 0 };
CodeViewCompilerVersion compiler_version = { 0 };
// Start new compiler record subsection.
emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, §ion_data);
emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
emit_int16 (acfg, CODEVIEW_CPU_TYPE);
// Get compiler version information.
codeview_parse_compiler_version (VERSION, &compiler_version);
// Compiler frontend version, 4 digits.
emit_int16 (acfg, compiler_version.major);
emit_int16 (acfg, compiler_version.minor);
emit_int16 (acfg, compiler_version.revision);
emit_int16 (acfg, compiler_version.patch);
// Compiler backend version, 4 digits (currently same as frontend).
emit_int16 (acfg, compiler_version.major);
emit_int16 (acfg, compiler_version.minor);
emit_int16 (acfg, compiler_version.revision);
emit_int16 (acfg, compiler_version.patch);
// Compiler string.
emit_string (acfg, "Mono AOT compiler");
// Done with section.
emit_codeview_end_symbol_subsection (acfg, §ion_data, section_id);
}
static void
emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
{
CodeViewSubsectionData section_data = { 0 };
gchar *full_method_name = NULL;
// Start new function record subsection.
emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, §ion_data);
// Emit 3 int 0 byte padding, currently not used.
emit_zero_bytes (acfg, sizeof (int) * 3);
// Emit size of function.
emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
// Emit 3 int 0 byte padding, currently not used.
emit_zero_bytes (acfg, sizeof (int) * 3);
// Emit reallocation info.
fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
fprintf (acfg->fp, "\t.secidx %s\n", symbol);
// Emit flag, currently not used.
emit_zero_bytes (acfg, 1);
// Emit function name, exclude signature since it should be described by own metadata.
full_method_name = mono_method_full_name (method, FALSE);
emit_string (acfg, full_method_name ? full_method_name : "");
g_free (full_method_name);
// Done with section.
emit_codeview_end_symbol_subsection (acfg, §ion_data, section_id);
}
static void
emit_codeview_info (MonoAotCompile *acfg)
{
int i;
int section_id = 0;
gchar symbol_buffer[MAX_SYMBOL_SIZE];
// Emit codeview debug info section
emit_section_change (acfg, ".debug$S", 0);
// Emit magic header.
emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
emit_codeview_compiler_info (acfg, §ion_id);
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg = acfg->cfgs[i];
if (!cfg || COMPILE_LLVM (cfg))
continue;
int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
emit_codeview_function_info (acfg, cfg->method, §ion_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
}
}
#else
static void
emit_codeview_info (MonoAotCompile *acfg)
{
}
#endif /* EMIT_WIN32_CODEVIEW_INFO */
#ifdef EMIT_WIN32_UNWIND_INFO
static UnwindInfoSectionCacheItem *
get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
UnwindInfoSectionCacheItem *item = NULL;
if (!acfg->unwind_info_section_cache)
acfg->unwind_info_section_cache = g_list_alloc ();
PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
// Search for unwind info in cache.
GList *list = acfg->unwind_info_section_cache;
int list_size = 0;
while (list && list->data) {
item = (UnwindInfoSectionCacheItem*)list->data;
if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
// Cache hit, return cached item.
return item;
}
list = list->next;
list_size++;
}
// Add to cache.
if (acfg->unwind_info_section_cache) {
item = g_new0 (UnwindInfoSectionCacheItem, 1);
if (item) {
// Format .xdata section label for function, used to get unwind info address RVA.
// Since the unwind info is similar for most functions, the symbol will be reused.
item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
// Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
//over ownership of unwind info.
item->unwind_info = unwind_info;
// Needs to be emitted once.
item->xdata_section_emitted = FALSE;
// Prepend to beginning of list to speed up inserts.
acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
}
}
return item;
}
static void
free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
{
GList *list = acfg->unwind_info_section_cache;
while (list) {
UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
if (item) {
g_free (item->xdata_section_label);
mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
g_free (item);
list->data = NULL;
}
list = list->next;
}
g_list_free (acfg->unwind_info_section_cache);
acfg->unwind_info_section_cache = NULL;
}
static void
emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
{
// Emit the unwind info struct.
emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
// Emit all unwind codes encoded in unwind info struct.
PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
while (current_unwind_node < last_unwind_node) {
guint8 node_count = 0;
switch (current_unwind_node->UnwindOp) {
case UWOP_PUSH_NONVOL:
case UWOP_ALLOC_SMALL:
case UWOP_SET_FPREG:
case UWOP_PUSH_MACHFRAME:
node_count = 1;
break;
case UWOP_SAVE_NONVOL:
case UWOP_SAVE_XMM128:
node_count = 2;
break;
case UWOP_SAVE_NONVOL_FAR:
case UWOP_SAVE_XMM128_FAR:
node_count = 3;
break;
case UWOP_ALLOC_LARGE:
if (current_unwind_node->OpInfo == 0)
node_count = 2;
else
node_count = 3;
break;
default:
g_assert (!"Unknown unwind opcode.");
}
while (node_count > 0) {
g_assert (current_unwind_node < last_unwind_node);
//Emit current node.
emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
node_count--;
current_unwind_node++;
}
}
}
// Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
// .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
// UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
// .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
static void
emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
{
char *pdata_section_label = NULL;
int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
temp_prefix_len = 0;
}
// Format .pdata section label for function.
pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
// Emit .pdata section.
emit_section_change (acfg, ".pdata", 0);
emit_alignment (acfg, sizeof (DWORD));
emit_label (acfg, pdata_section_label);
// Emit function start address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
// Emit function end address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
// Emit unwind info address RVA.
fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
if (!cache_item->xdata_section_emitted) {
// Emit .xdata section.
emit_section_change (acfg, ".xdata", 0);
emit_alignment (acfg, sizeof (DWORD));
emit_label (acfg, cache_item->xdata_section_label);
// Emit unwind info into .xdata section.
emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
cache_item->xdata_section_emitted = TRUE;
}
g_free (pdata_section_label);
}
#endif
static gboolean
should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
{
#ifdef TARGET_WASM
if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
/* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
return FALSE;
#endif
if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Volatile"))
/* Read<T>/Write<T> are not needed and cause JIT failures */
return FALSE;
return TRUE;
}
static gboolean
collect_methods (MonoAotCompile *acfg)
{
int mindex, i;
MonoImage *image = acfg->image;
/* Collect methods */
int rows = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
for (i = 0; i < rows; ++i) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
if (!method) {
aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
return FALSE;
}
/* Load all methods eagerly to skip the slower lazy loading code */
mono_class_setup_methods (method->klass);
if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
/* Compile the wrapper instead */
/* We do this here instead of add_wrappers () because it is easy to do it here */
MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
method = wrapper;
}
/* FIXME: Some mscorlib methods don't have debug info */
/*
if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
if (!mono_debug_lookup_method (method)) {
fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
exit (1);
}
}
}
*/
if (method->is_generic || mono_class_is_gtd (method->klass)) {
/* Compile the ref shared version instead */
method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
if (!method) {
aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
mono_error_cleanup (error);
return FALSE;
}
}
/* Since we add the normal methods first, their index will be equal to their zero based token index */
add_method_with_index (acfg, method, i, FALSE);
acfg->method_index ++;
}
/* gsharedvt methods */
rows = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]);
for (mindex = 0; mindex < rows; ++mindex) {
ERROR_DECL (error);
MonoMethod *method;
guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
if (!(acfg->jit_opts & MONO_OPT_GSHAREDVT))
continue;
method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
MonoMethod *gshared;
gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
add_extra_method (acfg, gshared);
}
}
if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
add_generic_instances (acfg);
if (mono_aot_mode_is_full (&acfg->aot_opts))
add_wrappers (acfg);
return TRUE;
}
static void
compile_methods (MonoAotCompile *acfg)
{
int i, methods_len;
if (acfg->aot_opts.nthreads > 0) {
GPtrArray *frag;
int len, j;
GPtrArray *threads;
MonoThreadHandle *thread_handle;
gpointer *user_data;
MonoMethod **methods;
methods_len = acfg->methods->len;
len = acfg->methods->len / acfg->aot_opts.nthreads;
g_assert (len > 0);
/*
* Partition the list of methods into fragments, and hand it to threads to
* process.
*/
threads = g_ptr_array_new ();
/* Make a copy since acfg->methods is modified by compile_method () */
methods = g_new0 (MonoMethod*, methods_len);
//memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
for (i = 0; i < methods_len; ++i)
methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
i = 0;
while (i < methods_len) {
ERROR_DECL (error);
MonoInternalThread *thread;
frag = g_ptr_array_new ();
for (j = 0; j < len; ++j) {
if (i < methods_len) {
g_ptr_array_add (frag, methods [i]);
i ++;
}
}
user_data = g_new0 (gpointer, 3);
user_data [0] = acfg;
user_data [1] = frag;
thread = mono_thread_create_internal ((MonoThreadStart)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
mono_error_assert_ok (error);
thread_handle = mono_threads_open_thread_handle (thread->handle);
g_ptr_array_add (threads, thread_handle);
}
g_free (methods);
for (i = 0; i < threads->len; ++i) {
mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
}
} else {
methods_len = 0;
}
/* Compile methods added by compile_method () or all methods if nthreads == 0 */
for (i = methods_len; i < acfg->methods->len; ++i) {
/* This can add new methods to acfg->methods */
compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
}
#ifdef ENABLE_LLVM
if (acfg->llvm)
mono_llvm_fixup_aot_module ();
#endif
}
static int
compile_asm (MonoAotCompile *acfg)
{
char *command, *objfile;
char *outfile_name, *tmp_outfile_name, *llvm_ofile;
const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
#ifdef TARGET_WIN32_MSVC
#define AS_OPTIONS "--target=x86_64-pc-windows-msvc -c -x assembler"
#elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
#define AS_OPTIONS "--64"
#elif defined(TARGET_POWERPC64)
#define AS_OPTIONS "-a64 -mppc64"
#elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
#define AS_OPTIONS "-xarch=v9"
#elif defined(TARGET_X86) && defined(TARGET_MACH)
#define AS_OPTIONS "-arch i386"
#elif defined(TARGET_X86) && !defined(TARGET_MACH)
#define AS_OPTIONS "--32"
#elif defined(MONO_ARCH_ENABLE_PTRAUTH)
#define AS_OPTIONS "-arch arm64e"
#else
#define AS_OPTIONS ""
#endif
#if defined(TARGET_OSX)
#define AS_NAME "clang"
#elif defined(TARGET_WIN32_MSVC)
#define AS_NAME "clang.exe"
#else
#define AS_NAME "as"
#endif
#ifdef TARGET_WIN32_MSVC
#define AS_OBJECT_FILE_SUFFIX "obj"
#else
#define AS_OBJECT_FILE_SUFFIX "o"
#endif
#if defined(sparc)
#define LD_NAME "ld"
#define LD_OPTIONS "-shared -G -Bsymbolic"
#elif defined(__ppc__) && defined(TARGET_MACH)
#define LD_NAME "gcc"
#define LD_OPTIONS "-dynamiclib -Wl,-Bsymbolic"
#elif defined(TARGET_AMD64) && defined(TARGET_MACH)
#define LD_NAME "clang"
#define LD_OPTIONS "--shared"
#elif defined(TARGET_ARM64) && defined(TARGET_OSX)
#define LD_NAME "clang"
#if defined(TARGET_OSX) && __has_feature(ptrauth_intrinsics)
#define LD_OPTIONS "--shared -arch arm64e"
#else
#define LD_OPTIONS "--shared"
#endif
#elif defined(TARGET_WIN32_MSVC)
#define LD_NAME "link.exe"
#define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
#define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
#elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
#define LD_NAME "gcc"
#define LD_OPTIONS "-shared -Wl,-Bsymbolic"
#elif defined(TARGET_X86) && defined(TARGET_MACH)
#define LD_NAME "clang"
#define LD_OPTIONS "-m32 -dynamiclib"
#elif defined(TARGET_X86) && !defined(TARGET_MACH)
#define LD_OPTIONS "-m elf_i386 -Bsymbolic"
#elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
#define LD_NAME "gcc"
#define LD_OPTIONS "--shared -Wl,-Bsymbolic"
#elif defined(TARGET_POWERPC64)
#define LD_OPTIONS "-m elf64ppc -Bsymbolic"
#endif
#ifndef LD_OPTIONS
#define LD_OPTIONS "-Bsymbolic"
#endif
if (acfg->aot_opts.asm_only) {
aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
if (acfg->aot_opts.static_link)
aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
if (acfg->llvm)
aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
return 0;
}
if (acfg->aot_opts.static_link) {
if (acfg->aot_opts.outfile)
objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
} else {
objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
}
#ifdef TARGET_OSX
g_string_append (acfg->as_args, "-c -x assembler ");
#endif
command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
acfg->as_args ? acfg->as_args->str : "",
wrap_path (objfile), wrap_path (acfg->tmpfname));
aot_printf (acfg, "Executing the native assembler: %s\n", command);
if (execute_system (command) != 0) {
g_free (command);
g_free (objfile);
return 1;
}
if (acfg->llvm && !acfg->llvm_owriter) {
command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
acfg->as_args ? acfg->as_args->str : "",
wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
aot_printf (acfg, "Executing the native assembler: %s\n", command);
if (execute_system (command) != 0) {
g_free (command);
g_free (objfile);
return 1;
}
}
g_free (command);
if (acfg->aot_opts.static_link) {
aot_printf (acfg, "Output file: '%s'.\n", objfile);
aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
g_free (objfile);
return 0;
}
if (acfg->aot_opts.outfile)
outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
if (acfg->llvm) {
llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
} else {
llvm_ofile = g_strdup ("");
}
/* replace the ; flags separators with spaces */
g_strdelimit (ld_flags, ';', ' ');
if (acfg->aot_opts.llvm_only)
ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
#ifdef TARGET_WIN32_MSVC
g_assert (tmp_outfile_name != NULL);
g_assert (objfile != NULL);
command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
#else
GString *str;
str = g_string_new ("");
const char *ld_binary_name = acfg->aot_opts.ld_name;
#if defined(LD_NAME)
if (ld_binary_name == NULL) {
ld_binary_name = LD_NAME;
}
g_string_append_printf (str, "%s%s %s", tool_prefix, ld_binary_name, LD_OPTIONS);
#else
if (ld_binary_name == NULL) {
ld_binary_name = "ld";
}
// Default (linux)
if (acfg->aot_opts.tool_prefix)
/* Cross compiling */
g_string_append_printf (str, "\"%s%s\" %s", tool_prefix, ld_binary_name, LD_OPTIONS);
else if (acfg->aot_opts.llvm_only)
g_string_append_printf (str, "%s", acfg->aot_opts.clangxx);
else
g_string_append_printf (str, "\"%s%s\"", tool_prefix, ld_binary_name);
g_string_append_printf (str, " -shared");
#endif
g_string_append_printf (str, " -o %s %s %s %s",
wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
#if defined(TARGET_MACH)
g_string_append_printf (str, " \"-Wl,-install_name,%s%s\"", g_path_get_basename (acfg->image->name), MONO_SOLIB_EXT);
#endif
command = g_string_free (str, FALSE);
#endif
aot_printf (acfg, "Executing the native linker: %s\n", command);
if (execute_system (command) != 0) {
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (command);
g_free (objfile);
g_free (ld_flags);
return 1;
}
g_free (command);
/*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
printf ("Stripping the binary: %s\n", com);
execute_system (com);
g_free (com);*/
#if defined(TARGET_ARM) && !defined(TARGET_MACH)
/*
* gas generates 'mapping symbols' each time code and data is mixed, which
* happens a lot in emit_and_reloc_code (), so we need to get rid of them.
*/
command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, wrap_path(tmp_outfile_name));
aot_printf (acfg, "Stripping the binary: %s\n", command);
if (execute_system (command) != 0) {
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (command);
g_free (objfile);
return 1;
}
#endif
if (0 != rename (tmp_outfile_name, outfile_name)) {
if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
/* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
unlink (outfile_name);
rename (tmp_outfile_name, outfile_name);
}
}
#if defined(TARGET_MACH)
command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
aot_printf (acfg, "Executing dsymutil: %s\n", command);
if (execute_system (command) != 0) {
return 1;
}
#endif
if (!acfg->aot_opts.save_temps)
unlink (objfile);
g_free (tmp_outfile_name);
g_free (outfile_name);
g_free (objfile);
if (acfg->aot_opts.save_temps)
aot_printf (acfg, "Retained input file.\n");
else
unlink (acfg->tmpfname);
return 0;
}
static guint8
profread_byte (FILE *infile)
{
guint8 i;
int res;
res = fread (&i, 1, 1, infile);
g_assert (res == 1);
return i;
}
static int
profread_int (FILE *infile)
{
int i, res;
res = fread (&i, 4, 1, infile);
g_assert (res == 1);
return i;
}
static char*
profread_string (FILE *infile)
{
int len, res;
char *pbuf;
len = profread_int (infile);
pbuf = (char*)g_malloc (len + 1);
res = fread (pbuf, 1, len, infile);
g_assert (res == len);
pbuf [len] = '\0';
return pbuf;
}
static void
load_profile_file (MonoAotCompile *acfg, char *filename)
{
FILE *infile;
char buf [1024];
int res, len, version;
char magic [32];
infile = fopen (filename, "rb");
if (!infile) {
fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
exit (1);
}
printf ("Using profile data file '%s'\n", filename);
sprintf (magic, AOT_PROFILER_MAGIC);
len = strlen (magic);
res = fread (buf, 1, len, infile);
magic [len] = '\0';
buf [len] = '\0';
if ((res != len) || strcmp (buf, magic) != 0) {
printf ("Profile file has wrong header: '%s'.\n", buf);
fclose (infile);
exit (1);
}
guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
version = profread_int (infile);
if (version != expected_version) {
printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
fclose (infile);
exit (1);
}
ProfileData *data = g_new0 (ProfileData, 1);
data->images = g_hash_table_new (NULL, NULL);
data->classes = g_hash_table_new (NULL, NULL);
data->ginsts = g_hash_table_new (NULL, NULL);
data->methods = g_hash_table_new (NULL, NULL);
while (TRUE) {
int type = profread_byte (infile);
int id = profread_int (infile);
if (type == AOTPROF_RECORD_NONE)
break;
switch (type) {
case AOTPROF_RECORD_IMAGE: {
ImageProfileData *idata = g_new0 (ImageProfileData, 1);
idata->name = profread_string (infile);
char *mvid = profread_string (infile);
g_free (mvid);
g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
break;
}
case AOTPROF_RECORD_GINST: {
int i;
int len = profread_int (infile);
GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
gdata->argc = len;
gdata->argv = g_new0 (ClassProfileData*, len);
for (i = 0; i < len; ++i) {
int class_id = profread_int (infile);
gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
g_assert (gdata->argv [i]);
}
g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
break;
}
case AOTPROF_RECORD_TYPE: {
int type = profread_byte (infile);
switch (type) {
case MONO_TYPE_CLASS: {
int image_id = profread_int (infile);
int ginst_id = profread_int (infile);
char *class_name = profread_string (infile);
ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
g_assert (image);
char *p = strrchr (class_name, '.');
g_assert (p);
*p = '\0';
ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
cdata->image = image;
cdata->ns = g_strdup (class_name);
cdata->name = g_strdup (p + 1);
if (ginst_id != -1) {
cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
g_assert (cdata->inst);
}
g_free (class_name);
g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
break;
}
#if 0
case MONO_TYPE_SZARRAY: {
int elem_id = profread_int (infile);
// FIXME:
break;
}
#endif
default:
g_assert_not_reached ();
break;
}
break;
}
case AOTPROF_RECORD_METHOD: {
int class_id = profread_int (infile);
int ginst_id = profread_int (infile);
int param_count = profread_int (infile);
char *method_name = profread_string (infile);
char *sig = profread_string (infile);
ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
g_assert (klass);
MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
mdata->id = id;
mdata->klass = klass;
mdata->name = method_name;
mdata->signature = sig;
mdata->param_count = param_count;
if (ginst_id != -1) {
mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
g_assert (mdata->inst);
}
g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
break;
}
default:
printf ("%d\n", type);
g_assert_not_reached ();
break;
}
}
fclose (infile);
acfg->profile_data = g_list_append (acfg->profile_data, data);
}
static void
resolve_class (ClassProfileData *cdata);
static void
resolve_ginst (GInstProfileData *inst_data)
{
int i;
if (inst_data->inst)
return;
for (i = 0; i < inst_data->argc; ++i) {
resolve_class (inst_data->argv [i]);
if (!inst_data->argv [i]->klass)
return;
}
MonoType **args = g_new0 (MonoType*, inst_data->argc);
for (i = 0; i < inst_data->argc; ++i)
args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
}
static void
resolve_class (ClassProfileData *cdata)
{
ERROR_DECL (error);
MonoClass *klass;
if (!cdata->image->image)
return;
klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
if (!klass) {
//printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
return;
}
if (cdata->inst) {
resolve_ginst (cdata->inst);
if (!cdata->inst->inst) {
/*
* The instance might not be found if its arguments are in another assembly,
* use the definition instead.
*/
cdata->klass = klass;
//printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
return;
}
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
ctx.class_inst = cdata->inst->inst;
cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
} else {
cdata->klass = klass;
}
}
/*
* Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
*/
static void
resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
{
GHashTableIter iter;
gpointer key, value;
int i;
if (!data)
return;
/* Images */
GPtrArray *assemblies = mono_alc_get_all_loaded_assemblies ();
g_hash_table_iter_init (&iter, data->images);
while (g_hash_table_iter_next (&iter, &key, &value)) {
ImageProfileData *idata = (ImageProfileData*)value;
if (!strcmp (current->aname.name, idata->name)) {
idata->image = current->image;
continue;
}
for (i = 0; i < assemblies->len; ++i) {
MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
if (!strcmp (ass->aname.name, idata->name)) {
idata->image = ass->image;
break;
}
}
}
g_ptr_array_free (assemblies, TRUE);
/* Classes */
g_hash_table_iter_init (&iter, data->classes);
while (g_hash_table_iter_next (&iter, &key, &value)) {
ClassProfileData *cdata = (ClassProfileData*)value;
if (!cdata->image->image) {
if (acfg->aot_opts.verbose)
printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
continue;
}
resolve_class (cdata);
/*
if (cdata->klass)
printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
*/
}
/* Methods */
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoClass *klass;
MonoMethod *m;
gpointer miter;
resolve_class (mdata->klass);
klass = mdata->klass->klass;
if (!klass) {
if (acfg->aot_opts.verbose)
printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
continue;
}
miter = NULL;
while ((m = mono_class_get_methods (klass, &miter))) {
ERROR_DECL (error);
if (strcmp (m->name, mdata->name))
continue;
MonoMethodSignature *sig = mono_method_signature_internal (m);
if (!sig)
continue;
if (sig->param_count != mdata->param_count)
continue;
if (mdata->inst) {
resolve_ginst (mdata->inst);
if (mdata->inst->inst) {
MonoGenericContext ctx;
memset (&ctx, 0, sizeof (ctx));
ctx.method_inst = mdata->inst->inst;
m = mono_class_inflate_generic_method_checked (m, &ctx, error);
if (!m)
continue;
sig = mono_method_signature_checked (m, error);
if (!is_ok (error)) {
mono_error_cleanup (error);
continue;
}
} else {
/* Use the generic definition */
mdata->method = m;
break;
}
}
char *sig_str = mono_signature_full_name (sig);
gboolean match = !strcmp (sig_str, mdata->signature);
g_free (sig_str);
if (!match) {
// The signature might not match for methods on gtds
if (!mono_class_is_gtd (klass))
continue;
}
//printf ("%s\n", mono_method_full_name (m, 1));
mdata->method = m;
break;
}
if (!mdata->method) {
if (acfg->aot_opts.verbose)
printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
}
}
}
static gboolean
inst_references_image (MonoGenericInst *inst, MonoImage *image)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
if (m_class_get_image (k) == image)
return TRUE;
if (mono_class_is_ginst (k)) {
MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
if (inst_references_image (kinst, image))
return TRUE;
}
}
return FALSE;
}
static gboolean
is_local_inst (MonoGenericInst *inst, MonoImage *image)
{
int i;
for (i = 0; i < inst->type_argc; ++i) {
MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
return FALSE;
}
return TRUE;
}
static void
add_profile_method (MonoAotCompile *acfg, MonoMethod *m)
{
g_hash_table_insert (acfg->profile_methods, m, m);
add_extra_method (acfg, m);
}
static void
add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
{
GHashTableIter iter;
gpointer key, value;
int count = 0;
if (!data)
return;
if (acfg->aot_opts.profile_only) {
/* Add methods referenced by the profile */
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoMethod *m = mdata->method;
if (!m)
continue;
if (m->is_inflated)
continue;
if (m_class_get_image (m->klass) != acfg->image)
continue;
add_profile_method (acfg, m);
count ++;
}
}
/*
* Add method instances 'related' to this assembly to the AOT image.
*/
g_hash_table_iter_init (&iter, data->methods);
while (g_hash_table_iter_next (&iter, &key, &value)) {
MethodProfileData *mdata = (MethodProfileData*)value;
MonoMethod *m = mdata->method;
MonoGenericContext *ctx;
if (!m)
continue;
if (!m->is_inflated)
continue;
if (mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
if (acfg->aot_opts.profile_only && m_class_get_image (m->klass) == acfg->image) {
// Add the fully shared version to its home image
add_profile_method (acfg, m);
count ++;
}
continue;
}
if (acfg->aot_opts.dedup_include) {
/* Add all instances from the profile */
add_profile_method (acfg, m);
count ++;
} else {
ctx = mono_method_get_context (m);
/* For simplicity, add instances which reference the assembly we are compiling */
if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
(ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image)))) {
//printf ("%s\n", mono_method_full_name (m, TRUE));
add_profile_method (acfg, m);
count ++;
} else if (m_class_get_image (m->klass) == acfg->image &&
((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
(ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image)))) {
/* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
//printf ("%s\n", mono_method_full_name (m, TRUE));
add_profile_method (acfg, m);
count ++;
} else {
//printf ("SKIP: %s (%s)\n", mono_method_get_full_name (m), acfg->image->name);
}
/*
* FIXME: We might skip some instances, for example:
* Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
* and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
*/
}
}
printf ("Added %d methods from profile.\n", count);
}
static void
init_got_info (GotInfo *info)
{
int i;
info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
info->got_patches = g_ptr_array_new ();
}
static MonoAotCompile*
acfg_create (MonoAssembly *ass, guint32 jit_opts)
{
MonoImage *image = ass->image;
MonoAotCompile *acfg;
acfg = g_new0 (MonoAotCompile, 1);
acfg->methods = g_ptr_array_new ();
acfg->method_indexes = g_hash_table_new (NULL, NULL);
acfg->method_depth = g_hash_table_new (NULL, NULL);
acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
acfg->image_hash = g_hash_table_new (NULL, NULL);
acfg->image_table = g_ptr_array_new ();
acfg->globals = g_ptr_array_new ();
acfg->image = image;
acfg->jit_opts = jit_opts;
acfg->mempool = mono_mempool_new ();
acfg->extra_methods = g_ptr_array_new ();
acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
acfg->unwind_ops = g_ptr_array_new ();
acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
acfg->method_order = g_ptr_array_new ();
acfg->export_names = g_hash_table_new (NULL, NULL);
acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
acfg->profile_methods = g_hash_table_new (NULL, NULL);
mono_os_mutex_init_recursive (&acfg->mutex);
init_got_info (&acfg->got_info);
init_got_info (&acfg->llvm_got_info);
method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
return acfg;
}
static void
got_info_free (GotInfo *info)
{
int i;
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
g_free (info->patch_to_got_offset_by_type);
g_hash_table_destroy (info->patch_to_got_offset);
g_ptr_array_free (info->got_patches, TRUE);
}
static void
acfg_free (MonoAotCompile *acfg)
{
int i;
mono_img_writer_destroy (acfg->w);
for (i = 0; i < acfg->nmethods; ++i)
if (acfg->cfgs [i])
mono_destroy_compile (acfg->cfgs [i]);
g_free (acfg->cfgs);
g_free (acfg->static_linking_symbol);
g_free (acfg->got_symbol);
g_free (acfg->plt_symbol);
g_ptr_array_free (acfg->methods, TRUE);
g_ptr_array_free (acfg->image_table, TRUE);
g_ptr_array_free (acfg->globals, TRUE);
g_ptr_array_free (acfg->unwind_ops, TRUE);
g_hash_table_destroy (acfg->method_indexes);
g_hash_table_destroy (acfg->method_depth);
g_hash_table_destroy (acfg->plt_offset_to_entry);
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
g_free (acfg->patch_to_plt_entry);
g_hash_table_destroy (acfg->method_to_cfg);
g_hash_table_destroy (acfg->token_info_hash);
g_hash_table_destroy (acfg->method_to_pinvoke_import);
g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
g_hash_table_destroy (acfg->image_hash);
g_hash_table_destroy (acfg->unwind_info_offsets);
g_hash_table_destroy (acfg->method_label_hash);
g_hash_table_destroy (acfg->typespec_classes);
g_hash_table_destroy (acfg->export_names);
g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
g_hash_table_destroy (acfg->klass_blob_hash);
g_hash_table_destroy (acfg->method_blob_hash);
if (acfg->blob_hash)
g_hash_table_destroy (acfg->blob_hash);
got_info_free (&acfg->got_info);
got_info_free (&acfg->llvm_got_info);
arch_free_unwind_info_section_cache (acfg);
mono_mempool_destroy (acfg->mempool);
method_to_external_icall_symbol_name = NULL;
g_free (acfg);
}
#define WRAPPER(e,n) n,
static const char* const
wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
#include "mono/metadata/wrapper-types.h"
NULL
};
static G_GNUC_UNUSED const char*
get_wrapper_type_name (int type)
{
return wrapper_type_names [type];
}
//#define DUMP_PLT
//#define DUMP_GOT
static void aot_dump (MonoAotCompile *acfg)
{
FILE *dumpfile;
char * dumpname;
JsonWriter writer;
mono_json_writer_init (&writer);
mono_json_writer_object_begin(&writer);
// Methods
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "methods");
mono_json_writer_array_begin (&writer);
int i;
for (i = 0; i < acfg->nmethods; ++i) {
MonoCompile *cfg;
MonoMethod *method;
MonoClass *klass;
cfg = acfg->cfgs [i];
if (ignore_cfg (cfg))
continue;
method = cfg->orig_method;
mono_json_writer_indent (&writer);
mono_json_writer_object_begin(&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "name");
mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "signature");
mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "code_size");
mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
klass = method->klass;
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "class");
mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "namespace");
mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "wrapper_type");
mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_end (&writer);
mono_json_writer_printf (&writer, ",\n");
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
// PLT entries
#ifdef DUMP_PLT
mono_json_writer_indent_push (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "plt");
mono_json_writer_array_begin (&writer);
for (i = 0; i < acfg->plt_offset; ++i) {
MonoPltEntry *plt_entry = NULL;
MonoJumpInfo *ji;
if (i == 0)
/*
* The first plt entry is unused.
*/
continue;
plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
ji = plt_entry->ji;
mono_json_writer_indent (&writer);
mono_json_writer_printf (&writer, "{ ");
mono_json_writer_object_key(&writer, "symbol");
mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
#endif
// GOT entries
#ifdef DUMP_GOT
mono_json_writer_indent_push (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_key(&writer, "got");
mono_json_writer_array_begin (&writer);
mono_json_writer_indent_push (&writer);
for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
mono_json_writer_indent (&writer);
mono_json_writer_printf (&writer, "{ ");
mono_json_writer_object_key(&writer, "patch_name");
mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
}
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_array_end (&writer);
mono_json_writer_printf (&writer, ",\n");
#endif
mono_json_writer_indent_pop (&writer);
mono_json_writer_indent (&writer);
mono_json_writer_object_end (&writer);
dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
dumpfile = fopen (dumpname, "w+");
g_free (dumpname);
fprintf (dumpfile, "%s", writer.text->str);
fclose (dumpfile);
mono_json_writer_destroy (&writer);
}
static const MonoJitICallId preinited_jit_icalls [] = {
MONO_JIT_ICALL_mini_llvm_init_method,
MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
MONO_JIT_ICALL_mini_llvmonly_throw_corlib_exception,
MONO_JIT_ICALL_mono_threads_state_poll,
MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
MONO_JIT_ICALL_mono_fill_method_rgctx,
MONO_JIT_ICALL_mono_fill_class_rgctx
};
static void
add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
{
if (!acfg->aot_opts.llvm_only)
get_got_offset (acfg, FALSE, ji);
get_got_offset (acfg, TRUE, ji);
}
static void
add_preinit_got_slots (MonoAotCompile *acfg)
{
MonoJumpInfo *ji;
int i;
/*
* Allocate the first few GOT entries to information which is needed frequently, or it is needed
* during method initialization etc.
*/
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_IMAGE;
ji->data.image = acfg->image;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_AOT_MODULE;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
add_preinit_slot (acfg, ji);
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
add_preinit_slot (acfg, ji);
if (!acfg->aot_opts.llvm_only) {
for (i = 0; i < TLS_KEY_NUM; i++) {
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
ji->data.jit_icall_id = mono_get_tls_key_to_jit_icall_id (i);
add_preinit_slot (acfg, ji);
}
}
/* Called by native-to-managed wrappers on possibly unattached threads */
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
ji->data.jit_icall_id = MONO_JIT_ICALL_mono_threads_attach_coop;
add_preinit_slot (acfg, ji);
for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
ji->data.jit_icall_id = preinited_jit_icalls [i];
add_preinit_slot (acfg, ji);
}
if (acfg->aot_opts.llvm_only)
acfg->nshared_got_entries = acfg->llvm_got_offset;
else
acfg->nshared_got_entries = acfg->got_offset;
g_assert (acfg->nshared_got_entries);
}
static void
mono_dedup_log_stats (MonoAotCompile *acfg)
{
GHashTableIter iter;
g_assert (acfg->dedup_stats);
if (!acfg->dedup_emit_mode)
return;
// If dedup_emit_mode, acfg is the dummy dedup module that consolidates
// deduped modules
g_hash_table_iter_init (&iter, acfg->method_to_cfg);
MonoCompile *dcfg = NULL;
MonoMethod *method = NULL;
size_t wrappers_size_saved = 0;
size_t inflated_size_saved = 0;
size_t copied_singles = 0;
int wrappers_saved = 0;
int instances_saved = 0;
int copied = 0;
while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
gchar *dedup_name = mono_aot_get_mangled_method_name (method);
guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
if (count == 0)
continue;
if (acfg->dedup_emit_mode) {
// Size *saved* is the size due to things not emitted.
if (count < 2) {
// Just moved, didn't save space / dedup
copied ++;
copied_singles += dcfg->code_len;
} else if (method->wrapper_type != MONO_WRAPPER_NONE) {
wrappers_saved ++;
wrappers_size_saved += dcfg->code_len * (count - 1);
} else {
instances_saved ++;
inflated_size_saved += dcfg->code_len * (count - 1);
}
}
if (acfg->aot_opts.dedup) {
if (method->wrapper_type != MONO_WRAPPER_NONE) {
wrappers_saved ++;
wrappers_size_saved += dcfg->code_len * count;
} else {
instances_saved ++;
inflated_size_saved += dcfg->code_len * count;
}
}
}
aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", wrappers_saved, wrappers_size_saved);
aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", instances_saved, inflated_size_saved);
if (acfg->dedup_emit_mode)
aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %" G_GSIZE_FORMAT "u bytes\n", copied, copied_singles);
g_hash_table_destroy (acfg->dedup_stats);
acfg->dedup_stats = NULL;
}
// Flush the cache to tell future calls what to skip
static void
mono_flush_method_cache (MonoAotCompile *acfg)
{
GHashTable *method_cache = acfg->dedup_cache;
char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
g_free (filename);
return;
}
acfg->dedup_cache = NULL;
FILE *cache = fopen (filename, "w");
if (!cache)
g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
GHashTableIter iter;
gchar *name = NULL;
g_hash_table_iter_init (&iter, method_cache);
gboolean cont = TRUE;
while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
int res = fprintf (cache, "%s\n", name);
cont = res >= 0;
}
// FIXME: don't assert if error when flushing
g_assert (cont);
fclose (cache);
g_free (filename);
// The keys are all in the imageset, nothing to free
// Values are just pointers to memory owned elsewhere, or sentinels
g_hash_table_destroy (method_cache);
}
// Read in what has been emitted by previous invocations,
// what can be skipped
static void
mono_read_method_cache (MonoAotCompile *acfg)
{
char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
// Only do once, when dedup_cache is null
if (acfg->dedup_cache)
goto early_exit;
if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
g_assert (acfg->dedup_stats);
// only in skip mode
if (!acfg->aot_opts.dedup)
goto early_exit;
g_assert (acfg->dedup_cache);
FILE *cache;
cache = fopen (filename, "r");
if (!cache)
goto early_exit;
// Since we do pointer comparisons, and it can't be allocated at
// the address 0x1 due to alignment, we use this as a sentinel
gpointer other_acfg_sentinel;
other_acfg_sentinel = GINT_TO_POINTER (0x1);
if (fseek (cache, 0L, SEEK_END))
goto cleanup;
size_t fileLength;
fileLength = ftell (cache);
g_assert (fileLength > 0);
if (fseek (cache, 0L, SEEK_SET))
goto cleanup;
// Avoid thousands of new malloc entries
// FIXME: allocate into imageset, so we don't need to free.
// put the other mangled names there too.
char *bulk;
bulk = g_malloc0 (fileLength * sizeof (char));
size_t offset;
offset = 0;
while (fgets (&bulk [offset], fileLength - offset, cache)) {
// strip newline
char *line = &bulk [offset];
size_t len = strlen (line);
if (len == 0)
break;
if (len >= 0 && line [len] == '\n')
line [len] = '\0';
offset += strlen (line) + 1;
g_assert (fileLength >= offset);
g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
}
cleanup:
fclose (cache);
early_exit:
g_free (filename);
return;
}
typedef struct {
GHashTable *cache;
GHashTable *stats;
gboolean emit_inflated_methods;
MonoAssembly *inflated_assembly;
} MonoAotState;
static MonoAotState *
alloc_aot_state (void)
{
MonoAotState *state = g_malloc (sizeof (MonoAotState));
// FIXME: Should this own the memory?
state->cache = g_hash_table_new (g_str_hash, g_str_equal);
state->stats = g_hash_table_new (g_str_hash, g_str_equal);
// Start in "collect mode"
state->emit_inflated_methods = FALSE;
state->inflated_assembly = NULL;
return state;
}
static void
free_aot_state (MonoAotState *astate)
{
g_hash_table_destroy (astate->cache);
g_free (astate);
}
static void
mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
{
GHashTableIter iter;
gchar *name = NULL;
MonoMethod *method = NULL;
acfg->dedup_emit_mode = TRUE;
g_hash_table_iter_init (&iter, astate->cache);
while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
add_method_full (acfg, method, TRUE, 0);
}
return;
}
static void
mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
{
if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
return;
if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
// Thread the state through when making the inflate pass
*astate = *global_aot_state;
}
if (!*astate) {
*astate = alloc_aot_state ();
*global_aot_state = *astate;
}
acfg->dedup_cache = (*astate)->cache;
acfg->dedup_stats = (*astate)->stats;
// fills out acfg->dedup_cache
if (acfg->aot_opts.dedup)
mono_read_method_cache (acfg);
if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
gchar *asm_file = NULL;
// Get the last part of the path, the filename
for (int i=0; asm_path [i] != NULL; i++)
asm_file = asm_path [i];
if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
// Save
*is_dedup_dummy = TRUE;
(*astate)->inflated_assembly = ass;
}
g_strfreev (asm_path);
} else if ((*astate)->inflated_assembly) {
*is_dedup_dummy = (ass == (*astate)->inflated_assembly);
}
}
int
mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
{
// create assembly, loop and add extra_methods
// in add_generic_instances , rip out what's in that for loop
// and apply that to this aot_state inside of mono_compile_assembly
MonoAotState *astate;
astate = *(MonoAotState **)aot_state;
g_assert (astate);
// FIXME: allow suffixes?
if (!astate->inflated_assembly) {
const char* inflate = strstr (aot_options, "dedup-inflate");
if (!inflate)
return 0;
else
g_error ("Error: mono was not given an assembly with the provided inflate name\n");
}
// Switch modes
astate->emit_inflated_methods = TRUE;
int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
*aot_state = NULL;
free_aot_state (astate);
return res;
}
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
static MonoMethodSignature * const * const interp_in_static_sigs [] = {
&mono_icall_sig_bool_ptr_int32_ptrref,
&mono_icall_sig_bool_ptr_ptrref,
&mono_icall_sig_int32_int32_ptrref,
&mono_icall_sig_int32_int32_ptr_ptrref,
&mono_icall_sig_int32_ptr_int32_ptr,
&mono_icall_sig_int32_ptr_int32_ptrref,
&mono_icall_sig_int32_ptr_ptrref,
&mono_icall_sig_object_object_ptr_ptr_ptr,
&mono_icall_sig_object,
&mono_icall_sig_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
&mono_icall_sig_ptr_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_ptrref,
&mono_icall_sig_ptr_ptr_uint32_ptrref,
&mono_icall_sig_ptr_uint32_ptrref,
&mono_icall_sig_void_object_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
&mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
&mono_icall_sig_void_ptr_ptr_ptrref,
&mono_icall_sig_void_ptr_ptrref,
&mono_icall_sig_void_ptr,
&mono_icall_sig_void_int32_ptrref,
&mono_icall_sig_void_uint32_ptrref,
&mono_icall_sig_void,
};
#else
// Common signatures for which we use interp in wrappers even in fullaot + trampolines mode
// for increased performance
static MonoMethodSignature *const * const interp_in_static_common_sigs [] = {
&mono_icall_sig_void,
&mono_icall_sig_ptr,
&mono_icall_sig_void_ptr,
&mono_icall_sig_ptr_ptr,
&mono_icall_sig_void_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr_ptr,
&mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr_ptr,
};
#endif
static void
add_interp_in_wrapper_for_sig (MonoAotCompile *acfg, MonoMethodSignature *sig)
{
MonoMethod *wrapper;
sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
sig->pinvoke = FALSE;
wrapper = mini_get_interp_in_wrapper (sig);
add_method (acfg, wrapper);
}
int
mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
{
MonoImage *image = ass->image;
int res;
MonoAotCompile *acfg;
char *p;
TV_DECLARE (atv);
TV_DECLARE (btv);
acfg = acfg_create (ass, opts);
memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
acfg->aot_opts.write_symbols = TRUE;
acfg->aot_opts.ntrampolines = 4096;
acfg->aot_opts.nrgctx_trampolines = 4096;
acfg->aot_opts.nimt_trampolines = 512;
acfg->aot_opts.nrgctx_fetch_trampolines = 128;
acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
acfg->aot_opts.nftnptr_arg_trampolines = 128;
#endif
acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
if (!acfg->aot_opts.llvm_path)
acfg->aot_opts.llvm_path = g_strdup ("");
acfg->aot_opts.temp_path = g_strdup ("");
#if defined(MONOTOUCH)&& !defined(TARGET_AMD64)
acfg->aot_opts.use_trampolines_page = TRUE;
#endif
acfg->aot_opts.clangxx = g_strdup ("clang++");
mono_aot_parse_options (aot_options, &acfg->aot_opts);
if (acfg->aot_opts.direct_extern_calls && !(acfg->aot_opts.llvm && acfg->aot_opts.static_link)) {
aot_printerrf (acfg, "The 'direct-extern-calls' option requires the 'llvm' and 'static' options.\n");
return 1;
}
// start dedup
MonoAotState *astate = NULL;
gboolean is_dedup_dummy = FALSE;
mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
// Process later
if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
return 0;
if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
acfg->dedup_collect_only = TRUE;
// end dedup
if (acfg->aot_opts.logfile) {
acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
}
if (acfg->aot_opts.data_outfile) {
acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
if (!acfg->data_outfile) {
aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
return 1;
}
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
}
//acfg->aot_opts.print_skipped_methods = TRUE;
#if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
if (acfg->jit_opts & MONO_OPT_GSHAREDVT) {
aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
return 1;
}
if (acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
return 1;
}
#else
if (acfg->aot_opts.llvm_only) {
if (!mono_aot_mode_is_interp (&acfg->aot_opts))
acfg->jit_opts |= MONO_OPT_GSHAREDVT;
} else if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
acfg->jit_opts |= MONO_OPT_GSHAREDVT;
#endif
#if !defined(ENABLE_LLVM)
if (acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
return 1;
}
if (mono_use_llvm || acfg->aot_opts.llvm) {
aot_printerrf (acfg, "--aot=llvm requires a runtime compiled with llvm support.\n");
return 1;
}
#endif
if (acfg->jit_opts & MONO_OPT_GSHAREDVT)
mono_set_generic_sharing_vt_supported (TRUE);
if (!acfg->dedup_collect_only)
aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
if (!acfg->aot_opts.deterministic)
generate_aotid ((guint8*) &acfg->image->aotid);
char *aotid = mono_guid_to_string (acfg->image->aotid);
if (!acfg->dedup_collect_only && !acfg->aot_opts.deterministic)
aot_printf (acfg, "AOTID %s\n", aotid);
g_free (aotid);
#ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
if (mono_aot_mode_is_full (&acfg->aot_opts)) {
aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
return 1;
}
#endif
if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
return 1;
}
if (acfg->aot_opts.static_link)
acfg->aot_opts.asm_writer = TRUE;
if (acfg->aot_opts.soft_debug) {
mini_debug_options.mdb_optimizations = TRUE;
mini_debug_options.gen_sdb_seq_points = TRUE;
if (!mono_debug_enabled ()) {
aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
return 1;
}
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
}
if (acfg->aot_opts.try_llvm)
acfg->aot_opts.llvm = mini_llvm_init ();
if (mono_use_llvm || acfg->aot_opts.llvm) {
acfg->llvm = TRUE;
acfg->aot_opts.asm_writer = TRUE;
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
if (acfg->aot_opts.soft_debug) {
aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
return 1;
}
mini_llvm_init ();
if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
return 1;
}
}
if (mono_aot_mode_is_full (&acfg->aot_opts)) {
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
acfg->is_full_aot = TRUE;
}
if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
acfg->is_full_aot = TRUE;
}
if (mini_safepoints_enabled ())
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
// The methods in dedup-emit amodules must be available on runtime startup
// Note: Only one such amodule can have this attribute
if (astate && astate->emit_inflated_methods)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
if (acfg->aot_opts.instances_logfile_path) {
acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
if (!acfg->instances_logfile) {
aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
return 1;
}
}
if (acfg->aot_opts.profile_files) {
GList *l;
for (l = acfg->aot_opts.profile_files; l; l = l->next) {
load_profile_file (acfg, (char*)l->data);
}
}
if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
int rows = table_info_get_rows (&acfg->image->tables [MONO_TABLE_METHOD]);
for (int method_index = 0; method_index < rows; ++method_index)
g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
}
if (mono_aot_mode_is_interp (&acfg->aot_opts) || mono_aot_mode_is_full (&acfg->aot_opts)) {
/* In interp mode, we don't need some trampolines, but this avoids having to add more conditionals at runtime */
acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.ntrampolines;
#ifdef MONO_ARCH_GSHARED_SUPPORTED
acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.nrgctx_trampolines;
#endif
acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = acfg->aot_opts.nimt_trampolines;
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
if (acfg->jit_opts & MONO_OPT_GSHAREDVT)
acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.ngsharedvt_arg_trampolines;
#endif
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = acfg->aot_opts.nftnptr_arg_trampolines;
#endif
acfg->num_trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = mono_aot_mode_is_interp (&acfg->aot_opts) && mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nunbox_arbitrary_trampolines : 0;
}
acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
arch_init (acfg);
if (mono_use_llvm || acfg->aot_opts.llvm) {
/*
* Emit all LLVM code into a separate assembly/object file and link with it
* normally.
*/
if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
acfg->llvm_owriter = TRUE;
} else if (acfg->aot_opts.llvm_outfile) {
int len = strlen (acfg->aot_opts.llvm_outfile);
if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
acfg->llvm_owriter = TRUE;
}
}
if (acfg->llvm && acfg->thumb_mixed)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
if (acfg->aot_opts.llvm_only)
acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
acfg->assembly_name_sym = g_strdup (get_assembly_prefix (acfg->image));
/* Get rid of characters which cannot occur in symbols */
for (p = acfg->assembly_name_sym; *p; ++p) {
if (!(isalnum (*p) || *p == '_'))
*p = '_';
}
acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
if (acfg->llvm) {
acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
}
acfg->method_index = 1;
if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
mono_set_partial_sharing_supported (TRUE);
if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
res = collect_methods (acfg);
if (!res)
return 1;
}
// If we're emitting all of the inflated methods into a dummy
// Assembly, then after extra_methods is set up, we're done
// in this function.
if (astate && astate->emit_inflated_methods)
mono_add_deferred_extra_methods (acfg, astate);
{
GList *l;
for (l = acfg->profile_data; l; l = l->next)
resolve_profile_data (acfg, (ProfileData*)l->data, ass);
for (l = acfg->profile_data; l; l = l->next)
add_profile_instances (acfg, (ProfileData*)l->data);
}
/* PLT offset 0 is reserved for the PLT trampoline */
acfg->plt_offset = 1;
add_preinit_got_slots (acfg);
current_acfg = acfg;
#ifdef ENABLE_LLVM
if (acfg->llvm) {
llvm_acfg = acfg;
LLVMModuleFlags flags = (LLVMModuleFlags)0;
#ifdef EMIT_DWARF_INFO
flags = LLVM_MODULE_FLAG_DWARF;
#endif
#ifdef EMIT_WIN32_CODEVIEW_INFO
flags = LLVM_MODULE_FLAG_CODEVIEW;
#endif
if (acfg->aot_opts.static_link)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
if (acfg->aot_opts.llvm_only)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
if (acfg->aot_opts.interp)
flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
add_lazy_init_wrappers (acfg);
add_method (acfg, mono_marshal_get_llvm_func_wrapper (LLVM_FUNC_WRAPPER_GC_POLL));
}
#endif
if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
add_method (acfg, wrapper);
wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
add_method (acfg, wrapper);
#ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++)
add_interp_in_wrapper_for_sig (acfg, *interp_in_static_sigs [i]);
#else
for (int i = 0; i < G_N_ELEMENTS (interp_in_static_common_sigs); i++)
add_interp_in_wrapper_for_sig (acfg, *interp_in_static_common_sigs [i]);
#endif
/* required for mixed mode */
if (strcmp (acfg->image->assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME) == 0) {
add_gc_wrappers (acfg);
for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
}
}
TV_GETTIME (atv);
compile_methods (acfg);
TV_GETTIME (btv);
acfg->stats.jit_time = TV_ELAPSED (atv, btv);
dedup_skip_methods (acfg);
if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
/* We only collected methods from this assembly */
return 0;
current_acfg = NULL;
return emit_aot_image (acfg);
}
static void
print_stats (MonoAotCompile *acfg)
{
int i;
gint64 all_sizes;
char llvm_stats_msg [256];
if (acfg->llvm && !acfg->aot_opts.llvm_only)
sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
else
strcpy (llvm_stats_msg, "");
all_sizes = acfg->stats.code_size + acfg->stats.method_info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d, BLOB: %d\n",
(int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
(int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
(int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
(int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
(int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
(int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
(int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
(int)(acfg->got_offset * sizeof (target_mgreg_t)),
(int)acfg->stats.blob_size);
aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
llvm_stats_msg,
acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
if (acfg->stats.genericcount)
aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.abscount)
aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.lmfcount)
aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
if (acfg->stats.ocount)
aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
aot_printf (acfg, "GOT slot distribution:\n");
int nslots = 0;
int size = 0;
for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
nslots += acfg->stats.got_slot_types [i];
size += acfg->stats.got_slot_info_sizes [i];
if (acfg->stats.got_slot_types [i])
aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
}
aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
aot_printf (acfg, "\nEncoding stats:\n");
aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
aot_printf (acfg, "\nMethod stats:\n");
aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
mono_dedup_log_stats (acfg);
}
static void
create_depfile (MonoAotCompile *acfg)
{
FILE *depfile;
// FIXME: Support other configurations
g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
depfile = fopen (acfg->aot_opts.depfile, "w");
g_assert (depfile);
int ntargets = 1;
char **targets = g_new0 (char*, ntargets);
targets [0] = acfg->aot_opts.llvm_outfile;
for (int tindex = 0; tindex < ntargets; ++tindex) {
fprintf (depfile, "%s: ", targets [tindex]);
for (int i = 0; i < acfg->image_table->len; i++) {
MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
fprintf (depfile, " %s", image->filename);
}
fprintf (depfile, "\n");
}
g_free (targets);
fclose (depfile);
}
static int
emit_aot_image (MonoAotCompile *acfg)
{
int i, res;
TV_DECLARE (atv);
TV_DECLARE (btv);
TV_GETTIME (atv);
#ifdef ENABLE_LLVM
if (acfg->llvm) {
if (acfg->aot_opts.asm_only) {
if (acfg->aot_opts.outfile) {
acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
acfg->tmpbasename = g_strdup (acfg->tmpfname);
} else {
acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
}
g_assert (acfg->aot_opts.llvm_outfile);
acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
if (acfg->llvm_owriter)
acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
else
acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
} else {
gchar *temp_path;
if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
temp_path = g_strdup (acfg->aot_opts.temp_path);
} else {
temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
acfg->temp_dir_to_delete = g_strdup (temp_path);
}
acfg->tmpbasename = g_build_filename (temp_path, "temp", (const char*)NULL);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
g_free (temp_path);
}
}
#endif
if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
if (acfg->aot_opts.outfile)
acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
else
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
acfg->fp = fopen (acfg->tmpfname, "w+");
} else {
if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
acfg->fp = fdopen (i, "w+");
} else {
acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", (const char*)NULL);
acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
acfg->fp = fopen (acfg->tmpfname, "w+");
}
}
if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
return 1;
}
if (acfg->fp)
acfg->w = mono_img_writer_create (acfg->fp);
/* Compute symbols for methods */
for (i = 0; i < acfg->nmethods; ++i) {
if (acfg->cfgs [i]) {
MonoCompile *cfg = acfg->cfgs [i];
int method_index = get_method_index (acfg, cfg->orig_method);
if (cfg->asm_symbol) {
// Set by method emitter in backend
if (acfg->llvm_label_prefix) {
char *old_symbol = cfg->asm_symbol;
cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
g_free (old_symbol);
}
} else if (COMPILE_LLVM (cfg)) {
cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
} else if (acfg->global_symbols || acfg->llvm) {
cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
} else {
cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
}
cfg->asm_debug_symbol = cfg->asm_symbol;
}
}
if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
/*
* CLANG supports GAS .file/.loc directives, so emit line number information this way
*/
acfg->gas_line_numbers = TRUE;
}
#ifdef EMIT_DWARF_INFO
if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
return 1;
}
acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
}
#endif /* EMIT_DWARF_INFO */
if (acfg->w)
mono_img_writer_emit_start (acfg->w);
if (acfg->dwarf)
mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
if (acfg->aot_opts.dedup)
mono_flush_method_cache (acfg);
emit_code (acfg);
emit_method_info_table (acfg);
emit_extra_methods (acfg);
emit_trampolines (acfg);
emit_class_name_table (acfg);
emit_got_info (acfg, FALSE);
if (acfg->llvm)
emit_got_info (acfg, TRUE);
emit_exception_info (acfg);
emit_unwind_info (acfg);
emit_class_info (acfg);
emit_plt (acfg);
emit_image_table (acfg);
emit_weak_field_indexes (acfg);
emit_got (acfg);
{
/*
* The managed allocators are GC specific, so can't use an AOT image created by one GC
* in another.
*/
const char *gc_name = mono_gc_get_gc_name ();
acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
}
emit_blob (acfg);
emit_objc_selectors (acfg);
emit_globals (acfg);
emit_file_info (acfg);
if (acfg->dwarf) {
emit_dwarf_info (acfg);
mono_dwarf_writer_close (acfg->dwarf);
} else {
if (!acfg->aot_opts.nodebug)
emit_codeview_info (acfg);
}
emit_mem_end (acfg);
if (acfg->need_pt_gnu_stack) {
/* This is required so the .so doesn't have an executable stack */
/* The bin writer already emits this */
fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
}
if (acfg->aot_opts.data_outfile)
fclose (acfg->data_outfile);
#ifdef ENABLE_LLVM
if (acfg->llvm) {
gboolean res;
res = emit_llvm_file (acfg);
if (!res)
return 1;
}
#endif
emit_library_info (acfg);
TV_GETTIME (btv);
acfg->stats.gen_time = TV_ELAPSED (atv, btv);
if (!acfg->aot_opts.stats)
aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
TV_GETTIME (atv);
if (acfg->w) {
res = mono_img_writer_emit_writeout (acfg->w);
if (res != 0) {
acfg_free (acfg);
return res;
}
res = compile_asm (acfg);
if (res != 0) {
acfg_free (acfg);
return res;
}
}
TV_GETTIME (btv);
acfg->stats.link_time = TV_ELAPSED (atv, btv);
if (acfg->aot_opts.stats)
print_stats (acfg);
aot_printf (acfg, "JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
if (acfg->aot_opts.depfile)
create_depfile (acfg);
if (acfg->aot_opts.dump_json)
aot_dump (acfg);
if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
execute_system (command);
g_free (command);
}
acfg_free (acfg);
return 0;
}
#else
/* AOT disabled */
void*
mono_aot_readonly_field_override (MonoClassField *field)
{
return NULL;
}
int
mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
{
return 0;
}
gboolean
mono_aot_is_shared_got_offset (int offset)
{
return FALSE;
}
gboolean
mono_aot_is_externally_callable (MonoMethod *cmethod)
{
return FALSE;
}
int
mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_can_enter_interp (MonoMethod *method)
{
return FALSE;
}
int
mono_aot_get_method_index (MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
#endif
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/mini/aot-runtime.c | /**
* \file
* mono Ahead of Time compiler
*
* Author:
* Dietmar Maurer ([email protected])
* Zoltan Varga ([email protected])
*
* (C) 2002 Ximian, Inc.
* Copyright 2003-2011 Novell, Inc.
* Copyright 2011 Xamarin, Inc.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#include <string.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#if HOST_WIN32
#include <winsock2.h>
#include <windows.h>
#endif
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include <errno.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
#endif
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/mono-endian.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-digest.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/bsearch.h>
#include <mono/utils/mono-tls-inline.h>
#include "mini.h"
#include "seq-points.h"
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "jit-icalls.h"
#include "mini-runtime.h"
#include <mono/jit/mono-private-unstable.h>
#include "llvmonly-runtime.h"
#include <mono/metadata/components.h>
#ifndef DISABLE_AOT
#ifdef MONO_ARCH_CODE_EXEC_ONLY
extern guint8* mono_aot_arch_get_plt_entry_exec_only (gpointer amodule_info, host_mgreg_t *regs, guint8 *code, guint8 *plt);
extern guint32 mono_arch_get_plt_info_offset_exec_only (gpointer amodule_info, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code, MonoAotResolvePltInfoOffset resolver, gpointer amodule);
extern void mono_arch_patch_plt_entry_exec_only (gpointer amodule_info, guint8 *code, gpointer *got, host_mgreg_t *regs, guint8 *addr);
#endif
#define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
#define JIT_INFO_MAP_BUCKET_SIZE 32
typedef struct _JitInfoMap JitInfoMap;
struct _JitInfoMap {
MonoJitInfo *jinfo;
JitInfoMap *next;
int method_index;
};
#define GOT_INITIALIZING 1
#define GOT_INITIALIZED 2
struct MonoAotModule {
char *aot_name;
/* Pointer to the Global Offset Table */
gpointer *got;
gpointer *llvm_got;
gpointer *shared_got;
GHashTable *name_cache;
GHashTable *extra_methods;
/* Maps methods to their code */
GHashTable *method_to_code;
/* Maps pointers into the method info to the methods themselves */
GHashTable *method_ref_to_method;
MonoAssemblyName *image_names;
char **image_guids;
MonoAssembly *assembly;
MonoImage **image_table;
guint32 image_table_len;
gboolean out_of_date;
gboolean plt_inited;
int got_initialized;
guint8 *mem_begin;
guint8 *mem_end;
guint8 *jit_code_start;
guint8 *jit_code_end;
guint8 *llvm_code_start;
guint8 *llvm_code_end;
guint8 *plt;
guint8 *plt_end;
guint8 *blob;
gpointer weak_field_indexes;
guint8 *method_flags_table;
/* Maps method indexes to their code */
/* Raw pointer on arm64e */
gpointer *methods;
/* Sorted array of method addresses */
gpointer *sorted_methods;
/* Method indexes for each method in sorted_methods */
int *sorted_method_indexes;
/* The length of the two tables above */
int sorted_methods_len;
guint32 *method_info_offsets;
guint32 *ex_info_offsets;
guint32 *class_info_offsets;
guint32 *got_info_offsets;
guint32 *llvm_got_info_offsets;
guint32 *methods_loaded;
guint16 *class_name_table;
guint32 *extra_method_table;
guint32 *extra_method_info_offsets;
guint32 *unbox_trampolines;
guint32 *unbox_trampolines_end;
guint32 *unbox_trampoline_addresses;
guint8 *unwind_info;
/* Maps method index -> unbox tramp */
gpointer *unbox_tramp_per_method;
/* Points to the mono EH data created by LLVM */
guint8 *mono_eh_frame;
/* Points to the data tables if MONO_AOT_FILE_FLAG_SEPARATE_DATA is set */
gpointer tables [MONO_AOT_TABLE_NUM];
/* Points to the trampolines */
guint8 *trampolines [MONO_AOT_TRAMP_NUM];
/* The first unused trampoline of each kind */
guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
gboolean use_page_trampolines;
MonoAotFileInfo info;
gpointer *globals;
MonoDl *sofile;
JitInfoMap **async_jit_info_table;
mono_mutex_t mutex;
};
typedef struct {
void *next;
unsigned char *trampolines;
unsigned char *trampolines_end;
} TrampolinePage;
static GHashTable *aot_modules;
#define mono_aot_lock() mono_os_mutex_lock (&aot_mutex)
#define mono_aot_unlock() mono_os_mutex_unlock (&aot_mutex)
static mono_mutex_t aot_mutex;
/*
* Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
* AOT modules registered by mono_aot_register_module ().
*/
static GHashTable *static_aot_modules;
/*
* Same as above, but tracks module that must be loaded before others are
* This allows us to have a "container" module which contains resources for
* other modules. Since it doesn't provide methods for a managed assembly,
* and it needs to be fully loaded by the time the other code needs it, it
* must be eagerly loaded before other modules.
*/
static char *container_assm_name;
static MonoAotModule *container_amodule;
static GHashTable *loaded_static_aot_modules;
/*
* Maps MonoJitInfo* to the aot module they belong to, this can be different
* from ji->method->klass->image's aot module for generic instances.
*/
static GHashTable *ji_to_amodule;
/* Maps method addresses to MonoAotMethodFlags */
static GHashTable *code_to_method_flags;
/* For debugging */
static gint32 mono_last_aot_method = -1;
static gboolean make_unreadable = FALSE;
static guint32 name_table_accesses = 0;
static guint32 n_pagefaults = 0;
/* Used to speed-up find_aot_module () */
static gsize aot_code_low_addr = (gssize)-1;
static gsize aot_code_high_addr = 0;
/* Stats */
static gint32 async_jit_info_size;
#ifdef MONOTOUCH
#define USE_PAGE_TRAMPOLINES (mscorlib_aot_module->use_page_trampolines)
#else
#define USE_PAGE_TRAMPOLINES 0
#endif
#define mono_aot_page_lock() mono_os_mutex_lock (&aot_page_mutex)
#define mono_aot_page_unlock() mono_os_mutex_unlock (&aot_page_mutex)
static mono_mutex_t aot_page_mutex;
static MonoAotModule *mscorlib_aot_module;
/* Embedding API hooks to load the AOT data for AOT images compiled with MONO_AOT_FILE_FLAG_SEPARATE_DATA */
static MonoLoadAotDataFunc aot_data_load_func;
static MonoFreeAotDataFunc aot_data_free_func;
static gpointer aot_data_func_user_data;
static void
init_plt (MonoAotModule *info);
static void
compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end);
static gboolean
init_method (MonoAotModule *amodule, gpointer info, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoError *error);
static MonoJumpInfo*
decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets);
static MonoMethodSignature*
decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
static void
load_container_amodule (MonoAssemblyLoadContext *alc);
static void
sort_methods (MonoAotModule *amodule);
static void
amodule_lock (MonoAotModule *amodule)
{
mono_os_mutex_lock (&amodule->mutex);
}
static void
amodule_unlock (MonoAotModule *amodule)
{
mono_os_mutex_unlock (&amodule->mutex);
}
/*
* load_image:
*
* Load one of the images referenced by AMODULE. Returns NULL if the image is not
* found, and sets @error for what happened
*/
static MonoImage *
load_image (MonoAotModule *amodule, int index, MonoError *error)
{
MonoAssembly *assembly;
MonoImageOpenStatus status;
MonoAssemblyLoadContext *alc = mono_alc_get_ambient ();
g_assert (index < amodule->image_table_len);
error_init (error);
if (amodule->image_table [index])
return amodule->image_table [index];
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s wants to load image %d: %s", amodule->aot_name, index, amodule->image_names[index].name);
if (amodule->out_of_date) {
mono_error_set_bad_image_by_name (error, amodule->aot_name, "Image out of date: %s", amodule->aot_name);
return NULL;
}
/*
* LoadFile allows loading more than one assembly with the same name.
* That means that just calling mono_assembly_load is unlikely to find
* the correct assembly (it'll just return the first one loaded). But
* we shouldn't hardcode the full assembly filepath into the AOT image,
* so it's not obvious that we can call mono_assembly_open_predicate.
*
* In the JIT, an assembly opened with LoadFile is supposed to only
* refer to already-loaded assemblies (or to GAC & MONO_PATH)
* assemblies - so nothing new should be loading. And for the
* LoadFile'd assembly itself, we can check if the name and guid of the
* current AOT module matches the wanted name and guid and just return
* the AOT module's assembly.
*/
if (!strcmp (amodule->assembly->image->guid, amodule->image_guids [index])) {
assembly = amodule->assembly;
} else if (mono_get_corlib () && !strcmp (mono_get_corlib ()->guid, amodule->image_guids [index])) {
/* This might be called before corlib is added to the root domain */
assembly = mono_get_corlib ()->assembly;
} else {
MonoAssemblyByNameRequest req;
mono_assembly_request_prepare_byname (&req, alc);
req.basedir = amodule->assembly->basedir;
assembly = mono_assembly_request_byname (&amodule->image_names [index], &req, &status);
}
if (!assembly) {
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable because dependency %s is not found.", amodule->aot_name, amodule->image_names [index].name);
mono_error_set_bad_image_by_name (error, amodule->aot_name, "module '%s' is unusable because dependency %s is not found (error %d).\n", amodule->aot_name, amodule->image_names [index].name, status);
amodule->out_of_date = TRUE;
return NULL;
}
if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s')).", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
mono_error_set_bad_image_by_name (error, amodule->aot_name, "module '%s' is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s')).", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
amodule->out_of_date = TRUE;
return NULL;
}
amodule->image_table [index] = assembly->image;
return assembly->image;
}
static gint32
decode_value (guint8 *ptr, guint8 **rptr)
{
guint8 b = *ptr;
gint32 len;
if ((b & 0x80) == 0){
len = b;
++ptr;
} else if ((b & 0x40) == 0){
len = ((b & 0x3f) << 8 | ptr [1]);
ptr += 2;
} else if (b != 0xff) {
len = ((b & 0x1f) << 24) |
(ptr [1] << 16) |
(ptr [2] << 8) |
ptr [3];
ptr += 4;
}
else {
len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
ptr += 5;
}
if (rptr)
*rptr = ptr;
//printf ("DECODE: %d.\n", len);
return len;
}
/*
* mono_aot_get_offset:
*
* Decode an offset table emitted by emit_offset_table (), returning the INDEXth
* entry.
*/
static guint32
mono_aot_get_offset (guint32 *table, int index)
{
int i, group, ngroups, index_entry_size;
int start_offset, offset, group_size;
guint8 *data_start, *p;
guint32 *index32 = NULL;
guint16 *index16 = NULL;
/* noffsets = table [0]; */
group_size = table [1];
ngroups = table [2];
index_entry_size = table [3];
group = index / group_size;
if (index_entry_size == 2) {
index16 = (guint16*)&table [4];
data_start = (guint8*)&index16 [ngroups];
p = data_start + index16 [group];
} else {
index32 = (guint32*)&table [4];
data_start = (guint8*)&index32 [ngroups];
p = data_start + index32 [group];
}
/* offset will contain the value of offsets [group * group_size] */
offset = start_offset = decode_value (p, &p);
for (i = group * group_size + 1; i <= index; ++i) {
offset += decode_value (p, &p);
}
//printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
return offset;
}
static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoGenericInst*
decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
int type_argc, i;
MonoType **type_argv;
MonoGenericInst *inst;
guint8 *p = buf;
error_init (error);
type_argc = decode_value (p, &p);
type_argv = g_new0 (MonoType*, type_argc);
for (i = 0; i < type_argc; ++i) {
MonoClass *pclass = decode_klass_ref (module, p, &p, error);
if (!pclass) {
g_free (type_argv);
return NULL;
}
type_argv [i] = m_class_get_byval_arg (pclass);
}
inst = mono_metadata_get_generic_inst (type_argc, type_argv);
g_free (type_argv);
*endbuf = p;
return inst;
}
static gboolean
decode_generic_context (MonoAotModule *amodule, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint8 *p = buf;
guint8 *p2;
guint32 offset, flags;
/* Either the class_inst or method_inst offset */
flags = decode_value (p, &p);
if (flags & 1) {
offset = decode_value (p, &p);
p2 = amodule->blob + offset;
ctx->class_inst = decode_generic_inst (amodule, p2, &p2, error);
if (!ctx->class_inst)
return FALSE;
}
if (flags & 2) {
offset = decode_value (p, &p);
p2 = amodule->blob + offset;
ctx->method_inst = decode_generic_inst (amodule, p2, &p2, error);
if (!ctx->method_inst)
return FALSE;
}
*endbuf = p;
return TRUE;
}
static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
MonoImage *image;
MonoClass *klass = NULL, *eklass;
guint32 token, rank, idx;
guint8 *p = buf;
int reftype;
error_init (error);
reftype = decode_value (p, &p);
if (reftype == 0) {
*endbuf = p;
mono_error_set_bad_image_by_name (error, module->aot_name, "Decoding a null class ref: %s", module->aot_name);
return NULL;
}
switch (reftype) {
case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
idx = decode_value (p, &p);
image = load_image (module, 0, error);
if (!image)
return NULL;
klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
break;
case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
idx = decode_value (p, &p);
image = load_image (module, decode_value (p, &p), error);
if (!image)
return NULL;
klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
break;
case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
token = decode_value (p, &p);
image = module->assembly->image;
if (!image) {
mono_error_set_bad_image_by_name (error, module->aot_name, "No image associated with the aot module: %s", module->aot_name);
return NULL;
}
klass = mono_class_get_checked (image, token, error);
break;
case MONO_AOT_TYPEREF_GINST: {
MonoClass *gclass;
MonoGenericContext ctx;
MonoType *type;
gclass = decode_klass_ref (module, p, &p, error);
if (!gclass)
return NULL;
g_assert (mono_class_is_gtd (gclass));
memset (&ctx, 0, sizeof (ctx));
guint32 offset = decode_value (p, &p);
guint8 *p2 = module->blob + offset;
ctx.class_inst = decode_generic_inst (module, p2, &p2, error);
if (!ctx.class_inst)
return NULL;
type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
if (!type)
return NULL;
klass = mono_class_from_mono_type_internal (type);
mono_metadata_free_type (type);
break;
}
case MONO_AOT_TYPEREF_VAR: {
MonoType *t = NULL;
MonoGenericContainer *container = NULL;
gboolean has_constraint = decode_value (p, &p);
if (has_constraint) {
MonoClass *par_klass;
MonoType *gshared_constraint;
gshared_constraint = decode_type (module, p, &p, error);
if (!gshared_constraint)
return NULL;
par_klass = decode_klass_ref (module, p, &p, error);
if (!par_klass)
return NULL;
t = mini_get_shared_gparam (m_class_get_byval_arg (par_klass), gshared_constraint);
mono_metadata_free_type (gshared_constraint);
klass = mono_class_from_mono_type_internal (t);
} else {
int type = decode_value (p, &p);
int num = decode_value (p, &p);
gboolean is_not_anonymous = decode_value (p, &p);
if (is_not_anonymous) {
gboolean is_method = decode_value (p, &p);
if (is_method) {
MonoMethod *method_def;
g_assert (type == MONO_TYPE_MVAR);
method_def = decode_resolve_method_ref (module, p, &p, error);
if (!method_def)
return NULL;
container = mono_method_get_generic_container (method_def);
} else {
MonoClass *class_def;
g_assert (type == MONO_TYPE_VAR);
class_def = decode_klass_ref (module, p, &p, error);
if (!class_def)
return NULL;
container = mono_class_try_get_generic_container (class_def); //FIXME is this a case for a try_get?
}
} else {
// We didn't decode is_method, so we have to infer it from type enum.
container = mono_get_anonymous_container_for_image (module->assembly->image, type == MONO_TYPE_MVAR);
}
t = g_new0 (MonoType, 1);
t->type = (MonoTypeEnum)type;
if (is_not_anonymous) {
t->data.generic_param = mono_generic_container_get_param (container, num);
} else {
/* Anonymous */
MonoGenericParam *par = mono_metadata_create_anon_gparam (module->assembly->image, num, type == MONO_TYPE_MVAR);
t->data.generic_param = par;
// FIXME: maybe do this for all anon gparams?
((MonoGenericParamFull*)par)->info.name = mono_make_generic_name_string (module->assembly->image, num);
}
// FIXME: Maybe use types directly to avoid
// the overhead of creating MonoClass-es
klass = mono_class_from_mono_type_internal (t);
g_free (t);
}
break;
}
case MONO_AOT_TYPEREF_ARRAY:
/* Array */
rank = decode_value (p, &p);
eklass = decode_klass_ref (module, p, &p, error);
if (!eklass)
return NULL;
klass = mono_class_create_array (eklass, rank);
break;
case MONO_AOT_TYPEREF_PTR: {
MonoType *t;
t = decode_type (module, p, &p, error);
if (!t)
return NULL;
klass = mono_class_from_mono_type_internal (t);
g_free (t);
break;
}
case MONO_AOT_TYPEREF_BLOB_INDEX: {
guint32 offset = decode_value (p, &p);
guint8 *p2;
p2 = module->blob + offset;
klass = decode_klass_ref (module, p2, &p2, error);
break;
}
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid klass reftype %d: %s", reftype, module->aot_name);
}
//g_assert (klass);
//printf ("BLA: %s\n", mono_type_full_name (m_class_get_byval_arg (klass)));
*endbuf = p;
return klass;
}
static MonoClassField*
decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
MonoClass *klass = decode_klass_ref (module, buf, &buf, error);
guint32 token;
guint8 *p = buf;
if (!klass) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
return NULL;
}
token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
*endbuf = p;
return mono_class_get_field (klass, token);
}
/*
* Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
* memory.
*/
static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint8 *p = buf;
MonoType *t;
if (*p == MONO_TYPE_CMOD_REQD) {
++p;
int count = decode_value (p, &p);
/* TODO: encode aggregate cmods differently than simple cmods and make it possible to use the more compact encoding here. */
t = (MonoType*)g_malloc0 (mono_sizeof_type_with_mods (count, TRUE));
mono_type_with_mods_init (t, count, TRUE);
/* Try not to blow up the stack. See comment on MONO_MAX_EXPECTED_CMODS */
g_assert (count < MONO_MAX_EXPECTED_CMODS);
MonoAggregateModContainer *cm = g_alloca (mono_sizeof_aggregate_modifiers (count));
cm->count = count;
for (int i = 0; i < count; ++i) {
MonoSingleCustomMod *cmod = &cm->modifiers [i];
cmod->required = decode_value (p, &p);
cmod->type = decode_type (module, p, &p, error);
goto_if_nok (error, fail);
}
mono_type_set_amods (t, mono_metadata_get_canonical_aggregate_modifiers (cm));
for (int i = 0; i < count; ++i)
mono_metadata_free_type (cm->modifiers [i].type);
} else {
t = (MonoType *) g_malloc0 (MONO_SIZEOF_TYPE);
}
while (TRUE) {
if (*p == MONO_TYPE_PINNED) {
t->pinned = TRUE;
++p;
} else if (*p == MONO_TYPE_BYREF) {
t->byref__ = TRUE;
++p;
} else {
break;
}
}
t->type = (MonoTypeEnum)*p;
++p;
switch (t->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:
t->data.klass = decode_klass_ref (module, p, &p, error);
if (!t->data.klass)
goto fail;
break;
case MONO_TYPE_SZARRAY:
t->data.klass = decode_klass_ref (module, p, &p, error);
if (!t->data.klass)
goto fail;
break;
case MONO_TYPE_PTR:
t->data.type = decode_type (module, p, &p, error);
if (!t->data.type)
goto fail;
break;
case MONO_TYPE_FNPTR:
t->data.method = decode_signature (module, p, &p);
if (!t->data.method)
goto fail;
break;
case MONO_TYPE_GENERICINST: {
MonoClass *gclass;
MonoGenericContext ctx;
MonoType *type;
MonoClass *klass;
gclass = decode_klass_ref (module, p, &p, error);
if (!gclass)
goto fail;
g_assert (mono_class_is_gtd (gclass));
memset (&ctx, 0, sizeof (ctx));
ctx.class_inst = decode_generic_inst (module, p, &p, error);
if (!ctx.class_inst)
goto fail;
type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
if (!type)
goto fail;
klass = mono_class_from_mono_type_internal (type);
t->data.generic_class = mono_class_get_generic_class (klass);
break;
}
case MONO_TYPE_ARRAY: {
MonoArrayType *array;
int i;
// FIXME: memory management
array = g_new0 (MonoArrayType, 1);
array->eklass = decode_klass_ref (module, p, &p, error);
if (!array->eklass)
goto fail;
array->rank = decode_value (p, &p);
array->numsizes = decode_value (p, &p);
if (array->numsizes)
array->sizes = (int *)g_malloc0 (sizeof (int) * array->numsizes);
for (i = 0; i < array->numsizes; ++i)
array->sizes [i] = decode_value (p, &p);
array->numlobounds = decode_value (p, &p);
if (array->numlobounds)
array->lobounds = (int *)g_malloc0 (sizeof (int) * array->numlobounds);
for (i = 0; i < array->numlobounds; ++i)
array->lobounds [i] = decode_value (p, &p);
t->data.array = array;
break;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR: {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
goto fail;
t->data.generic_param = m_class_get_byval_arg (klass)->data.generic_param;
break;
}
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid encoded type %d: %s", t->type, module->aot_name);
goto fail;
}
*endbuf = p;
return t;
fail:
g_free (t);
return NULL;
}
// FIXME: Error handling, memory management
static MonoMethodSignature*
decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
MonoMethodSignature *sig;
guint32 flags;
int i, gen_param_count = 0, param_count, call_conv;
guint8 *p = buf;
gboolean hasthis, explicit_this, has_gen_params, pinvoke;
flags = *p;
p ++;
has_gen_params = (flags & 0x10) != 0;
hasthis = (flags & 0x20) != 0;
explicit_this = (flags & 0x40) != 0;
pinvoke = (flags & 0x80) != 0;
call_conv = flags & 0x0F;
if (has_gen_params)
gen_param_count = decode_value (p, &p);
param_count = decode_value (p, &p);
if (target && param_count != target->param_count)
return NULL;
sig = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
sig->param_count = param_count;
sig->sentinelpos = -1;
sig->hasthis = hasthis;
sig->explicit_this = explicit_this;
sig->pinvoke = pinvoke;
sig->call_convention = call_conv;
sig->generic_param_count = gen_param_count;
sig->ret = decode_type (module, p, &p, error);
if (!sig->ret)
goto fail;
for (i = 0; i < param_count; ++i) {
if (*p == MONO_TYPE_SENTINEL) {
g_assert (sig->call_convention == MONO_CALL_VARARG);
sig->sentinelpos = i;
p ++;
}
sig->params [i] = decode_type (module, p, &p, error);
if (!sig->params [i])
goto fail;
}
if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
sig->sentinelpos = sig->param_count;
*endbuf = p;
return sig;
fail:
mono_error_cleanup (error); /* FIXME don't swallow the error */
g_free (sig);
return NULL;
}
static MonoMethodSignature*
decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
return decode_signature_with_target (module, NULL, buf, endbuf);
}
static gboolean
sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
{
MonoMethodSignature *sig;
gboolean res;
guint8 *p = buf;
sig = decode_signature_with_target (module, mono_method_signature_internal (target), p, &p);
res = sig && mono_metadata_signature_equal (mono_method_signature_internal (target), sig);
g_free (sig);
*endbuf = p;
return res;
}
/* Stores information returned by decode_method_ref () */
typedef struct {
MonoImage *image;
guint32 token;
MonoMethod *method;
gboolean no_aot_trampoline;
} MethodRef;
/*
* decode_method_ref_with_target:
*
* Decode a method reference, storing the image/token into a MethodRef structure.
* This avoids loading metadata for the method if the caller does not need it. If the method has
* no token, then it is loaded from metadata and ref->method is set to the method instance.
* If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
* couldn't resolve to TARGET, and return FALSE.
* There are some kinds of method references which only support a non-null TARGET.
* This means that its not possible to decode this into a method, only to check
* that the method reference matches a given method. This is normally not a problem
* as these wrappers only occur in the extra_methods table, where we already have
* a method we want to lookup.
*
* If there was a decoding error, we return FALSE and set @error
*/
static gboolean
decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint32 image_index, value;
MonoImage *image = NULL;
guint8 *p = buf;
memset (ref, 0, sizeof (MethodRef));
error_init (error);
value = decode_value (p, &p);
image_index = value >> 24;
if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
ref->no_aot_trampoline = TRUE;
value = decode_value (p, &p);
image_index = value >> 24;
}
if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC ||
image_index == MONO_AOT_METHODREF_GINST || image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
if (target && target->wrapper_type) {
return FALSE;
}
}
if (image_index == MONO_AOT_METHODREF_WRAPPER) {
WrapperInfo *info;
guint32 wrapper_type;
wrapper_type = decode_value (p, &p);
if (target && target->wrapper_type != wrapper_type)
return FALSE;
/* Doesn't matter */
image = mono_defaults.corlib;
switch (wrapper_type) {
case MONO_WRAPPER_ALLOC: {
int atype = decode_value (p, &p);
ManagedAllocatorVariant variant =
mono_profiler_allocations_enabled () ?
MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR;
ref->method = mono_gc_get_managed_allocator_by_type (atype, variant);
/* Try to fallback to the slow path version */
if (!ref->method)
ref->method = mono_gc_get_managed_allocator_by_type (atype, MANAGED_ALLOCATOR_SLOW_PATH);
if (!ref->method) {
mono_error_set_bad_image_by_name (error, module->aot_name, "Error: No managed allocator, but we need one for AOT.\nAre you using non-standard GC options?\n%s\n", module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
ref->method = mono_gc_get_write_barrier ();
break;
}
case MONO_WRAPPER_STELEMREF: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_NONE) {
ref->method = mono_marshal_get_stelemref ();
} else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
int kind;
kind = decode_value (p, &p);
ref->method = mono_marshal_get_virtual_stelemref_wrapper ((MonoStelemrefKind)kind);
} else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid STELEMREF subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_synchronized_wrapper (m);
break;
}
case MONO_WRAPPER_OTHER: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
if (!target)
return FALSE;
if (klass != target->klass)
return FALSE;
if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
if (strcmp (target->name, "PtrToStructure"))
return FALSE;
ref->method = mono_marshal_get_ptr_to_struct (klass);
} else {
if (strcmp (target->name, "StructureToPtr"))
return FALSE;
ref->method = mono_marshal_get_struct_to_ptr (klass);
}
} else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
} else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_array_accessor_wrapper (m);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
} else if (subtype == WRAPPER_SUBTYPE_INTERP_IN) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_interp_in_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_INTERP_LMF) {
MonoJitICallInfo *info = mono_find_jit_icall_info ((MonoJitICallId)decode_value (p, &p));
ref->method = mini_get_interp_lmf_wrapper (info->name, (gpointer) info->func);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_gsharedvt_in_sig_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_gsharedvt_out_sig_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_AOT_INIT) {
guint32 init_type = decode_value (p, &p);
ref->method = mono_marshal_get_aot_init_wrapper ((MonoAotInitSubtype) init_type);
} else if (subtype == WRAPPER_SUBTYPE_LLVM_FUNC) {
guint32 init_type = decode_value (p, &p);
ref->method = mono_marshal_get_llvm_func_wrapper ((MonoLLVMFuncWrapperSubtype) init_type);
} else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid UNKNOWN wrapper subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
int rank = decode_value (p, &p);
int elem_size = decode_value (p, &p);
ref->method = mono_marshal_get_array_address (rank, elem_size);
} else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
MonoMethod *m;
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
if (!target)
return FALSE;
g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
info = mono_marshal_get_wrapper_info (target);
if (info && info->subtype == subtype && info->d.string_ctor.method == m)
ref->method = target;
else
return FALSE;
} else if (subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
int name_idx = decode_value (p, &p);
const char *name = (const char*)module->blob + name_idx;
ref->method = mono_marshal_get_generic_array_helper (klass, name, m);
}
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
MonoMethod *m;
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
MonoJitICallInfo *info = mono_find_jit_icall_info ((MonoJitICallId)decode_value (p, &p));
ref->method = mono_icall_get_wrapper_method (info);
} else if (subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_INDIRECT) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mono_marshal_get_native_func_wrapper_indirect (klass, sig, TRUE);
} else {
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
/* This should only happen when looking for an extra method */
if (!target)
return FALSE;
if (mono_marshal_method_from_wrapper (target) == m)
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
ref->method = mono_marshal_get_castclass_with_cache ();
else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
ref->method = mono_marshal_get_isinst_with_cache ();
else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid CASTCLASS wrapper subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
int subtype = decode_value (p, &p);
if (!target)
return FALSE;
if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
return FALSE;
ref->method = target;
} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
/* Direct wrapper */
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
/* Virtual direct wrapper */
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
} else {
MonoMethodSignature *sig;
sig = decode_signature_with_target (module, NULL, p, &p);
info = mono_marshal_get_wrapper_info (target);
g_assert (info);
if (info->subtype != subtype) {
g_free (sig);
return FALSE;
}
g_assert (info->d.runtime_invoke.sig);
const gboolean same_sig = mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig);
g_free (sig);
if (same_sig)
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
gboolean is_inflated = decode_value (p, &p);
WrapperSubtype subtype;
if (is_inflated) {
MonoClass *klass;
MonoMethod *invoke, *wrapper;
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
switch (wrapper_type) {
case MONO_WRAPPER_DELEGATE_INVOKE:
invoke = mono_get_delegate_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
break;
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
invoke = mono_get_delegate_begin_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
break;
case MONO_WRAPPER_DELEGATE_END_INVOKE:
invoke = mono_get_delegate_end_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_end_invoke (invoke);
break;
default:
g_assert_not_reached ();
break;
}
if (target) {
/*
* Due to the way mini_get_shared_method_full () works, we could end up with
* multiple copies of the same wrapper.
*/
if (wrapper->klass != target->klass)
return FALSE;
ref->method = target;
} else {
ref->method = wrapper;
}
} else {
/*
* These wrappers are associated with a signature, not with a method.
* Since we can't decode them into methods, they need a target method.
*/
if (!target)
return FALSE;
if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
subtype = (WrapperSubtype)decode_value (p, &p);
info = mono_marshal_get_wrapper_info (target);
if (info) {
if (info->subtype != subtype)
return FALSE;
} else {
if (subtype != WRAPPER_SUBTYPE_NONE)
return FALSE;
}
}
if (sig_matches_target (module, target, p, &p))
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
MonoMethod *m;
MonoClass *klass;
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
gboolean has_class = decode_value (p, &p);
if (has_class) {
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
} else
klass = NULL;
ref->method = mono_marshal_get_managed_wrapper (m, klass, 0, error);
if (!is_ok (error))
return FALSE;
break;
}
default:
g_assert_not_reached ();
}
} else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
image_index = decode_value (p, &p);
ref->token = decode_value (p, &p);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
guint32 offset = decode_value (p, &p);
guint8 *p2;
p2 = module->blob + offset;
if (!decode_method_ref_with_target (module, ref, target, p2, &p2, error))
return FALSE;
image = ref->image;
if (!image)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_GINST) {
MonoClass *klass;
MonoGenericContext ctx;
guint32 token_index;
/*
* These methods do not have a token which resolves them, so we
* resolve them immediately.
*/
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
if (target && target->klass != klass)
return FALSE;
image_index = decode_value (p, &p);
token_index = decode_value (p, &p);
ref->token = mono_metadata_make_token (MONO_TABLE_METHOD, token_index);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
ref->method = mono_get_method_checked (image, ref->token, NULL, NULL, error);
if (!ref->method)
return FALSE;
memset (&ctx, 0, sizeof (ctx));
if (FALSE && mono_class_is_ginst (klass)) {
ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
ctx.method_inst = NULL;
ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
if (!ref->method)
return FALSE;
}
memset (&ctx, 0, sizeof (ctx));
if (!decode_generic_context (module, &ctx, p, &p, error))
return FALSE;
ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
if (!ref->method)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_ARRAY) {
MonoClass *klass;
int method_type;
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
method_type = decode_value (p, &p);
switch (method_type) {
case 0:
ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass), 0, error);
return_val_if_nok (error, FALSE);
break;
case 1:
ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass) * 2, 0, error);
return_val_if_nok (error, FALSE);
break;
case 2:
ref->method = mono_class_get_method_from_name_checked (klass, "Get", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
case 3:
ref->method = mono_class_get_method_from_name_checked (klass, "Address", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
case 4:
ref->method = mono_class_get_method_from_name_checked (klass, "Set", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid METHODREF_ARRAY method type %d: %s", method_type, module->aot_name);
return FALSE;
}
} else {
if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
image_index = decode_value (p, &p);
value = decode_value (p, &p);
}
ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
}
*endbuf = p;
ref->image = image;
return TRUE;
}
static gboolean
decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf, MonoError *error)
{
return decode_method_ref_with_target (module, ref, NULL, buf, endbuf, error);
}
/*
* decode_resolve_method_ref_with_target:
*
* Similar to decode_method_ref, but resolve and return the method itself.
*/
static MonoMethod*
decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
{
MethodRef ref;
error_init (error);
if (!decode_method_ref_with_target (module, &ref, target, buf, endbuf, error))
return NULL;
if (ref.method)
return ref.method;
if (!ref.image) {
mono_error_set_bad_image_by_name (error, module->aot_name, "No image found for methodref with target: %s", module->aot_name);
return NULL;
}
return mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
}
static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf, error);
}
static void
find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
{
if (globals) {
int global_index;
guint16 *table, *entry;
guint16 table_size;
guint32 hash;
char *symbol = (char*)name;
#ifdef TARGET_MACH
symbol = g_strdup_printf ("_%s", name);
#endif
/* The first entry points to the hash */
table = (guint16 *)globals [0];
globals ++;
table_size = table [0];
table ++;
hash = mono_metadata_str_hash (symbol) % table_size;
entry = &table [hash * 2];
/* Search the hash for the index into the globals table */
global_index = -1;
while (entry [0] != 0) {
guint32 index = entry [0] - 1;
guint32 next = entry [1];
//printf ("X: %s %s\n", (char*)globals [index * 2], name);
if (!strcmp ((const char*)globals [index * 2], symbol)) {
global_index = index;
break;
}
if (next != 0) {
entry = &table [next * 2];
} else {
break;
}
}
if (global_index != -1)
*value = globals [global_index * 2 + 1];
else
*value = NULL;
if (symbol != name)
g_free (symbol);
} else {
char *err = mono_dl_symbol (module, name, value);
if (err)
g_free (err);
}
}
static void
find_amodule_symbol (MonoAotModule *amodule, const char *name, gpointer *value)
{
g_assert (!(amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY));
find_symbol (amodule->sofile, amodule->globals, name, value);
}
void
mono_install_load_aot_data_hook (MonoLoadAotDataFunc load_func, MonoFreeAotDataFunc free_func, gpointer user_data)
{
aot_data_load_func = load_func;
aot_data_free_func = free_func;
aot_data_func_user_data = user_data;
}
/* Load the separate aot data file for ASSEMBLY */
static guint8*
open_aot_data (MonoAssembly *assembly, MonoAotFileInfo *info, void **ret_handle)
{
MonoFileMap *map;
char *filename;
guint8 *data;
if (aot_data_load_func) {
data = aot_data_load_func (assembly, info->datafile_size, aot_data_func_user_data, ret_handle);
g_assert (data);
return data;
}
/*
* Use <assembly name>.aotdata as the default implementation if no callback is given
*/
filename = g_strdup_printf ("%s.aotdata", assembly->image->name);
map = mono_file_map_open (filename);
g_assert (map);
data = (guint8*)mono_file_map (info->datafile_size, MONO_MMAP_READ, mono_file_map_fd (map), 0, ret_handle);
g_assert (data);
return data;
}
static gboolean
check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, guint8 *blob, char **out_msg)
{
char *build_info;
char *msg = NULL;
gboolean usable = TRUE;
gboolean full_aot, interp, safepoints;
guint32 excluded_cpu_optimizations;
if (strcmp (assembly->image->guid, (const char*)info->assembly_guid)) {
msg = g_strdup ("doesn't match assembly");
usable = FALSE;
}
build_info = mono_get_runtime_build_info ();
if (strlen ((const char *)info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
usable = FALSE;
}
g_free (build_info);
full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
interp = info->flags & MONO_AOT_FILE_FLAG_INTERP;
if (mono_aot_only && !full_aot) {
if (!interp) {
msg = g_strdup ("not compiled with --aot=full");
usable = FALSE;
}
}
if (!mono_aot_only && full_aot) {
msg = g_strdup ("compiled with --aot=full");
usable = FALSE;
}
if (mono_use_interpreter && !interp && !strcmp (assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME)) {
/* mscorlib contains necessary interpreter trampolines */
msg = g_strdup ("not compiled with --aot=interp");
usable = FALSE;
}
if (mono_llvm_only && !(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
msg = g_strdup ("not compiled with --aot=llvmonly");
usable = FALSE;
}
if (mono_use_llvm && !(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)) {
/* Prefer LLVM JITted code when using --llvm */
msg = g_strdup ("not compiled with --aot=llvm");
usable = FALSE;
}
if (mini_debug_options.mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot && !interp) {
msg = g_strdup ("not compiled for debugging");
usable = FALSE;
}
mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
if (info->opts & excluded_cpu_optimizations) {
msg = g_strdup ("compiled with unsupported CPU optimizations");
usable = FALSE;
}
if (info->gc_name_index != -1) {
char *gc_name = (char*)&blob [info->gc_name_index];
const char *current_gc_name = mono_gc_get_gc_name ();
if (strcmp (current_gc_name, gc_name) != 0) {
msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
usable = FALSE;
}
}
safepoints = info->flags & MONO_AOT_FILE_FLAG_SAFEPOINTS;
if (!safepoints && mono_threads_are_safepoints_enabled ()) {
msg = g_strdup ("not compiled with safepoints");
usable = FALSE;
}
#ifdef MONO_ARCH_CODE_EXEC_ONLY
if (!(info->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)) {
msg = g_strdup ("not compiled targeting a runtime configured as CODE_EXEC_ONLY");
usable = FALSE;
}
#else
if (info->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
msg = g_strdup ("compiled targeting a runtime configured as CODE_EXEC_ONLY");
usable = FALSE;
}
#endif
*out_msg = msg;
return usable;
}
/*
* TABLE should point to a table of call instructions. Return the address called by the INDEXth entry.
*/
static void*
get_call_table_entry (void *table, int index, int entry_size)
{
#if defined(TARGET_ARM)
guint32 *ins_addr;
guint32 ins;
gint32 offset;
if (entry_size == 8) {
ins_addr = (guint32 *)table + (index * 2);
g_assert ((guint32) *ins_addr == (guint32 ) 0xe51ff004); // ldr pc, =<label>
return *((char **) (ins_addr + 1));
}
g_assert (entry_size == 4);
ins_addr = (guint32*)table + index;
ins = *ins_addr;
if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
/* blx */
offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
return (char*)ins_addr + (offset * 2) + 8 + 1;
} else {
g_assert ((ins >> ARMCOND_SHIFT) == ARMCOND_AL);
/* bl */
offset = (((int)ins & 0xffffff) << 8) >> 8;
return (char*)ins_addr + (offset * 4) + 8;
}
#elif defined(TARGET_ARM64)
return mono_arch_get_call_target ((guint8*)table + (index * 4) + 4);
#elif defined(TARGET_X86) || defined(TARGET_AMD64)
/* The callee expects an ip which points after the call */
return mono_arch_get_call_target ((guint8*)table + (index * 5) + 5);
#else
g_assert_not_reached ();
return NULL;
#endif
}
/*
* init_amodule_got:
*
* Initialize the shared got entries for AMODULE.
*/
static void
init_amodule_got (MonoAotModule *amodule, gboolean preinit)
{
MonoJumpInfo *ji;
MonoMemPool *mp;
MonoJumpInfo *patches;
guint32 got_offsets [128];
ERROR_DECL (error);
int i, npatches;
/* These can't be initialized in load_aot_module () */
if (amodule->got_initialized == GOT_INITIALIZED)
return;
mono_loader_lock ();
/*
* If it is initialized some other thread did it in the meantime. If it is
* initializing it means the current thread is initializing it since we are
* holding the loader lock, skip it.
*/
if (amodule->got_initialized) {
mono_loader_unlock ();
return;
}
if (!preinit)
amodule->got_initialized = GOT_INITIALIZING;
mp = mono_mempool_new ();
npatches = amodule->info.nshared_got_entries;
for (i = 0; i < npatches; ++i)
got_offsets [i] = i;
if (amodule->got)
patches = decode_patches (amodule, mp, npatches, FALSE, got_offsets);
else
patches = decode_patches (amodule, mp, npatches, TRUE, got_offsets);
g_assert (patches);
for (i = 0; i < npatches; ++i) {
ji = &patches [i];
if (amodule->shared_got [i]) {
} else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
amodule->shared_got [i] = amodule;
} else if (preinit) {
/*
* This is called from init_amodule () during startup, so some things might not
* be setup. Initialize just the slots needed to make method initialization work.
*/
if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
if (ji->data.jit_icall_id == MONO_JIT_ICALL_mini_llvm_init_method)
amodule->shared_got [i] = (gpointer)mini_llvm_init_method;
}
} else if (ji->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_START && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_BITS && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_IMAGE) {
amodule->shared_got [i] = amodule->assembly->image;
} else if (ji->type == MONO_PATCH_INFO_MSCORLIB_GOT_ADDR) {
if (mono_defaults.corlib) {
MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
if (mscorlib_amodule)
amodule->shared_got [i] = mscorlib_amodule->got;
} else {
amodule->shared_got [i] = amodule->got;
}
} else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
amodule->shared_got [i] = amodule;
} else if (ji->type == MONO_PATCH_INFO_NONE) {
} else {
amodule->shared_got [i] = mono_resolve_patch_target (NULL, NULL, ji, FALSE, error);
mono_error_assert_ok (error);
}
}
if (amodule->got) {
for (i = 0; i < npatches; ++i)
amodule->got [i] = amodule->shared_got [i];
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_WITH_LLVM) {
void (*init_aotconst) (int, gpointer) = (void (*)(int, gpointer))amodule->info.llvm_init_aotconst;
for (i = 0; i < npatches; ++i) {
amodule->llvm_got [i] = amodule->shared_got [i];
init_aotconst (i, amodule->llvm_got [i]);
}
}
mono_mempool_destroy (mp);
if (!preinit) {
mono_memory_barrier ();
amodule->got_initialized = GOT_INITIALIZED;
}
mono_loader_unlock ();
}
#ifdef MONOTOUCH
// Follow branch islands on ARM iOS machines.
static inline guint8 *
method_address_resolve (guint8 *code_addr)
{
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
#if defined(TARGET_ARM)
// Skip branches to thumb destinations; the convention used is that the
// lowest bit is set if the destination is thumb. See
// get_call_table_entry.
if (((uintptr_t) code_addr) & 0x1)
return code_addr;
#endif
for (;;) {
// `mono_arch_get_call_target` takes the IP after the branch
// instruction, not before. Add 4 bytes to compensate.
guint8 *next = mono_arch_get_call_target (code_addr + 4);
if (next == NULL) return code_addr;
code_addr = next;
}
#endif
return code_addr;
}
#else
static inline guint8 *
method_address_resolve (guint8 *code_addr) {
return code_addr;
}
#endif
#ifdef HOST_WASM
static void
register_methods_in_jinfo (MonoAotModule *amodule)
{
MonoAssembly *assembly = amodule->assembly;
int i;
static MonoBitSet *registered;
static int registered_len;
/*
* Register the methods in AMODULE in the jit info table. There are 2 issues:
* - emscripten could reorder code so methods from different aot images are intermixed.
* - if linkonce linking is used, multiple aot images could refer to the same method.
*/
sort_methods (amodule);
if (amodule->sorted_methods_len == 0)
return;
mono_aot_lock ();
/* The 'registered' bitset contains whenever we have already registered a method in the jit info table */
int max = -1;
for (i = 0; i < amodule->sorted_methods_len; ++i)
max = MAX (max, GPOINTER_TO_INT (amodule->sorted_methods [i]));
g_assert (max != -1);
if (registered == NULL) {
registered = mono_bitset_new (max, 0);
registered_len = max;
} else if (max > registered_len) {
MonoBitSet *new_registered = mono_bitset_clone (registered, max);
mono_bitset_free (registered);
registered = new_registered;
registered_len = max;
}
#if 0
for (i = 0; i < amodule->sorted_methods_len; ++i) {
printf ("%s %d\n", amodule->assembly->aname.name, amodule->sorted_methods [i]);
}
#endif
int start = 0;
while (start < amodule->sorted_methods_len) {
/* Find beginning of interval */
int start_method = GPOINTER_TO_INT (amodule->sorted_methods [start]);
if (mono_bitset_test_fast (registered, start_method)) {
start ++;
continue;
}
/* Find end of interval */
int end = start + 1;
while (end < amodule->sorted_methods_len && GPOINTER_TO_INT (amodule->sorted_methods [end]) == GPOINTER_TO_INT (amodule->sorted_methods [end - 1]) + 1 && !mono_bitset_test_fast (registered, GPOINTER_TO_INT (amodule->sorted_methods [end])))
end ++;
int end_method = GPOINTER_TO_INT (amodule->sorted_methods [end - 1]);
//printf ("%s [%d %d]\n", amodule->assembly->aname.name, start_method, end_method);
/* The 'end' parameter is exclusive */
mono_jit_info_add_aot_module (assembly->image, GINT_TO_POINTER (start_method), GINT_TO_POINTER (end_method + 1));
for (int j = start_method; j < end_method + 1; ++j)
g_assert (!mono_bitset_test_fast (registered, j));
start = end;
}
for (i = 0; i < amodule->sorted_methods_len; ++i)
mono_bitset_set_fast (registered, GPOINTER_TO_INT (amodule->sorted_methods [i]));
mono_aot_unlock ();
}
#endif
static void
load_aot_module (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error)
{
char *aot_name, *found_aot_name;
MonoAotModule *amodule;
MonoDl *sofile;
gboolean usable = TRUE;
char *version_symbol = NULL;
char *msg = NULL;
gpointer *globals = NULL;
MonoAotFileInfo *info = NULL;
int i, version;
gboolean do_load_image = TRUE;
int align_double, align_int64;
guint8 *aot_data = NULL;
if (mono_compile_aot)
return;
if (mono_aot_mode == MONO_AOT_MODE_NONE)
return;
if (assembly->image->aot_module)
/*
* Already loaded. This can happen because the assembly loading code might invoke
* the assembly load hooks multiple times for the same assembly.
*/
return;
if (image_is_dynamic (assembly->image))
return;
gboolean loaded = FALSE;
mono_aot_lock ();
if (static_aot_modules)
info = (MonoAotFileInfo *)g_hash_table_lookup (static_aot_modules, assembly->aname.name);
if (info) {
if (!loaded_static_aot_modules)
loaded_static_aot_modules = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (loaded_static_aot_modules, info))
loaded = TRUE;
else
g_hash_table_insert (loaded_static_aot_modules, info, info);
}
mono_aot_unlock ();
if (loaded)
/*
* Already loaded by another assembly with the same name, or the same assembly loaded
* in another ALC.
*/
return;
sofile = NULL;
found_aot_name = NULL;
if (info) {
/* Statically linked AOT module */
aot_name = g_strdup_printf ("%s", assembly->aname.name);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.", aot_name);
if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
globals = (void **)info->globals;
g_assert (globals);
}
found_aot_name = g_strdup (aot_name);
} else {
char *err;
aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
if (sofile) {
found_aot_name = g_strdup (aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
g_free (err);
}
g_free (aot_name);
if (!sofile) {
GList *l;
for (l = mono_aot_paths; l; l = l->next) {
char *path = (char*)l->data;
char *basename = g_path_get_basename (assembly->image->name);
aot_name = g_strdup_printf ("%s/%s%s", path, basename, MONO_SOLIB_EXT);
sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
if (sofile) {
found_aot_name = g_strdup (aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
g_free (err);
}
g_free (basename);
g_free (aot_name);
if (sofile)
break;
}
}
if (!sofile) {
// Maybe do these on more platforms ?
#ifndef HOST_WASM
if (mono_aot_only && !mono_use_interpreter && table_info_get_rows (&assembly->image->tables [MONO_TABLE_METHOD])) {
aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
g_error ("Failed to load AOT module '%s' ('%s') in aot-only mode.\n", aot_name, assembly->image->name);
g_free (aot_name);
}
#endif
return;
}
}
if (!info) {
find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
}
// Copy aotid to MonoImage
memcpy(&assembly->image->aotid, info->aotid, 16);
if (version_symbol) {
/* Old file format */
version = atoi (version_symbol);
} else {
g_assert (info);
version = info->version;
}
if (version != MONO_AOT_FILE_VERSION) {
msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
usable = FALSE;
} else {
guint8 *blob;
void *handle;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
aot_data = open_aot_data (assembly, info, &handle);
blob = aot_data + info->table_offsets [MONO_AOT_TABLE_BLOB];
} else {
blob = (guint8 *)info->blob;
}
usable = check_usable (assembly, info, blob, &msg);
}
if (!usable) {
if (mono_aot_only) {
g_error ("Failed to load AOT module '%s' while running in aot-only mode: %s.\n", found_aot_name, msg);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s is unusable: %s.", found_aot_name, msg);
}
g_free (msg);
g_free (found_aot_name);
if (sofile)
mono_dl_close (sofile);
assembly->image->aot_module = NULL;
return;
}
/* Sanity check */
align_double = MONO_ABI_ALIGNOF (double);
align_int64 = MONO_ABI_ALIGNOF (gint64);
int card_table_shift_bits = 0;
gpointer card_table_mask = NULL;
mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
g_assert (info->double_align == align_double);
g_assert (info->long_align == align_int64);
g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
g_assert (info->card_table_shift_bits == card_table_shift_bits);
g_assert (info->card_table_mask == GPOINTER_TO_UINT (card_table_mask));
amodule = g_new0 (MonoAotModule, 1);
amodule->aot_name = found_aot_name;
amodule->assembly = assembly;
memcpy (&amodule->info, info, sizeof (*info));
amodule->got = (void **)amodule->info.jit_got;
/*
* The llvm code keeps its data in separate scalar variables, so this just used by this module.
*/
amodule->llvm_got = g_malloc0 (sizeof (gpointer) * amodule->info.llvm_got_size);
amodule->globals = globals;
amodule->sofile = sofile;
amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
amodule->extra_methods = g_hash_table_new (NULL, NULL);
amodule->shared_got = g_new0 (gpointer, info->nshared_got_entries);
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
amodule->tables [i] = aot_data + info->table_offsets [i];
}
mono_os_mutex_init_recursive (&amodule->mutex);
/* Read image table */
{
guint32 table_len, i;
char *table = NULL;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA)
table = (char *)amodule->tables [MONO_AOT_TABLE_IMAGE_TABLE];
else
table = (char *)info->image_table;
g_assert (table);
table_len = *(guint32*)table;
table += sizeof (guint32);
amodule->image_table = g_new0 (MonoImage*, table_len);
amodule->image_names = g_new0 (MonoAssemblyName, table_len);
amodule->image_guids = g_new0 (char*, table_len);
amodule->image_table_len = table_len;
for (i = 0; i < table_len; ++i) {
MonoAssemblyName *aname = &(amodule->image_names [i]);
aname->name = g_strdup (table);
table += strlen (table) + 1;
amodule->image_guids [i] = g_strdup (table);
table += strlen (table) + 1;
if (table [0] != 0)
aname->culture = g_strdup (table);
table += strlen (table) + 1;
memcpy (aname->public_key_token, table, strlen (table) + 1);
table += strlen (table) + 1;
table = (char *)ALIGN_PTR_TO (table, 8);
aname->flags = *(guint32*)table;
table += 4;
aname->major = *(guint32*)table;
table += 4;
aname->minor = *(guint32*)table;
table += 4;
aname->build = *(guint32*)table;
table += 4;
aname->revision = *(guint32*)table;
table += 4;
}
}
amodule->jit_code_start = (guint8 *)info->jit_code_start;
amodule->jit_code_end = (guint8 *)info->jit_code_end;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
amodule->blob = (guint8*)amodule->tables [MONO_AOT_TABLE_BLOB];
amodule->method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_METHOD_INFO_OFFSETS];
amodule->ex_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EX_INFO_OFFSETS];
amodule->class_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_CLASS_INFO_OFFSETS];
amodule->class_name_table = (guint16*)amodule->tables [MONO_AOT_TABLE_CLASS_NAME];
amodule->extra_method_table = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_TABLE];
amodule->extra_method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS];
amodule->got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_GOT_INFO_OFFSETS];
amodule->llvm_got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS];
amodule->weak_field_indexes = (guint32*)amodule->tables [MONO_AOT_TABLE_WEAK_FIELD_INDEXES];
amodule->method_flags_table = (guint8*)amodule->tables [MONO_AOT_TABLE_METHOD_FLAGS_TABLE];
} else {
amodule->blob = (guint8*)info->blob;
amodule->method_info_offsets = (guint32 *)info->method_info_offsets;
amodule->ex_info_offsets = (guint32 *)info->ex_info_offsets;
amodule->class_info_offsets = (guint32 *)info->class_info_offsets;
amodule->class_name_table = (guint16 *)info->class_name_table;
amodule->extra_method_table = (guint32 *)info->extra_method_table;
amodule->extra_method_info_offsets = (guint32 *)info->extra_method_info_offsets;
amodule->got_info_offsets = (guint32*)info->got_info_offsets;
amodule->llvm_got_info_offsets = (guint32*)info->llvm_got_info_offsets;
amodule->weak_field_indexes = (guint32*)info->weak_field_indexes;
amodule->method_flags_table = (guint8*)info->method_flags_table;
}
amodule->unbox_trampolines = (guint32 *)info->unbox_trampolines;
amodule->unbox_trampolines_end = (guint32 *)info->unbox_trampolines_end;
amodule->unbox_trampoline_addresses = (guint32 *)info->unbox_trampoline_addresses;
amodule->unwind_info = (guint8 *)info->unwind_info;
amodule->mem_begin = (guint8*)amodule->jit_code_start;
amodule->mem_end = (guint8 *)info->mem_end;
amodule->plt = (guint8 *)info->plt;
amodule->plt_end = (guint8 *)info->plt_end;
amodule->mono_eh_frame = (guint8 *)info->mono_eh_frame;
amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = (guint8 *)info->specific_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = (guint8 *)info->static_rgctx_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_IMT] = (guint8 *)info->imt_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = (guint8 *)info->gsharedvt_arg_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = (guint8 *)info->ftnptr_arg_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = (guint8 *)info->unbox_arbitrary_trampolines;
if (mono_is_corlib_image (assembly->image) || !strcmp (assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME)) {
g_assert (!mscorlib_aot_module);
mscorlib_aot_module = amodule;
}
/* Compute method addresses */
amodule->methods = (void **)g_malloc0 (amodule->info.nmethods * sizeof (gpointer));
for (i = 0; i < amodule->info.nmethods; ++i) {
void *addr = NULL;
if (amodule->info.llvm_get_method) {
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
addr = get_method (i);
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
addr = ((gpointer*)amodule->info.method_addresses) [i];
} else {
/* method_addresses () contains a table of branches, since the ios linker can update those correctly */
if (!addr && amodule->info.method_addresses) {
addr = get_call_table_entry (amodule->info.method_addresses, i, amodule->info.call_table_entry_size);
g_assert (addr);
if (addr == amodule->info.method_addresses)
addr = NULL;
else
addr = method_address_resolve ((guint8 *) addr);
}
}
if (addr == NULL)
amodule->methods [i] = GINT_TO_POINTER (-1);
else
amodule->methods [i] = addr;
}
if (make_unreadable) {
#ifndef TARGET_WIN32
guint8 *addr;
guint8 *page_start, *page_end;
int err, len;
addr = amodule->mem_begin;
g_assert (addr);
len = amodule->mem_end - amodule->mem_begin;
/* Round down in both directions to avoid modifying data which is not ours */
page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
if (page_end > page_start) {
err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
g_assert (err == 0);
}
#endif
}
/* Compute the boundaries of LLVM code */
if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
compute_llvm_code_range (amodule, &amodule->llvm_code_start, &amodule->llvm_code_end);
mono_aot_lock ();
if (amodule->jit_code_start) {
aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->jit_code_start);
aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->jit_code_end);
}
if (amodule->llvm_code_start) {
aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->llvm_code_start);
aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->llvm_code_end);
}
g_hash_table_insert (aot_modules, assembly, amodule);
mono_aot_unlock ();
init_amodule_got (amodule, TRUE);
#ifdef HOST_WASM
register_methods_in_jinfo (amodule);
#else
if (amodule->jit_code_start)
mono_jit_info_add_aot_module (assembly->image, amodule->jit_code_start, amodule->jit_code_end);
if (amodule->llvm_code_start)
mono_jit_info_add_aot_module (assembly->image, amodule->llvm_code_start, amodule->llvm_code_end);
#endif
assembly->image->aot_module = amodule;
if (mono_aot_only && !mono_llvm_only) {
char *code;
find_amodule_symbol (amodule, "specific_trampolines_page", (gpointer *)&code);
amodule->use_page_trampolines = code != NULL;
/*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
}
if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
/* Directly called methods might make calls through the PLT */
init_plt (amodule);
/*
* Register the plt region as a single trampoline so we can unwind from this code
*/
mono_aot_tramp_info_register (
mono_tramp_info_create (
NULL,
amodule->plt,
amodule->plt_end - amodule->plt,
NULL,
mono_unwind_get_cie_program ()
),
NULL
);
/*
* Since we store methoddef and classdef tokens when referring to methods/classes in
* referenced assemblies, we depend on the exact versions of the referenced assemblies.
* MS calls this 'hard binding'. This means we have to load all referenced assemblies
* non-lazily, since we can't handle out-of-date errors later.
* The cached class info also depends on the exact assemblies.
*/
if (do_load_image) {
for (i = 0; i < amodule->image_table_len; ++i) {
ERROR_DECL (error);
load_image (amodule, i, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
if (amodule->out_of_date) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: Module %s is unusable because a dependency is out-of-date.", assembly->image->name);
if (mono_aot_only && (mono_aot_mode != MONO_AOT_MODE_LLVMONLY_INTERP))
g_error ("Failed to load AOT module '%s' while running in aot-only mode because a dependency cannot be found or it is out of date.\n", found_aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' found.", found_aot_name);
}
}
/*
* mono_aot_register_module:
*
* This should be called by embedding code to register normal AOT modules statically linked
* into the executable.
*
* \param aot_info the value of the 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
*/
void
mono_aot_register_module (gpointer *aot_info)
{
gpointer *globals;
char *aname;
MonoAotFileInfo *info = (MonoAotFileInfo *)aot_info;
g_assert (info->version == MONO_AOT_FILE_VERSION);
if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
globals = (void **)info->globals;
g_assert (globals);
}
aname = (char *)info->assembly_name;
/* This could be called before startup */
if (aot_modules)
mono_aot_lock ();
if (!static_aot_modules)
static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (static_aot_modules, aname, info);
if (info->flags & MONO_AOT_FILE_FLAG_EAGER_LOAD) {
/*
* This assembly contains shared generic instances/wrappers, etc. It needs be be loaded
* before AOT code is loaded.
*/
g_assert (!container_assm_name);
container_assm_name = aname;
}
if (aot_modules)
mono_aot_unlock ();
}
void
mono_aot_init (void)
{
mono_os_mutex_init_recursive (&aot_mutex);
mono_os_mutex_init_recursive (&aot_page_mutex);
aot_modules = g_hash_table_new (NULL, NULL);
mono_install_assembly_load_hook_v2 (load_aot_module, NULL, FALSE);
mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
char *lastaot = g_getenv ("MONO_LASTAOT");
if (lastaot) {
mono_last_aot_method = atoi (lastaot);
g_free (lastaot);
}
}
/*
* load_container_amodule:
*
* Load the container assembly and its AOT image.
*/
static void
load_container_amodule (MonoAssemblyLoadContext *alc)
{
ERROR_DECL (error);
if (!container_assm_name || container_amodule)
return;
char *local_ref = container_assm_name;
container_assm_name = NULL;
MonoImageOpenStatus status = MONO_IMAGE_OK;
MonoAssemblyOpenRequest req;
gchar *dll = g_strdup_printf ( "%s.dll", local_ref);
/*
* Don't fire managed assembly load events whose execution
* might require this module to be already loaded.
*/
mono_assembly_request_prepare_open (&req, alc);
req.request.no_managed_load_event = TRUE;
MonoAssembly *assm = mono_assembly_request_open (dll, &req, &status);
if (!assm) {
gchar *exe = g_strdup_printf ("%s.exe", local_ref);
assm = mono_assembly_request_open (exe, &req, &status);
}
g_assert (assm);
load_aot_module (alc, assm, NULL, error);
container_amodule = assm->image->aot_module;
}
static gboolean
decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
guint32 flags;
MethodRef ref;
gboolean res;
info->vtable_size = decode_value (buf, &buf);
if (info->vtable_size == -1)
/* Generic type */
return FALSE;
flags = decode_value (buf, &buf);
info->ghcimpl = (flags >> 0) & 0x1;
info->has_finalize = (flags >> 1) & 0x1;
info->has_cctor = (flags >> 2) & 0x1;
info->has_nested_classes = (flags >> 3) & 0x1;
info->blittable = (flags >> 4) & 0x1;
info->has_references = (flags >> 5) & 0x1;
info->has_static_refs = (flags >> 6) & 0x1;
info->no_special_static_fields = (flags >> 7) & 0x1;
info->is_generic_container = (flags >> 8) & 0x1;
info->has_weak_fields = (flags >> 9) & 0x1;
if (info->has_cctor) {
res = decode_method_ref (module, &ref, buf, &buf, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
return FALSE;
info->cctor_token = ref.token;
}
if (info->has_finalize) {
res = decode_method_ref (module, &ref, buf, &buf, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
return FALSE;
info->finalize_image = ref.image;
info->finalize_token = ref.token;
}
info->instance_size = decode_value (buf, &buf);
info->class_size = decode_value (buf, &buf);
info->packing_size = decode_value (buf, &buf);
info->min_align = decode_value (buf, &buf);
*endbuf = buf;
return TRUE;
}
gpointer
mono_aot_get_method_from_vt_slot (MonoVTable *vtable, int slot, MonoError *error)
{
int i;
MonoClass *klass = vtable->klass;
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *info, *p;
MonoCachedClassInfo class_info;
gboolean err;
MethodRef ref;
gboolean res;
gpointer addr;
ERROR_DECL (inner_error);
error_init (error);
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || m_class_get_rank (klass) || !amodule)
return NULL;
info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
p = info;
err = decode_cached_class_info (amodule, &class_info, p, &p);
if (!err)
return NULL;
for (i = 0; i < slot; ++i) {
decode_method_ref (amodule, &ref, p, &p, inner_error);
mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
}
res = decode_method_ref (amodule, &ref, p, &p, inner_error);
mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
if (!res)
return NULL;
if (ref.no_aot_trampoline)
return NULL;
if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
return NULL;
addr = mono_aot_get_method_from_token (ref.image, ref.token, error);
return addr;
}
gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *p;
gboolean err;
if (m_class_get_rank (klass) || !m_class_get_type_token (klass) || !amodule)
return FALSE;
p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
err = decode_cached_class_info (amodule, res, p, &p);
if (!err)
return FALSE;
return TRUE;
}
/**
* mono_aot_get_class_from_name:
*
* Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
* using a cache stored in the AOT file.
* Stores the resulting class in *KLASS if found, stores NULL otherwise.
*
* Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
* found.
*/
gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
MonoAotModule *amodule = image->aot_module;
guint16 *table, *entry;
guint16 table_size;
guint32 hash;
char full_name_buf [1024];
char *full_name;
const char *name2, *name_space2;
MonoTableInfo *t;
guint32 cols [MONO_TYPEDEF_SIZE];
GHashTable *nspace_table;
if (!amodule || !amodule->class_name_table)
return FALSE;
amodule_lock (amodule);
*klass = NULL;
/* First look in the cache */
if (!amodule->name_cache)
amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
if (nspace_table) {
*klass = (MonoClass *)g_hash_table_lookup (nspace_table, name);
if (*klass) {
amodule_unlock (amodule);
return TRUE;
}
}
table_size = amodule->class_name_table [0];
table = amodule->class_name_table + 1;
if (name_space [0] == '\0')
full_name = g_strdup_printf ("%s", name);
else {
if (strlen (name_space) + strlen (name) < 1000) {
sprintf (full_name_buf, "%s.%s", name_space, name);
full_name = full_name_buf;
} else {
full_name = g_strdup_printf ("%s.%s", name_space, name);
}
}
hash = mono_metadata_str_hash (full_name) % table_size;
if (full_name != full_name_buf)
g_free (full_name);
entry = &table [hash * 2];
if (entry [0] != 0) {
t = &image->tables [MONO_TABLE_TYPEDEF];
while (TRUE) {
guint32 index = entry [0];
guint32 next = entry [1];
guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
name_table_accesses ++;
mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
ERROR_DECL (error);
amodule_unlock (amodule);
*klass = mono_class_get_checked (image, token, error);
if (!is_ok (error))
mono_error_cleanup (error); /* FIXME don't swallow the error */
/* Add to cache */
if (*klass) {
amodule_lock (amodule);
nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
if (!nspace_table) {
nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
}
g_hash_table_insert (nspace_table, (char*)name2, *klass);
amodule_unlock (amodule);
}
return TRUE;
}
if (next != 0) {
entry = &table [next * 2];
} else {
break;
}
}
}
amodule_unlock (amodule);
return TRUE;
}
GHashTable *
mono_aot_get_weak_field_indexes (MonoImage *image)
{
MonoAotModule *amodule = image->aot_module;
if (!amodule)
return NULL;
/* Initialize weak field indexes from the cached copy */
guint32 *indexes = (guint32*)amodule->weak_field_indexes;
int len = indexes [0];
GHashTable *indexes_hash = g_hash_table_new (NULL, NULL);
for (int i = 0; i < len; ++i)
g_hash_table_insert (indexes_hash, GUINT_TO_POINTER (indexes [i + 1]), GUINT_TO_POINTER (1));
return indexes_hash;
}
/* Compute the boundaries of the LLVM code for AMODULE. */
static void
compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end)
{
guint8 *p;
int version, fde_count;
gint32 *table;
if (amodule->info.llvm_get_method) {
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
#ifdef HOST_WASM
gsize min = 1 << 30, max = 0;
//gsize prev = 0;
// FIXME: This depends on emscripten allocating ftnptr ids sequentially
for (int i = 0; i < amodule->info.nmethods; ++i) {
void *addr = NULL;
addr = get_method (i);
gsize val = (gsize)addr;
if (val) {
//g_assert (val > prev);
if (val < min)
min = val;
else if (val > max)
max = val;
//prev = val;
}
}
if (max) {
*code_start = (guint8*)min;
*code_end = (guint8*)(max + 1);
} else {
*code_start = NULL;
*code_end = NULL;
}
#else
*code_start = (guint8 *)get_method (-1);
*code_end = (guint8 *)get_method (-2);
g_assert (*code_end > *code_start);
#endif
return;
}
g_assert (amodule->mono_eh_frame);
p = amodule->mono_eh_frame;
/* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
/* Header */
version = *p;
g_assert (version == 3);
p ++;
p ++;
p = (guint8 *)ALIGN_PTR_TO (p, 4);
fde_count = *(guint32*)p;
p += 4;
table = (gint32*)p;
if (fde_count > 0) {
*code_start = (guint8 *)amodule->methods [table [0]];
*code_end = (guint8*)amodule->methods [table [(fde_count - 1) * 2]] + table [fde_count * 2];
} else {
*code_start = NULL;
*code_end = NULL;
}
}
static gboolean
is_llvm_code (MonoAotModule *amodule, guint8 *code)
{
#if HOST_WASM
return TRUE;
#else
if ((guint8*)code >= amodule->llvm_code_start && (guint8*)code < amodule->llvm_code_end)
return TRUE;
else
return FALSE;
#endif
}
static gboolean
is_thumb_code (MonoAotModule *amodule, guint8 *code)
{
if (is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_THUMB))
return TRUE;
else
return FALSE;
}
/*
* decode_llvm_mono_eh_frame:
*
* Decode the EH information emitted by our modified LLVM compiler and construct a
* MonoJitInfo structure from it.
* If JINFO is NULL, set OUT_LLVM_CLAUSES to the number of llvm level clauses.
* This function is async safe when called in async context.
*/
static void
decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoJitInfo *jinfo,
guint8 *code, guint32 code_len,
MonoJitExceptionInfo *clauses, int num_clauses,
GSList **nesting,
int *this_reg, int *this_offset, int *out_llvm_clauses)
{
guint8 *p, *code1, *code2;
guint8 *fde, *cie, *code_start, *code_end;
int version, fde_count;
gint32 *table;
int i, pos, left, right;
MonoJitExceptionInfo *ei;
MonoMemoryManager *mem_manager;
guint32 fde_len, ei_len, nested_len, nindex;
gpointer *type_info;
MonoLLVMFDEInfo info;
guint8 *unw_info;
gboolean async;
mem_manager = m_image_get_mem_manager (amodule->assembly->image);
async = mono_thread_info_is_async_context ();
if (!amodule->mono_eh_frame) {
if (!jinfo) {
*out_llvm_clauses = num_clauses;
return;
}
memcpy (jinfo->clauses, clauses, num_clauses * sizeof (MonoJitExceptionInfo));
return;
}
g_assert (amodule->mono_eh_frame && code);
p = amodule->mono_eh_frame;
/* p points to data emitted by LLVM in DwarfMonoException::EmitMonoEHFrame () */
/* Header */
version = *p;
g_assert (version == 3);
p ++;
/* func_encoding = *p; */
p ++;
p = (guint8 *)ALIGN_PTR_TO (p, 4);
fde_count = *(guint32*)p;
p += 4;
table = (gint32*)p;
/* There is +1 entry in the table */
cie = p + ((fde_count + 1) * 8);
/* Binary search in the table to find the entry for code */
left = 0;
right = fde_count;
while (TRUE) {
pos = (left + right) / 2;
/* The table contains method index/fde offset pairs */
g_assert (table [(pos * 2)] != -1);
code1 = (guint8 *)amodule->methods [table [(pos * 2)]];
if (pos + 1 == fde_count) {
code2 = amodule->llvm_code_end;
} else {
g_assert (table [(pos + 1) * 2] != -1);
code2 = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
}
if (code < code1)
right = pos;
else if (code >= code2)
left = pos + 1;
else
break;
}
code_start = (guint8 *)amodule->methods [table [(pos * 2)]];
if (pos + 1 == fde_count) {
/* The +1 entry in the table contains the length of the last method */
int len = table [(pos + 1) * 2];
code_end = code_start + len;
} else {
code_end = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
}
if (!code_len)
code_len = code_end - code_start;
g_assert (code >= code_start && code < code_end);
if (is_thumb_code (amodule, code_start))
/* Clear thumb flag */
code_start = (guint8*)(((gsize)code_start) & ~1);
fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
/* This won't overflow because there is +1 entry in the table */
fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
/* Compute lengths */
mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, NULL, NULL, NULL);
if (async) {
/* These are leaked, but the leak is bounded */
ei = mono_mem_manager_alloc0_lock_free (mem_manager, info.ex_info_len * sizeof (MonoJitExceptionInfo));
type_info = mono_mem_manager_alloc0_lock_free (mem_manager, info.ex_info_len * sizeof (gpointer));
unw_info = mono_mem_manager_alloc0_lock_free (mem_manager, info.unw_info_len);
} else {
ei = (MonoJitExceptionInfo *)g_malloc0 (info.ex_info_len * sizeof (MonoJitExceptionInfo));
type_info = (gpointer *)g_malloc0 (info.ex_info_len * sizeof (gpointer));
unw_info = (guint8*)g_malloc0 (info.unw_info_len);
}
mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, ei, type_info, unw_info);
ei_len = info.ex_info_len;
*this_reg = info.this_reg;
*this_offset = info.this_offset;
/*
* LLVM might represent one IL region with multiple regions.
*/
/* Count number of nested clauses */
nested_len = 0;
for (i = 0; i < ei_len; ++i) {
/* This might be unaligned */
gint32 cindex1 = read32 (type_info [i]);
GSList *l;
for (l = nesting [cindex1]; l; l = l->next)
nested_len ++;
}
if (!jinfo) {
*out_llvm_clauses = ei_len + nested_len;
return;
}
/* Store the unwind info addr/length in the MonoJitInfo structure itself so its async safe */
MonoUnwindJitInfo *jinfo_unwind = mono_jit_info_get_unwind_info (jinfo);
g_assert (jinfo_unwind);
jinfo_unwind->unw_info = unw_info;
jinfo_unwind->unw_info_len = info.unw_info_len;
for (i = 0; i < ei_len; ++i) {
/*
* clauses contains the original IL exception info saved by the AOT
* compiler, we have to combine that with the information produced by LLVM
*/
/* The type_info entries contain IL clause indexes */
int clause_index = read32 (type_info [i]);
MonoJitExceptionInfo *jei = &jinfo->clauses [i];
MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
g_assert (clause_index < num_clauses);
jei->flags = orig_jei->flags;
jei->data.catch_class = orig_jei->data.catch_class;
jei->try_start = ei [i].try_start;
jei->try_end = ei [i].try_end;
jei->handler_start = ei [i].handler_start;
jei->clause_index = clause_index;
if (is_thumb_code (amodule, (guint8 *)jei->try_start)) {
jei->try_start = (void*)((gsize)jei->try_start & ~1);
jei->try_end = (void*)((gsize)jei->try_end & ~1);
/* Make sure we transition to thumb when a handler starts */
jei->handler_start = (void*)((gsize)jei->handler_start + 1);
}
}
/* See exception_cb () in mini-llvm.c as to why this is needed */
nindex = ei_len;
for (i = 0; i < ei_len; ++i) {
gint32 cindex1 = read32 (type_info [i]);
GSList *l;
for (l = nesting [cindex1]; l; l = l->next) {
gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
MonoJitExceptionInfo *nesting_ei;
MonoJitExceptionInfo *nesting_clause = &clauses [nesting_cindex];
nesting_ei = &jinfo->clauses [nindex];
nindex ++;
memcpy (nesting_ei, &jinfo->clauses [i], sizeof (MonoJitExceptionInfo));
nesting_ei->flags = nesting_clause->flags;
nesting_ei->data.catch_class = nesting_clause->data.catch_class;
nesting_ei->clause_index = nesting_cindex;
}
}
g_assert (nindex == ei_len + nested_len);
}
static gpointer
alloc0_jit_info_data (MonoMemoryManager *mem_manager, int size, gboolean async_context)
#define alloc0_jit_info_data(mem_manager, size, async_context) (g_cast (alloc0_jit_info_data ((mem_manager), (size), (async_context))))
{
gpointer res;
if (async_context) {
res = mono_mem_manager_alloc0_lock_free (mem_manager, size);
mono_atomic_fetch_add_i32 (&async_jit_info_size, size);
} else {
res = mono_mem_manager_alloc0 (mem_manager, size);
}
return res;
}
/*
* In async context, this is async safe.
*/
static MonoJitInfo*
decode_exception_debug_info (MonoAotModule *amodule,
MonoMethod *method, guint8* ex_info,
guint8 *code, guint32 code_len)
{
ERROR_DECL (error);
int i, buf_len, num_clauses, len;
MonoJitInfo *jinfo;
MonoJitInfoFlags flags = JIT_INFO_NONE;
guint unwind_info, eflags;
gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
gboolean from_llvm, has_gc_map;
guint8 *p;
int try_holes_info_size, num_holes;
int this_reg = 0, this_offset = 0;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (amodule->assembly->image);
gboolean async;
code = (guint8*)MINI_FTNPTR_TO_ADDR (code);
/* Load the method info from the AOT file */
async = mono_thread_info_is_async_context ();
p = ex_info;
eflags = decode_value (p, &p);
has_generic_jit_info = (eflags & 1) != 0;
has_dwarf_unwind_info = (eflags & 2) != 0;
has_clauses = (eflags & 4) != 0;
has_seq_points = (eflags & 8) != 0;
from_llvm = (eflags & 16) != 0;
has_try_block_holes = (eflags & 32) != 0;
has_gc_map = (eflags & 64) != 0;
has_arch_eh_jit_info = (eflags & 128) != 0;
if (has_dwarf_unwind_info) {
unwind_info = decode_value (p, &p);
g_assert (unwind_info < (1 << 30));
} else {
unwind_info = decode_value (p, &p);
}
if (has_generic_jit_info)
flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
if (has_try_block_holes) {
num_holes = decode_value (p, &p);
flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
} else {
num_holes = try_holes_info_size = 0;
}
if (has_arch_eh_jit_info) {
flags |= JIT_INFO_HAS_ARCH_EH_INFO;
/* Overwrite the original code_len which includes alignment padding */
code_len = decode_value (p, &p);
}
/* Exception table */
if (has_clauses)
num_clauses = decode_value (p, &p);
else
num_clauses = 0;
if (from_llvm) {
MonoJitExceptionInfo *clauses;
GSList **nesting;
/*
* Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
* section.
*/
if (async) {
if (num_clauses < 16) {
clauses = g_newa (MonoJitExceptionInfo, num_clauses);
nesting = g_newa (GSList*, num_clauses);
} else {
clauses = alloc0_jit_info_data (mem_manager, sizeof (MonoJitExceptionInfo) * num_clauses, TRUE);
nesting = alloc0_jit_info_data (mem_manager, sizeof (GSList*) * num_clauses, TRUE);
}
memset (clauses, 0, sizeof (MonoJitExceptionInfo) * num_clauses);
memset (nesting, 0, sizeof (GSList*) * num_clauses);
} else {
clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
nesting = g_new0 (GSList*, num_clauses);
}
for (i = 0; i < num_clauses; ++i) {
MonoJitExceptionInfo *ei = &clauses [i];
ei->flags = decode_value (p, &p);
if (!(ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
int len = decode_value (p, &p);
if (len > 0) {
if (async) {
p += len;
} else {
ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
}
ei->clause_index = i;
ei->try_offset = decode_value (p, &p);
ei->try_len = decode_value (p, &p);
ei->handler_offset = decode_value (p, &p);
ei->handler_len = decode_value (p, &p);
/* Read the list of nesting clauses */
while (TRUE) {
int nesting_index = decode_value (p, &p);
if (nesting_index == -1)
break;
// FIXME: async
g_assert (!async);
nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
}
}
flags |= JIT_INFO_HAS_UNWIND_INFO;
int num_llvm_clauses;
/* Get the length first */
decode_llvm_mono_eh_frame (amodule, NULL, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, &num_llvm_clauses);
len = mono_jit_info_size (flags, num_llvm_clauses, num_holes);
jinfo = (MonoJitInfo *)alloc0_jit_info_data (mem_manager, len, async);
mono_jit_info_init (jinfo, method, code, code_len, flags, num_llvm_clauses, num_holes);
decode_llvm_mono_eh_frame (amodule, jinfo, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, NULL);
if (!async) {
g_free (clauses);
for (i = 0; i < num_clauses; ++i)
g_slist_free (nesting [i]);
g_free (nesting);
}
jinfo->from_llvm = 1;
} else {
len = mono_jit_info_size (flags, num_clauses, num_holes);
jinfo = (MonoJitInfo *)alloc0_jit_info_data (mem_manager, len, async);
/* The jit info table needs to sort addresses so it contains non-authenticated pointers on arm64e */
mono_jit_info_init (jinfo, method, code, code_len, flags, num_clauses, num_holes);
for (i = 0; i < jinfo->num_clauses; ++i) {
MonoJitExceptionInfo *ei = &jinfo->clauses [i];
ei->flags = decode_value (p, &p);
#ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
/* Not used for catch clauses */
if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
ei->exvar_offset = decode_value (p, &p);
#else
ei->exvar_offset = decode_value (p, &p);
#endif
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
ei->data.filter = code + decode_value (p, &p);
} else {
int len = decode_value (p, &p);
if (len > 0) {
if (async) {
p += len;
} else {
ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
}
ei->try_start = code + decode_value (p, &p);
ei->try_end = code + decode_value (p, &p);
ei->handler_start = code + decode_value (p, &p);
/* Keep try_start/end non-authenticated, they are never branched to */
//ei->try_start = MINI_ADDR_TO_FTNPTR (ei->try_start);
//ei->try_end = MINI_ADDR_TO_FTNPTR (ei->try_end);
ei->handler_start = MINI_ADDR_TO_FTNPTR (ei->handler_start);
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ei->data.filter = MINI_ADDR_TO_FTNPTR (ei->data.filter);
else if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
ei->data.handler_end = MINI_ADDR_TO_FTNPTR (ei->data.handler_end);
}
jinfo->unwind_info = unwind_info;
jinfo->from_aot = 1;
}
if (has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table;
g_assert (jinfo->has_try_block_holes);
table = mono_jit_info_get_try_block_hole_table_info (jinfo);
g_assert (table);
table->num_holes = (guint16)num_holes;
for (i = 0; i < num_holes; ++i) {
MonoTryBlockHoleJitInfo *hole = &table->holes [i];
hole->clause = decode_value (p, &p);
hole->length = decode_value (p, &p);
hole->offset = decode_value (p, &p);
}
}
if (has_arch_eh_jit_info) {
MonoArchEHJitInfo *eh_info;
g_assert (jinfo->has_arch_eh_info);
eh_info = mono_jit_info_get_arch_eh_info (jinfo);
eh_info->stack_size = decode_value (p, &p);
eh_info->epilog_size = decode_value (p, &p);
}
if (async) {
/* The rest is not needed in async mode */
jinfo->async = TRUE;
jinfo->d.aot_info = amodule;
// FIXME: Cache
return jinfo;
}
if (has_generic_jit_info) {
MonoGenericJitInfo *gi;
int len;
g_assert (jinfo->has_generic_jit_info);
gi = mono_jit_info_get_generic_jit_info (jinfo);
g_assert (gi);
gi->nlocs = decode_value (p, &p);
if (gi->nlocs) {
gi->locations = (MonoDwarfLocListEntry *)alloc0_jit_info_data (mem_manager, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
for (i = 0; i < gi->nlocs; ++i) {
MonoDwarfLocListEntry *entry = &gi->locations [i];
entry->is_reg = decode_value (p, &p);
entry->reg = decode_value (p, &p);
if (!entry->is_reg)
entry->offset = decode_value (p, &p);
if (i > 0)
entry->from = decode_value (p, &p);
entry->to = decode_value (p, &p);
}
gi->has_this = 1;
} else {
if (from_llvm) {
gi->has_this = this_reg != -1;
gi->this_reg = this_reg;
gi->this_offset = this_offset;
} else {
gi->has_this = decode_value (p, &p);
gi->this_reg = decode_value (p, &p);
gi->this_offset = decode_value (p, &p);
}
}
len = decode_value (p, &p);
if (async) {
p += len;
} else {
jinfo->d.method = decode_resolve_method_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
gi->generic_sharing_context = alloc0_jit_info_data (mem_manager, sizeof (MonoGenericSharingContext), async);
if (decode_value (p, &p)) {
/* gsharedvt */
MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
gsctx->is_gsharedvt = TRUE;
}
}
if (method && has_seq_points) {
MonoSeqPointInfo *seq_points;
p += mono_seq_point_info_read (&seq_points, p, FALSE);
if (!async) {
// FIXME: Call a function in seq-points.c
// FIXME:
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
/* This could be set already since this function can be called more than once for the same method */
if (!g_hash_table_lookup (jit_mm->seq_points, method))
g_hash_table_insert (jit_mm->seq_points, method, seq_points);
else
mono_seq_point_info_free (seq_points);
jit_mm_unlock (jit_mm);
}
jinfo->seq_points = seq_points;
}
/* Load debug info */
buf_len = decode_value (p, &p);
if (!async)
mono_debug_add_aot_method (method, code, p, buf_len);
p += buf_len;
if (has_gc_map) {
int map_size = decode_value (p, &p);
/* The GC map requires 4 bytes of alignment */
while ((guint64)(gsize)p % 4)
p ++;
jinfo->gc_info = p;
p += map_size;
}
if (amodule != m_class_get_image (jinfo->d.method->klass)->aot_module && !async) {
mono_aot_lock ();
if (!ji_to_amodule)
ji_to_amodule = g_hash_table_new (NULL, NULL);
g_hash_table_insert (ji_to_amodule, jinfo, amodule);
mono_aot_unlock ();
}
return jinfo;
}
static gboolean
amodule_contains_code_addr (MonoAotModule *amodule, guint8 *code)
{
return (code >= amodule->jit_code_start && code <= amodule->jit_code_end) ||
(code >= amodule->llvm_code_start && code <= amodule->llvm_code_end);
}
/*
* mono_aot_get_unwind_info:
*
* Return a pointer to the DWARF unwind info belonging to JI.
*/
guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
MonoAotModule *amodule;
guint8 *p;
guint8 *code = (guint8 *)ji->code_start;
if (ji->async)
amodule = ji->d.aot_info;
else
amodule = m_class_get_image (jinfo_get_method (ji)->klass)->aot_module;
g_assert (amodule);
g_assert (ji->from_aot);
if (!amodule_contains_code_addr (amodule, code)) {
/* ji belongs to a different aot module than amodule */
mono_aot_lock ();
g_assert (ji_to_amodule);
amodule = (MonoAotModule *)g_hash_table_lookup (ji_to_amodule, ji);
g_assert (amodule);
g_assert (amodule_contains_code_addr (amodule, code));
mono_aot_unlock ();
}
p = amodule->unwind_info + ji->unwind_info;
*unwind_info_len = decode_value (p, &p);
return p;
}
static void
msort_method_addresses_internal (gpointer *array, int *indexes, int lo, int hi, gpointer *scratch, int *scratch_indexes)
{
int mid = (lo + hi) / 2;
int i, t_lo, t_hi;
if (lo >= hi)
return;
if (hi - lo < 32) {
for (i = lo; i < hi; ++i)
if (array [i] > array [i + 1])
break;
if (i == hi)
/* Already sorted */
return;
}
msort_method_addresses_internal (array, indexes, lo, mid, scratch, scratch_indexes);
msort_method_addresses_internal (array, indexes, mid + 1, hi, scratch, scratch_indexes);
if (array [mid] < array [mid + 1])
return;
/* Merge */
t_lo = lo;
t_hi = mid + 1;
for (i = lo; i <= hi; i ++) {
if (t_lo <= mid && ((t_hi > hi) || array [t_lo] < array [t_hi])) {
scratch [i] = array [t_lo];
scratch_indexes [i] = indexes [t_lo];
t_lo ++;
} else {
scratch [i] = array [t_hi];
scratch_indexes [i] = indexes [t_hi];
t_hi ++;
}
}
for (i = lo; i <= hi; ++i) {
array [i] = scratch [i];
indexes [i] = scratch_indexes [i];
}
}
static void
msort_method_addresses (gpointer *array, int *indexes, int len)
{
gpointer *scratch;
int *scratch_indexes;
scratch = g_new (gpointer, len);
scratch_indexes = g_new (int, len);
msort_method_addresses_internal (array, indexes, 0, len - 1, scratch, scratch_indexes);
g_free (scratch);
g_free (scratch_indexes);
}
static void
sort_methods (MonoAotModule *amodule)
{
int nmethods = amodule->info.nmethods;
/* Compute a sorted table mapping code to method indexes. */
if (amodule->sorted_methods)
return;
// FIXME: async
gpointer *methods = g_new0 (gpointer, nmethods);
int *method_indexes = g_new0 (int, nmethods);
int methods_len = 0;
for (int i = 0; i < nmethods; ++i) {
/* Skip the -1 entries to speed up sorting */
if (amodule->methods [i] == GINT_TO_POINTER (-1))
continue;
methods [methods_len] = amodule->methods [i];
method_indexes [methods_len] = i;
methods_len ++;
}
/* Use a merge sort as this is mostly sorted */
msort_method_addresses (methods, method_indexes, methods_len);
for (int i = 0; i < methods_len -1; ++i)
g_assert (methods [i] <= methods [i + 1]);
amodule->sorted_methods_len = methods_len;
if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_methods, methods, NULL) != NULL)
/* Somebody got in before us */
g_free (methods);
if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_method_indexes, method_indexes, NULL) != NULL)
/* Somebody got in before us */
g_free (method_indexes);
}
/*
* mono_aot_find_jit_info:
*
* In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
* to the jit info tables.
* FIXME: Large sizes in the lock free allocator
*/
MonoJitInfo *
mono_aot_find_jit_info (MonoImage *image, gpointer addr)
{
ERROR_DECL (error);
int pos, left, right, code_len;
int method_index, table_len;
guint32 token;
MonoAotModule *amodule = image->aot_module;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (image);
MonoMethod *method = NULL;
MonoJitInfo *jinfo;
guint8 *code, *ex_info, *p;
guint32 *table;
gpointer *methods;
guint8 *code1, *code2;
int methods_len;
gboolean async;
if (!amodule)
return NULL;
addr = MINI_FTNPTR_TO_ADDR (addr);
if (!amodule_contains_code_addr (amodule, (guint8 *)addr))
return NULL;
async = mono_thread_info_is_async_context ();
sort_methods (amodule);
/* Binary search in the sorted_methods table */
methods = amodule->sorted_methods;
methods_len = amodule->sorted_methods_len;
code = (guint8 *)addr;
left = 0;
right = methods_len;
while (TRUE) {
pos = (left + right) / 2;
code1 = (guint8 *)methods [pos];
if (pos + 1 == methods_len) {
#ifdef HOST_WASM
code2 = code1 + 1;
#else
if (code1 >= amodule->jit_code_start && code1 < amodule->jit_code_end)
code2 = amodule->jit_code_end;
else
code2 = amodule->llvm_code_end;
#endif
} else {
code2 = (guint8 *)methods [pos + 1];
}
if (code < code1)
right = pos;
else if (code >= code2)
left = pos + 1;
else
break;
}
#ifdef HOST_WASM
if (addr != methods [pos])
return NULL;
#endif
g_assert (addr >= methods [pos]);
if (pos + 1 < methods_len)
g_assert (addr < methods [pos + 1]);
method_index = amodule->sorted_method_indexes [pos];
/* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
if (async) {
JitInfoMap **table = amodule->async_jit_info_table;
LOAD_ACQUIRE_FENCE;
if (table) {
int buckets = (amodule->info.nmethods / JIT_INFO_MAP_BUCKET_SIZE) + 1;
JitInfoMap *current_item = table [method_index % buckets];
LOAD_ACQUIRE_FENCE;
while (current_item) {
if (current_item->method_index == method_index)
return current_item->jinfo;
current_item = current_item->next;
LOAD_ACQUIRE_FENCE;
}
}
}
code = (guint8 *)amodule->methods [method_index];
ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
#ifdef HOST_WASM
/* WASM methods have no length, can only look up the method address */
code_len = 1;
#else
if (pos == methods_len - 1) {
if (code >= amodule->jit_code_start && code < amodule->jit_code_end)
code_len = amodule->jit_code_end - code;
else
code_len = amodule->llvm_code_end - code;
} else {
guint8* code_end = (guint8*)methods [pos + 1];
if (code >= amodule->jit_code_start && code < amodule->jit_code_end && code_end > amodule->jit_code_end) {
code_end = amodule->jit_code_end;
}
if (code >= amodule->llvm_code_start && code < amodule->llvm_code_end && code_end > amodule->llvm_code_end) {
code_end = amodule->llvm_code_end;
}
code_len = code_end - code;
}
#endif
g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
/* Might be a wrapper/extra method */
if (!async) {
if (amodule->extra_methods) {
amodule_lock (amodule);
method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
amodule_unlock (amodule);
} else {
method = NULL;
}
if (!method) {
if (method_index >= table_info_get_rows (&image->tables [MONO_TABLE_METHOD])) {
/*
* This is hit for extra methods which are called directly, so they are
* not in amodule->extra_methods.
*/
table_len = amodule->extra_method_info_offsets [0];
table = amodule->extra_method_info_offsets + 1;
left = 0;
right = table_len;
pos = 0;
/* Binary search */
while (TRUE) {
pos = ((left + right) / 2);
g_assert (pos < table_len);
if (table [pos * 2] < method_index)
left = pos + 1;
else if (table [pos * 2] > method_index)
right = pos;
else
break;
}
p = amodule->blob + table [(pos * 2) + 1];
method = decode_resolve_method_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!method)
/* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
return NULL;
} else {
ERROR_DECL (error);
token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
}
}
/* FIXME: */
g_assert (method);
}
//printf ("F: %s\n", mono_method_full_name (method, TRUE));
jinfo = decode_exception_debug_info (amodule, method, ex_info, code, code_len);
g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
if (async) {
/* Add it to the async JitInfo tables */
JitInfoMap **current_table, **new_table;
JitInfoMap *current_item, *new_item;
int buckets = (amodule->info.nmethods / JIT_INFO_MAP_BUCKET_SIZE) + 1;
for (;;) {
current_table = amodule->async_jit_info_table;
LOAD_ACQUIRE_FENCE;
if (current_table)
break;
new_table = alloc0_jit_info_data (mem_manager, buckets * sizeof (JitInfoMap*), async);
STORE_RELEASE_FENCE;
if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table, new_table, current_table) == current_table)
break;
}
new_item = alloc0_jit_info_data (mem_manager, sizeof (JitInfoMap), async);
new_item->method_index = method_index;
new_item->jinfo = jinfo;
for (;;) {
current_item = amodule->async_jit_info_table [method_index % buckets];
LOAD_ACQUIRE_FENCE;
new_item->next = current_item;
STORE_RELEASE_FENCE;
if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table [method_index % buckets], new_item, current_item) == current_item)
break;
}
} else {
/* Add it to the normal JitInfo tables */
mono_jit_info_table_add (jinfo);
}
if ((guint8*)addr >= (guint8*)jinfo->code_start + jinfo->code_size)
/* addr is in the padding between methods, see the adjustment of code_size in decode_exception_debug_info () */
return NULL;
return jinfo;
}
static gboolean
decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
guint8 *p = buf;
gpointer *table;
MonoImage *image;
int i;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (aot_module->assembly->image);
switch (ji->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
MethodRef ref;
gboolean res;
res = decode_method_ref (aot_module, &ref, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
goto cleanup;
if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
ji->data.target = mono_create_ftnptr (mono_create_jit_trampoline_from_token (ref.image, ref.token));
ji->type = MONO_PATCH_INFO_ABS;
}
else {
if (ref.method) {
ji->data.method = ref.method;
}else {
ERROR_DECL (error);
ji->data.method = mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
if (!ji->data.method)
g_error ("AOT Runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
}
g_assert (ji->data.method);
mono_class_init_internal (ji->data.method->klass);
}
break;
}
case MONO_PATCH_INFO_LDSTR_LIT:
{
guint32 len = decode_value (p, &p);
ji->data.name = (char*)p;
p += len + 1;
break;
}
case MONO_PATCH_INFO_METHODCONST:
/* Shared */
ji->data.method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.method)
goto cleanup;
break;
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
/* Shared */
ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.klass)
goto cleanup;
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
ji->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.del_tramp->klass)
goto cleanup;
if (decode_value (p, &p)) {
ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.del_tramp->method)
goto cleanup;
}
ji->data.del_tramp->is_virtual = decode_value (p, &p) ? TRUE : FALSE;
break;
case MONO_PATCH_INFO_IMAGE:
ji->data.image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.image)
goto cleanup;
break;
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
/* Shared */
ji->data.field = decode_field_info (aot_module, p, &p);
if (!ji->data.field)
goto cleanup;
break;
case MONO_PATCH_INFO_SWITCH:
ji->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
ji->data.table->table_size = decode_value (p, &p);
table = (void **)mono_mem_manager_alloc (mem_manager, sizeof (gpointer) * ji->data.table->table_size);
ji->data.table->table = (MonoBasicBlock**)table;
for (i = 0; i < ji->data.table->table_size; i++)
table [i] = (gpointer)(gssize)decode_value (p, &p);
break;
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT: {
guint32 val;
ji->data.target = mono_mem_manager_alloc0 (mem_manager, sizeof (float));
val = decode_value (p, &p);
*(float*)ji->data.target = *(float*)&val;
break;
}
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT: {
guint32 val [2];
guint64 v;
// FIXME: Align to 16 bytes ?
ji->data.target = mono_mem_manager_alloc0 (mem_manager, sizeof (double));
val [0] = decode_value (p, &p);
val [1] = decode_value (p, &p);
v = ((guint64)val [1] << 32) | ((guint64)val [0]);
*(double*)ji->data.target = *(double*)&v;
break;
}
case MONO_PATCH_INFO_LDSTR:
image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!image)
goto cleanup;
ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
break;
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_DECLSEC:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
/* Shared */
image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!image)
goto cleanup;
ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
ji->data.token->has_context = decode_value (p, &p);
if (ji->data.token->has_context) {
gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!res)
goto cleanup;
}
break;
case MONO_PATCH_INFO_EXC_NAME:
ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.klass)
goto cleanup;
ji->data.name = m_class_get_name (ji->data.klass);
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
break;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
ji->data.uindex = decode_value (p, &p);
break;
case MONO_PATCH_INFO_CASTCLASS_CACHE:
ji->data.index = decode_value (p, &p);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
ji->data.jit_icall_id = (MonoJitICallId)decode_value (p, &p);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
gboolean res;
MonoJumpInfoRgctxEntry *entry;
guint32 offset, val;
guint8 *p2;
offset = decode_value (p, &p);
val = decode_value (p, &p);
entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
p2 = aot_module->blob + offset;
entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
if (entry->in_mrgctx)
entry->d.method = decode_resolve_method_ref (aot_module, p2, &p2, error);
else
entry->d.klass = decode_klass_ref (aot_module, p2, &p2, error);
entry->info_type = (MonoRgctxInfoType)((val >> 1) & 0xff);
entry->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
entry->data->type = (MonoJumpInfoType)((val >> 9) & 0xff);
mono_error_cleanup (error); /* FIXME don't swallow the error */
res = decode_patch (aot_module, mp, entry->data, p, &p);
if (!res)
goto cleanup;
ji->data.rgctx_entry = entry;
break;
}
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_AOT_MODULE:
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
break;
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
ji->data.target = decode_signature (aot_module, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL: {
MonoJumpInfoGSharedVtCall *info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
info->sig = decode_signature (aot_module, p, &p);
g_assert (info->sig);
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
int i;
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
info->num_entries = decode_value (p, &p);
info->count_entries = info->num_entries;
info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
for (i = 0; i < info->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
template_->info_type = (MonoRgctxInfoType)decode_value (p, &p);
switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
case MONO_PATCH_INFO_CLASS: {
MonoClass *klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!klass)
goto cleanup;
template_->data = m_class_get_byval_arg (klass);
break;
}
case MONO_PATCH_INFO_FIELD:
template_->data = decode_field_info (aot_module, p, &p);
if (!template_->data)
goto cleanup;
break;
case MONO_PATCH_INFO_METHOD:
template_->data = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!template_->data)
goto cleanup;
break;
default:
g_assert_not_reached ();
break;
}
}
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
info->klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
break;
case MONO_PATCH_INFO_AOT_JIT_INFO:
ji->data.index = decode_value (p, &p);
break;
default:
g_error ("unhandled type %d", ji->type);
break;
}
*endbuf = p;
return TRUE;
cleanup:
return FALSE;
}
/*
* decode_patches:
*
* Decode a list of patches identified by the got offsets in GOT_OFFSETS. Return an array of
* MonoJumpInfo structures allocated from MP. GOT entries already loaded have their
* ji->type set to MONO_PATCH_INFO_NONE.
*/
static MonoJumpInfo*
decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets)
{
MonoJumpInfo *patches;
MonoJumpInfo *ji;
gpointer *got;
guint32 *got_info_offsets;
int i;
gboolean res;
if (llvm) {
got = amodule->llvm_got;
got_info_offsets = (guint32 *)amodule->llvm_got_info_offsets;
} else {
got = amodule->got;
got_info_offsets = (guint32 *)amodule->got_info_offsets;
}
patches = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
for (i = 0; i < n_patches; ++i) {
guint8 *p = amodule->blob + mono_aot_get_offset (got_info_offsets, got_offsets [i]);
ji = &patches [i];
ji->type = (MonoJumpInfoType)decode_value (p, &p);
/* See load_method () for SFLDA */
if (got && got [got_offsets [i]] && ji->type != MONO_PATCH_INFO_SFLDA) {
/* Already loaded */
ji->type = MONO_PATCH_INFO_NONE;
} else {
res = decode_patch (amodule, mp, ji, p, &p);
if (!res)
return NULL;
}
}
return patches;
}
static MonoJumpInfo*
load_patch_info (MonoAotModule *amodule, MonoMemPool *mp, int n_patches,
gboolean llvm, guint32 **got_slots,
guint8 *buf, guint8 **endbuf)
{
MonoJumpInfo *patches;
int pindex;
guint8 *p;
p = buf;
*got_slots = (guint32 *)g_malloc (sizeof (guint32) * n_patches);
for (pindex = 0; pindex < n_patches; ++pindex) {
(*got_slots)[pindex] = decode_value (p, &p);
}
patches = decode_patches (amodule, mp, n_patches, llvm, *got_slots);
if (!patches) {
g_free (*got_slots);
*got_slots = NULL;
return NULL;
}
*endbuf = p;
return patches;
}
static void
register_jump_target_got_slot (MonoMethod *method, gpointer *got_slot)
{
/*
* Jump addresses cannot be patched by the trampoline code since it
* does not have access to the caller's address. Instead, we collect
* the addresses of the GOT slots pointing to a method, and patch
* them after the method has been compiled.
*/
GSList *list;
MonoJitMemoryManager *jit_mm;
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
if (!jit_mm->jump_target_got_slot_hash)
jit_mm->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
list = (GSList *)g_hash_table_lookup (jit_mm->jump_target_got_slot_hash, method);
list = g_slist_prepend (list, got_slot);
g_hash_table_insert (jit_mm->jump_target_got_slot_hash, method, list);
jit_mm_unlock (jit_mm);
}
/*
* load_method:
*
* Load the method identified by METHOD_INDEX from the AOT image. Return a
* pointer to the native code of the method, or NULL if not found.
* METHOD might not be set if the caller only has the image/token info.
*/
static gpointer
load_method (MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index,
MonoError *error)
{
MonoJitInfo *jinfo = NULL;
guint8 *code = NULL, *info;
gboolean res;
error_init (error);
init_amodule_got (amodule, FALSE);
if (amodule->out_of_date)
return NULL;
if (amodule->info.llvm_get_method) {
/*
* Obtain the method address by calling a generated function in the LLVM module.
*/
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
code = (guint8 *)get_method (method_index);
}
if (!code) {
if (method_index < amodule->info.nmethods)
code = (guint8*)MINI_ADDR_TO_FTNPTR ((guint8 *)amodule->methods [method_index]);
else
return NULL;
/* JITted method */
if (amodule->methods [method_index] == GINT_TO_POINTER (-1)) {
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
full_name = mono_method_full_name (method, TRUE);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: NOT FOUND: %s.", full_name);
g_free (full_name);
}
}
return NULL;
}
}
info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
if (!amodule->methods_loaded) {
amodule_lock (amodule);
if (!amodule->methods_loaded) {
guint32 *loaded;
loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
mono_memory_barrier ();
amodule->methods_loaded = loaded;
}
amodule_unlock (amodule);
}
if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
return code;
if (mini_debug_options.aot_skip_set && !(method && method->wrapper_type)) {
gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
methods_aot += mono_atomic_load_i32 (&mono_jit_stats.methods_aot_llvm);
if (methods_aot == mini_debug_options.aot_skip) {
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (method) {
char *name = mono_method_full_name (method, TRUE);
g_print ("NON AOT METHOD: %s.\n", name);
g_free (name);
} else {
g_print ("NON AOT METHOD: %p %d\n", code, method_index);
}
mini_debug_options.aot_skip_set = FALSE;
return NULL;
}
}
if (mono_last_aot_method != -1) {
gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
methods_aot += mono_atomic_load_i32 (&mono_jit_stats.methods_aot_llvm);
if (methods_aot >= mono_last_aot_method)
return NULL;
else if (methods_aot == mono_last_aot_method - 1) {
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (method) {
char *name = mono_method_full_name (method, TRUE);
g_print ("LAST AOT METHOD: %s.\n", name);
g_free (name);
} else {
g_print ("LAST AOT METHOD: %p %d\n", code, method_index);
}
}
}
if (!(is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) ||
(mono_llvm_only && method && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)) {
/* offset == 0 means its llvm code */
if (mono_aot_get_offset (amodule->method_info_offsets, method_index) != 0) {
res = init_method (amodule, NULL, method_index, method, NULL, error);
if (!res)
goto cleanup;
}
}
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
full_name = mono_method_full_name (method, TRUE);
if (!jinfo)
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
g_free (full_name);
}
if (mono_llvm_only) {
guint8 flags = amodule->method_flags_table [method_index];
/* The caller needs to looks this up, but its hard to do without constructing the full MonoJitInfo, so save it here */
if (flags & (MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE | MONO_AOT_METHOD_FLAG_INTERP_ENTRY_ONLY)) {
mono_aot_lock ();
if (!code_to_method_flags)
code_to_method_flags = g_hash_table_new (NULL, NULL);
g_hash_table_insert (code_to_method_flags, code, GUINT_TO_POINTER (flags));
mono_aot_unlock ();
}
}
init_plt (amodule);
amodule_lock (amodule);
if (is_llvm_code (amodule, code))
mono_atomic_inc_i32 (&mono_jit_stats.methods_aot_llvm);
else
mono_atomic_inc_i32 (&mono_jit_stats.methods_aot);
if (method && method->wrapper_type)
g_hash_table_insert (amodule->method_to_code, method, code);
/* Commit changes since methods_loaded is accessed outside the lock */
mono_memory_barrier ();
amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
amodule_unlock (amodule);
if (MONO_PROFILER_ENABLED (jit_begin) || MONO_PROFILER_ENABLED (jit_done)) {
MonoJitInfo *jinfo;
if (!method) {
method = mono_get_method_checked (amodule->assembly->image, token, NULL, NULL, error);
if (!method)
return NULL;
}
MONO_PROFILER_RAISE (jit_begin, (method));
jinfo = mono_jit_info_table_find_internal (code, TRUE, FALSE);
g_assert (jinfo);
MONO_PROFILER_RAISE (jit_done, (method, jinfo));
}
return code;
cleanup:
if (jinfo)
g_free (jinfo);
return NULL;
}
/** find_aot_method_in_amodule
*
* \param code_amodule The AOT module containing the code pointer
* \param method The method to find the code index for
* \param hash_full The hash for the method
*/
static guint32
find_aot_method_in_amodule (MonoAotModule *code_amodule, MonoMethod *method, guint32 hash_full)
{
ERROR_DECL (error);
guint32 table_size, entry_size, hash;
guint32 *table, *entry;
guint32 index;
static guint32 n_extra_decodes;
// The AOT module containing the MonoMethod
// The reference to the metadata amodule will differ among multiple dedup methods
// which mangle to the same name but live in different assemblies. This leads to
// the caching breaking. The solution seems to be to cache using the "metadata" amodule.
MonoAotModule *metadata_amodule = m_class_get_image (method->klass)->aot_module;
if (!metadata_amodule || metadata_amodule->out_of_date || !code_amodule || code_amodule->out_of_date)
return 0xffffff;
table_size = code_amodule->extra_method_table [0];
hash = hash_full % table_size;
table = code_amodule->extra_method_table + 1;
entry_size = 3;
entry = &table [hash * entry_size];
if (entry [0] == 0)
return 0xffffff;
index = 0xffffff;
while (TRUE) {
guint32 key = entry [0];
guint32 value = entry [1];
guint32 next = entry [entry_size - 1];
MonoMethod *m;
guint8 *p, *orig_p;
p = code_amodule->blob + key;
orig_p = p;
amodule_lock (metadata_amodule);
if (!metadata_amodule->method_ref_to_method)
metadata_amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
m = (MonoMethod *)g_hash_table_lookup (metadata_amodule->method_ref_to_method, p);
amodule_unlock (metadata_amodule);
if (!m) {
m = decode_resolve_method_ref_with_target (code_amodule, method, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
/*
* Can't catche runtime invoke wrappers since it would break
* the check in decode_method_ref_with_target ().
*/
if (m && m->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
amodule_lock (metadata_amodule);
g_hash_table_insert (metadata_amodule->method_ref_to_method, orig_p, m);
amodule_unlock (metadata_amodule);
}
}
if (m == method) {
index = value;
break;
}
/* Methods decoded needlessly */
if (m) {
//printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
n_extra_decodes ++;
}
if (next != 0)
entry = &table [next * entry_size];
else
break;
}
if (index != 0xffffff)
g_assert (index < code_amodule->info.nmethods);
return index;
}
static void
add_module_cb (gpointer key, gpointer value, gpointer user_data)
{
g_ptr_array_add ((GPtrArray*)user_data, value);
}
static gboolean
inst_is_private (MonoGenericInst *inst)
{
for (int i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if ((t->type == MONO_TYPE_CLASS || t->type == MONO_TYPE_VALUETYPE)) {
int access_level = mono_class_get_flags (t->data.klass) & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (access_level == TYPE_ATTRIBUTE_NESTED_PRIVATE || access_level == TYPE_ATTRIBUTE_NOT_PUBLIC)
return TRUE;
}
}
return FALSE;
}
gboolean
mono_aot_can_dedup (MonoMethod *method)
{
#ifdef TARGET_WASM
/* Use a set of wrappers/instances which work and useful */
switch (method->wrapper_type) {
case MONO_WRAPPER_RUNTIME_INVOKE:
return TRUE;
break;
case MONO_WRAPPER_OTHER: {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR ||
info->subtype == WRAPPER_SUBTYPE_INTERP_LMF ||
info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
return FALSE;
#if 0
// See is_linkonce_method () in mini-llvm.c
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
/* Handled using linkonce */
return FALSE;
#endif
return TRUE;
}
default:
break;
}
if (method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) &&
!mini_is_gsharedvt_signature (mono_method_signature_internal (method)) &&
!mini_is_gsharedvt_klass (method->klass)) {
MonoGenericContext *context = mono_method_get_context (method);
if (context->method_inst && mini_is_gsharedvt_inst (context->method_inst))
return FALSE;
/* No point in dedup-ing private instances */
if ((context->class_inst && inst_is_private (context->class_inst)) ||
(context->method_inst && inst_is_private (context->method_inst)))
return FALSE;
return TRUE;
}
return FALSE;
#else
gboolean not_normal_gshared = method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE);
gboolean extra_method = (method->wrapper_type != MONO_WRAPPER_NONE) || not_normal_gshared;
return extra_method;
#endif
}
/*
* find_aot_method:
*
* Try finding METHOD in the extra_method table in all AOT images.
* Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
* module where the method was found.
*/
static guint32
find_aot_method (MonoMethod *method, MonoAotModule **out_amodule)
{
guint32 index;
GPtrArray *modules;
int i;
guint32 hash = mono_aot_method_hash (method);
/* Try the place we expect to have moved the method only
* We don't probe, as that causes hard-to-debug issues when we fail
* to find the method */
if (container_amodule && mono_aot_can_dedup (method)) {
*out_amodule = container_amodule;
index = find_aot_method_in_amodule (container_amodule, method, hash);
return index;
}
/* Try the method's module first */
*out_amodule = m_class_get_image (method->klass)->aot_module;
index = find_aot_method_in_amodule (m_class_get_image (method->klass)->aot_module, method, hash);
if (index != 0xffffff)
return index;
/*
* Try all other modules.
* This is needed because generic instances klass->image points to the image
* containing the generic definition, but the native code is generated to the
* AOT image which contains the reference.
*/
/* Make a copy to avoid doing the search inside the aot lock */
modules = g_ptr_array_new ();
mono_aot_lock ();
g_hash_table_foreach (aot_modules, add_module_cb, modules);
mono_aot_unlock ();
index = 0xffffff;
for (i = 0; i < modules->len; ++i) {
MonoAotModule *amodule = (MonoAotModule *)g_ptr_array_index (modules, i);
if (amodule != m_class_get_image (method->klass)->aot_module)
index = find_aot_method_in_amodule (amodule, method, hash);
if (index != 0xffffff) {
*out_amodule = amodule;
break;
}
}
g_ptr_array_free (modules, TRUE);
return index;
}
guint32
mono_aot_find_method_index (MonoMethod *method)
{
MonoAotModule *out_amodule;
return find_aot_method (method, &out_amodule);
}
static gboolean
init_method (MonoAotModule *amodule, gpointer info, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoError *error)
{
MonoMemPool *mp;
MonoClass *klass_to_run_ctor = NULL;
gboolean from_plt = method == NULL;
int pindex, n_patches;
guint8 *p;
MonoJitInfo *jinfo = NULL;
guint8 *code;
MonoGenericContext *context;
MonoGenericContext ctx;
/* Might be needed if the method is externally called */
init_plt (amodule);
init_amodule_got (amodule, FALSE);
memset (&ctx, 0, sizeof (ctx));
error_init (error);
if (!info)
info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
p = (guint8*)info;
// FIXME: Is this aligned ?
guint32 encoded_method_index = *(guint32*)p;
if (method_index)
g_assert (method_index == encoded_method_index);
method_index = encoded_method_index;
p += 4;
code = (guint8 *)amodule->methods [method_index];
guint8 flags = amodule->method_flags_table [method_index];
if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
klass_to_run_ctor = decode_klass_ref (amodule, p, &p, error);
if (!is_ok (error))
return FALSE;
//FIXME old code would use the class from @method if not null and ignore the one encoded. I don't know if we need to honor that -- @kumpera
if (method)
klass_to_run_ctor = method->klass;
context = NULL;
if (flags & MONO_AOT_METHOD_FLAG_HAS_CTX) {
decode_generic_context (amodule, &ctx, p, &p, error);
mono_error_assert_ok (error);
context = &ctx;
}
if (flags & MONO_AOT_METHOD_FLAG_HAS_PATCHES)
n_patches = decode_value (p, &p);
else
n_patches = 0;
if (n_patches) {
MonoJumpInfo *patches;
guint32 *got_slots;
gboolean llvm;
gpointer *got;
mp = mono_mempool_new ();
if ((gpointer)code >= amodule->info.jit_code_start && (gpointer)code <= amodule->info.jit_code_end) {
llvm = FALSE;
got = amodule->got;
} else {
llvm = TRUE;
got = amodule->llvm_got;
g_assert (got);
}
patches = load_patch_info (amodule, mp, n_patches, llvm, &got_slots, p, &p);
if (patches == NULL) {
mono_mempool_destroy (mp);
goto cleanup;
}
for (pindex = 0; pindex < n_patches; ++pindex) {
MonoJumpInfo *ji = &patches [pindex];
gpointer addr;
/*
* For SFLDA, we need to call resolve_patch_target () since the GOT slot could have
* been initialized by load_method () for a static cctor before the cctor has
* finished executing (#23242).
*/
if (ji->type == MONO_PATCH_INFO_NONE) {
} else if (!got [got_slots [pindex]] || ji->type == MONO_PATCH_INFO_SFLDA) {
/* In llvm-only made, we might encounter shared methods */
if (mono_llvm_only && ji->type == MONO_PATCH_INFO_METHOD && mono_method_check_context_used (ji->data.method)) {
g_assert (context);
ji->data.method = mono_class_inflate_generic_method_checked (ji->data.method, context, error);
if (!is_ok (error)) {
g_free (got_slots);
mono_mempool_destroy (mp);
return FALSE;
}
}
/* This cannot be resolved in mono_resolve_patch_target () */
if (ji->type == MONO_PATCH_INFO_AOT_JIT_INFO) {
// FIXME: Lookup using the index
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
ji->type = MONO_PATCH_INFO_ABS;
ji->data.target = jinfo;
}
addr = mono_resolve_patch_target (method, code, ji, TRUE, error);
if (!is_ok (error)) {
g_free (got_slots);
mono_mempool_destroy (mp);
return FALSE;
}
if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
addr = mono_create_ftnptr (addr);
mono_memory_barrier ();
got [got_slots [pindex]] = addr;
if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
register_jump_target_got_slot (ji->data.method, &(got [got_slots [pindex]]));
if (llvm) {
void (*init_aotconst) (int, gpointer) = (void (*)(int, gpointer))amodule->info.llvm_init_aotconst;
init_aotconst (got_slots [pindex], addr);
}
}
ji->type = MONO_PATCH_INFO_NONE;
}
g_free (got_slots);
mono_mempool_destroy (mp);
}
if (mini_debug_options.load_aot_jit_info_eagerly)
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
gboolean inited_ok;
inited_ok = TRUE;
if (init_class) {
MonoVTable *vt = mono_class_vtable_checked (init_class, error);
if (!is_ok (error))
inited_ok = FALSE;
else
inited_ok = mono_runtime_class_init_full (vt, error);
} else if (from_plt && klass_to_run_ctor && !mono_class_is_gtd (klass_to_run_ctor)) {
MonoVTable *vt = mono_class_vtable_checked (klass_to_run_ctor, error);
if (!is_ok (error))
inited_ok = FALSE;
else
inited_ok = mono_runtime_class_init_full (vt, error);
}
if (!inited_ok)
return FALSE;
return TRUE;
cleanup:
if (jinfo)
g_free (jinfo);
return FALSE;
}
/*
* mono_aot_init_llvm_method:
*
* Initialize the LLVM method identified by METHOD_INFO.
*/
gboolean
mono_aot_init_llvm_method (gpointer aot_module, gpointer method_info, MonoClass *init_class, MonoError *error)
{
MonoAotModule *amodule = (MonoAotModule*)aot_module;
return init_method (amodule, method_info, 0, NULL, init_class, error);
}
/*
* mono_aot_get_method:
*
* Return a pointer to the AOTed native code for METHOD if it can be found,
* NULL otherwise.
* On platforms with function pointers, this doesn't return a function pointer.
*/
gpointer
mono_aot_get_method (MonoMethod *method, MonoError *error)
{
MonoClass *klass = method->klass;
MonoMethod *orig_method = method;
guint32 method_index;
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *code;
gboolean cache_result = FALSE;
ERROR_DECL (inner_error);
error_init (error);
if (!amodule)
return NULL;
if (amodule->out_of_date)
return NULL;
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT))
return NULL;
/* Load the dedup module lazily */
load_container_amodule (mono_assembly_get_alc (amodule->assembly));
g_assert (m_class_is_inited (klass));
/* Find method index */
method_index = 0xffffff;
gboolean dedupable = mono_aot_can_dedup (method);
if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) && !dedupable) {
MonoMethod *orig_method = method;
/*
* For generic methods, we store the fully shared instance in place of the
* original method.
*/
method = mono_method_get_declaring_generic_method (method);
method_index = mono_metadata_token_index (method->token) - 1;
if (amodule->info.flags & MONO_AOT_FILE_FLAG_WITH_LLVM) {
/* Needed by mini_llvm_init_gshared_method_this () */
/* orig_method is a random instance but it is enough to make init_method () work */
amodule_lock (amodule);
g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), orig_method);
amodule_unlock (amodule);
}
}
if (method_index == 0xffffff && (method->is_inflated || !method->token)) {
/* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
amodule_lock (amodule);
code = (guint8 *)g_hash_table_lookup (amodule->method_to_code, method);
amodule_unlock (amodule);
if (code)
return code;
cache_result = TRUE;
if (method_index == 0xffffff)
method_index = find_aot_method (method, &amodule);
/*
* Special case the ICollection<T> wrappers for arrays, as they cannot
* be statically enumerated, and each wrapper ends up calling the same
* method in Array.
*/
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && m_class_get_rank (method->klass) && strstr (method->name, "System.Collections.Generic")) {
MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
/*
* Special case Array.GetGenericValue_icall which is a generic icall.
* Generic sharing currently can't handle it, but the icall returns data using
* an out parameter, so the managed-to-native wrappers can share the same code.
*/
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValue_icall")) {
MonoMethod *m;
MonoGenericContext ctx;
if (mono_method_signature_internal (method)->params [1]->type == MONO_TYPE_OBJECT)
/* Avoid recursion */
return NULL;
m = mono_class_get_method_from_name_checked (mono_defaults.array_class, "GetGenericValue_icall", 3, 0, error);
mono_error_assert_ok (error);
g_assert (m);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (mono_defaults.object_class) };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
if (!m)
g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
/*
* Get the code for the <object> instantiation which should be emitted into
* the mscorlib aot image by the AOT compiler.
*/
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
/* For ARRAY_ACCESSOR wrappers with reference types, use the <object> instantiation saved in corlib */
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
MonoMethod *array_method = info->d.array_accessor.method;
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (array_method->klass)))) {
int rank;
if (!strcmp (array_method->name, "Set"))
rank = mono_method_signature_internal (array_method)->param_count - 1;
else if (!strcmp (array_method->name, "Get") || !strcmp (array_method->name, "Address"))
rank = mono_method_signature_internal (array_method)->param_count;
else
g_assert_not_reached ();
MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, rank);
MonoMethod *m = mono_class_get_method_from_name_checked (obj_array_class, array_method->name, mono_method_signature_internal (array_method)->param_count, 0, error);
mono_error_assert_ok (error);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
if (m != method) {
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
}
}
}
if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
/* Partial sharing */
MonoMethod *shared;
shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
return_val_if_nok (error, NULL);
method_index = find_aot_method (shared, &amodule);
if (method_index != 0xffffff)
method = shared;
}
if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
MonoMethod *shared;
/* gsharedvt */
/* Use the all-vt shared method since this is what was AOTed */
shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
if (!shared)
return NULL;
method_index = find_aot_method (shared, &amodule);
if (method_index != 0xffffff) {
method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
if (!method)
return NULL;
}
}
if (method_index == 0xffffff) {
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
full_name = mono_method_full_name (method, TRUE);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
g_free (full_name);
}
return NULL;
}
if (method_index == 0xffffff)
return NULL;
/* Needed by find_jit_info */
amodule_lock (amodule);
g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
amodule_unlock (amodule);
} else {
/* Common case */
method_index = mono_metadata_token_index (method->token) - 1;
if (!mono_llvm_only) {
guint32 num_methods = amodule->info.nmethods - amodule->info.nextra_methods;
if (method_index >= num_methods)
/* method not available in AOT image */
return NULL;
}
}
code = (guint8 *)load_method (amodule, m_class_get_image (klass), method, method->token, method_index, error);
if (!is_ok (error))
return NULL;
if (code && cache_result) {
amodule_lock (amodule);
g_hash_table_insert (amodule->method_to_code, orig_method, code);
amodule_unlock (amodule);
}
return code;
}
/**
* Same as mono_aot_get_method, but we try to avoid loading any metadata from the
* method.
*/
gpointer
mono_aot_get_method_from_token (MonoImage *image, guint32 token, MonoError *error)
{
MonoAotModule *aot_module = image->aot_module;
int method_index;
gpointer res;
error_init (error);
if (!aot_module)
return NULL;
method_index = mono_metadata_token_index (token) - 1;
res = load_method (aot_module, image, NULL, token, method_index, error);
return res;
}
typedef struct {
guint8 *addr;
gboolean res;
} IsGotEntryUserData;
static void
check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
{
IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
MonoAotModule *aot_module = (MonoAotModule*)value;
if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
data->res = TRUE;
}
gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
IsGotEntryUserData user_data;
if (!aot_modules)
return FALSE;
user_data.addr = addr;
user_data.res = FALSE;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
mono_aot_unlock ();
return user_data.res;
}
typedef struct {
guint8 *addr;
MonoAotModule *module;
} FindAotModuleUserData;
static void
find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
{
FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
MonoAotModule *aot_module = (MonoAotModule*)value;
if (amodule_contains_code_addr (aot_module, data->addr))
data->module = aot_module;
}
static MonoAotModule*
find_aot_module (guint8 *code)
{
FindAotModuleUserData user_data;
if (!aot_modules)
return NULL;
/* Reading these need no locking */
if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
return NULL;
user_data.addr = code;
user_data.module = NULL;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
mono_aot_unlock ();
return user_data.module;
}
#ifdef MONO_ARCH_CODE_EXEC_ONLY
static guint32
aot_resolve_plt_info_offset (gpointer amodule, guint32 plt_entry_index)
{
MonoAotModule *module = (MonoAotModule*)amodule;
return mono_aot_get_offset (module->got_info_offsets, module->info.plt_got_info_offset_base + plt_entry_index);
}
#endif
void
mono_aot_patch_plt_entry (gpointer aot_module, guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
{
MonoAotModule *amodule = (MonoAotModule *)aot_module;
if (!amodule)
amodule = find_aot_module (code);
#ifdef MONO_ARCH_CODE_EXEC_ONLY
mono_arch_patch_plt_entry_exec_only (&amodule->info, plt_entry, amodule->got, regs, addr);
#else
mono_arch_patch_plt_entry (plt_entry, amodule->got, regs, addr);
#endif
}
/*
* mono_aot_plt_resolve:
*
* This function is called by the entries in the PLT to resolve the actual method that
* needs to be called. It returns a trampoline to the method and patches the PLT entry.
* Returns NULL if the something cannot be loaded.
*/
gpointer
mono_aot_plt_resolve (gpointer aot_module, host_mgreg_t *regs, guint8 *code, MonoError *error)
{
#ifdef MONO_ARCH_AOT_SUPPORTED
guint8 *p, *target, *plt_entry;
guint32 plt_info_offset;
MonoJumpInfo ji;
MonoAotModule *module = (MonoAotModule*)aot_module;
gboolean res, no_ftnptr = FALSE;
MonoMemPool *mp;
gboolean using_gsharedvt = FALSE;
error_init (error);
plt_entry = mono_aot_get_plt_entry (regs, code);
g_assert (plt_entry);
plt_info_offset = mono_aot_get_plt_info_offset (aot_module, plt_entry, regs, code);
//printf ("DYN: %p %d\n", aot_module, plt_info_offset);
p = &module->blob [plt_info_offset];
ji.type = (MonoJumpInfoType)decode_value (p, &p);
mp = mono_mempool_new ();
res = decode_patch (module, mp, &ji, p, &p);
if (!res) {
mono_mempool_destroy (mp);
return NULL;
}
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
using_gsharedvt = TRUE;
#endif
/*
* Avoid calling resolve_patch_target in the full-aot case if possible, since
* it would create a trampoline, and we don't need that.
* We could do this only if the method does not need the special handling
* in mono_magic_trampoline ().
*/
if (mono_aot_only && ji.type == MONO_PATCH_INFO_METHOD && !ji.data.method->is_generic && !mono_method_check_context_used (ji.data.method) && !(ji.data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) &&
!mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
target = (guint8 *)mono_jit_compile_method (ji.data.method, error);
if (!is_ok (error)) {
mono_mempool_destroy (mp);
return NULL;
}
no_ftnptr = TRUE;
} else {
target = (guint8 *)mono_resolve_patch_target (NULL, NULL, &ji, TRUE, error);
if (!is_ok (error)) {
mono_mempool_destroy (mp);
return NULL;
}
}
/*
* The trampoline expects us to return a function descriptor on platforms which use
* it, but resolve_patch_target returns a direct function pointer for some type of
* patches, so have to translate between the two.
* FIXME: Clean this up, but how ?
*/
if (ji.type == MONO_PATCH_INFO_ABS
|| ji.type == MONO_PATCH_INFO_JIT_ICALL_ID
|| ji.type == MONO_PATCH_INFO_ICALL_ADDR
|| ji.type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR
|| ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR
|| ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
/* These should already have a function descriptor */
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
/* Our function descriptors have a 0 environment, gcc created ones don't */
if (ji.type != MONO_PATCH_INFO_JIT_ICALL_ID
&& ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR
&& ji.type != MONO_PATCH_INFO_ICALL_ADDR
&& ji.type != MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR)
g_assert (((gpointer*)target) [2] == 0);
#endif
/* Empty */
} else if (!no_ftnptr) {
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
g_assert (((gpointer*)target) [2] != 0);
#endif
target = (guint8 *)mono_create_ftnptr (target);
}
mono_mempool_destroy (mp);
/* Patch the PLT entry with target which might be the actual method not a trampoline */
mono_aot_patch_plt_entry (aot_module, code, plt_entry, module->got, regs, target);
return target;
#else
g_assert_not_reached ();
return NULL;
#endif
}
/**
* init_plt:
*
* Initialize the PLT table of the AOT module. Called lazily when the first AOT
* method in the module is loaded to avoid committing memory by writing to it.
*/
static void
init_plt (MonoAotModule *amodule)
{
int i;
gpointer tramp;
if (amodule->plt_inited)
return;
tramp = mono_create_specific_trampoline (get_default_mem_manager (), amodule, MONO_TRAMPOLINE_AOT_PLT, NULL);
tramp = mono_create_ftnptr (tramp);
amodule_lock (amodule);
if (amodule->plt_inited) {
amodule_unlock (amodule);
return;
}
if (amodule->info.plt_size <= 1) {
amodule->plt_inited = TRUE;
amodule_unlock (amodule);
return;
}
/*
* Initialize the PLT entries in the GOT to point to the default targets.
*/
for (i = 1; i < amodule->info.plt_size; ++i)
/* All the default entries point to the AOT trampoline */
((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
mono_memory_barrier ();
amodule->plt_inited = TRUE;
amodule_unlock (amodule);
}
/*
* mono_aot_get_plt_entry:
*
* Return the address of the PLT entry called by the code at CODE if exists.
*/
guint8*
mono_aot_get_plt_entry (host_mgreg_t *regs, guint8 *code)
{
MonoAotModule *amodule = find_aot_module (code);
guint8 *target = NULL;
if (!amodule)
return NULL;
#ifdef TARGET_ARM
if (is_thumb_code (amodule, code - 4))
return mono_arm_get_thumb_plt_entry (code);
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
#ifdef MONO_ARCH_CODE_EXEC_ONLY
target = mono_aot_arch_get_plt_entry_exec_only (&amodule->info, regs, code, amodule->plt);
#else
target = mono_arch_get_call_target (code);
#endif
#else
g_assert_not_reached ();
#endif
#ifdef MONOTOUCH
while (target != NULL) {
if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
return target;
// Add 4 since mono_arch_get_call_target assumes we're passing
// the instruction after the actual branch instruction.
target = mono_arch_get_call_target (target + 4);
}
return NULL;
#else
if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
return target;
else
return NULL;
#endif
}
/*
* mono_aot_get_plt_info_offset:
*
* Return the PLT info offset belonging to the plt entry called by CODE.
*/
guint32
mono_aot_get_plt_info_offset (gpointer aot_module, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code)
{
if (!plt_entry) {
plt_entry = mono_aot_get_plt_entry (regs, code);
g_assert (plt_entry);
}
/* The offset is embedded inside the code after the plt entry */
#ifdef MONO_ARCH_AOT_SUPPORTED
#ifdef MONO_ARCH_CODE_EXEC_ONLY
return mono_arch_get_plt_info_offset_exec_only (&((MonoAotModule*)aot_module)->info, plt_entry, regs, code, aot_resolve_plt_info_offset, aot_module);
#else
return mono_arch_get_plt_info_offset (plt_entry, regs, code);
#endif
#else
g_assert_not_reached ();
return 0;
#endif
}
static gpointer
mono_create_ftnptr_malloc (guint8 *code)
{
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
ftnptr->code = code;
ftnptr->toc = NULL;
ftnptr->env = NULL;
return ftnptr;
#else
return code;
#endif
}
/*
* load_function_full:
*
* Load the function named NAME from the aot image.
*/
static gpointer
load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
{
char *symbol;
guint8 *p;
int n_patches, pindex;
MonoMemPool *mp;
gpointer code;
guint32 info_offset;
/* Load the code */
find_amodule_symbol (amodule, name, &code);
g_assertf (code, "Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
/* Load info */
symbol = g_strdup_printf ("%s_p", name);
find_amodule_symbol (amodule, symbol, (gpointer *)&p);
g_free (symbol);
if (!p)
/* Nothing to patch */
return code;
info_offset = *(guint32*)p;
if (out_tinfo) {
MonoTrampInfo *tinfo;
guint32 code_size, uw_info_len, uw_offset;
guint8 *uw_info;
/* Construct a MonoTrampInfo from the data in the AOT image */
p += sizeof (guint32);
code_size = *(guint32*)p;
p += sizeof (guint32);
uw_offset = *(guint32*)p;
uw_info = amodule->unwind_info + uw_offset;
uw_info_len = decode_value (uw_info, &uw_info);
tinfo = g_new0 (MonoTrampInfo, 1);
tinfo->code = (guint8 *)code;
tinfo->code_size = code_size;
tinfo->uw_info_len = uw_info_len;
if (uw_info_len)
tinfo->uw_info = uw_info;
*out_tinfo = tinfo;
}
p = amodule->blob + info_offset;
/* Similar to mono_aot_load_method () */
n_patches = decode_value (p, &p);
if (n_patches) {
MonoJumpInfo *patches;
guint32 *got_slots;
mp = mono_mempool_new ();
patches = load_patch_info (amodule, mp, n_patches, FALSE, &got_slots, p, &p);
g_assert (patches);
for (pindex = 0; pindex < n_patches; ++pindex) {
MonoJumpInfo *ji = &patches [pindex];
ERROR_DECL (error);
gpointer target;
if (amodule->got [got_slots [pindex]])
continue;
/*
* When this code is executed, the runtime may not be initalized yet, so
* resolve the patch info by hand.
*/
if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR) {
target = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (ji->data.uindex), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, NULL);
target = mono_create_ftnptr_malloc ((guint8 *)target);
} else if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES) {
target = amodule->info.specific_trampolines;
g_assert (target);
} else if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE) {
target = &amodule->got [amodule->info.trampoline_got_offset_base [MONO_AOT_TRAMP_SPECIFIC]];
} else if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
const MonoJitICallId jit_icall_id = (MonoJitICallId)ji->data.jit_icall_id;
switch (jit_icall_id) {
#undef MONO_AOT_ICALL
#define MONO_AOT_ICALL(x) case MONO_JIT_ICALL_ ## x: target = (gpointer)x; break;
MONO_AOT_ICALL (mono_get_lmf_addr)
MONO_AOT_ICALL (mono_thread_force_interruption_checkpoint_noraise)
MONO_AOT_ICALL (mono_exception_from_token)
case MONO_JIT_ICALL_mono_debugger_agent_single_step_from_context:
target = (gpointer)mono_component_debugger ()->single_step_from_context;
break;
case MONO_JIT_ICALL_mono_debugger_agent_breakpoint_from_context:
target = (gpointer)mono_component_debugger ()->breakpoint_from_context;
break;
case MONO_JIT_ICALL_mono_throw_exception:
target = mono_get_throw_exception_addr ();
break;
case MONO_JIT_ICALL_mono_rethrow_preserve_exception:
target = mono_get_rethrow_preserve_exception_addr ();
break;
case MONO_JIT_ICALL_generic_trampoline_jit:
case MONO_JIT_ICALL_generic_trampoline_jump:
case MONO_JIT_ICALL_generic_trampoline_rgctx_lazy_fetch:
case MONO_JIT_ICALL_generic_trampoline_aot:
case MONO_JIT_ICALL_generic_trampoline_aot_plt:
case MONO_JIT_ICALL_generic_trampoline_delegate:
case MONO_JIT_ICALL_generic_trampoline_vcall:
target = (gpointer)mono_get_trampoline_func (mono_jit_icall_id_to_trampoline_type (jit_icall_id));
break;
default:
target = mono_arch_load_function (jit_icall_id);
g_assertf (target, "Unknown relocation '%p'\n", ji->data.target);
}
} else {
/* Hopefully the code doesn't have patches which need method to be set.
*/
target = mono_resolve_patch_target (NULL, (guint8 *)code, ji, FALSE, error);
mono_error_assert_ok (error);
g_assert (target);
}
if (ji->type != MONO_PATCH_INFO_NONE)
amodule->got [got_slots [pindex]] = target;
}
g_free (got_slots);
mono_mempool_destroy (mp);
}
return code;
}
static gpointer
load_function (MonoAotModule *amodule, const char *name)
{
return load_function_full (amodule, name, NULL);
}
static MonoAotModule*
get_mscorlib_aot_module (void)
{
MonoImage *image;
MonoAotModule *amodule;
image = mono_defaults.corlib;
if (image && image->aot_module)
amodule = image->aot_module;
else
amodule = mscorlib_aot_module;
g_assert (amodule);
return amodule;
}
static void
mono_no_trampolines (void)
{
g_assert_not_reached ();
}
/*
* Return the trampoline identified by NAME from the mscorlib AOT file.
* On ppc64, this returns a function descriptor.
*/
gpointer
mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
{
MonoAotModule *amodule = get_mscorlib_aot_module ();
if (mono_llvm_only) {
*out_tinfo = NULL;
return (gpointer)mono_no_trampolines;
}
return mono_create_ftnptr_malloc ((guint8 *)load_function_full (amodule, name, out_tinfo));
}
gpointer
mono_aot_get_trampoline (const char *name)
{
MonoTrampInfo *out_tinfo;
gpointer code;
code = mono_aot_get_trampoline_full (name, &out_tinfo);
mono_aot_tramp_info_register (out_tinfo, NULL);
return code;
}
static gpointer
read_unwind_info (MonoAotModule *amodule, MonoTrampInfo *info, const char *symbol_name)
{
gpointer symbol_addr;
guint32 uw_offset, uw_info_len;
guint8 *uw_info;
find_amodule_symbol (amodule, symbol_name, &symbol_addr);
if (!symbol_addr)
return NULL;
uw_offset = *(guint32*)symbol_addr;
uw_info = amodule->unwind_info + uw_offset;
uw_info_len = decode_value (uw_info, &uw_info);
info->uw_info_len = uw_info_len;
if (uw_info_len)
info->uw_info = uw_info;
else
info->uw_info = NULL;
/* If successful return the address of the following data */
return (guint32*)symbol_addr + 1;
}
#ifdef MONOTOUCH
#include <mach/mach.h>
static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
static void
read_page_trampoline_uwinfo (MonoTrampInfo *info, int tramp_type, gboolean is_generic)
{
char symbol_name [128];
if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
sprintf (symbol_name, "specific_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
sprintf (symbol_name, "rgctx_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_IMT)
sprintf (symbol_name, "imt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
sprintf (symbol_name, "gsharedvt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
sprintf (symbol_name, "unbox_arbitrary_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else
g_assert_not_reached ();
read_unwind_info (mscorlib_aot_module, info, symbol_name);
}
static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
TrampolinePage *page;
int count;
void *tpage;
vm_address_t addr, taddr;
kern_return_t ret;
vm_prot_t prot, max_prot;
int psize, specific_trampoline_size;
unsigned char *code;
specific_trampoline_size = 2 * sizeof (gpointer);
mono_aot_page_lock ();
page = trampoline_pages [tramp_type];
if (page && page->trampolines < page->trampolines_end) {
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
return code;
}
mono_aot_page_unlock ();
psize = MONO_AOT_TRAMP_PAGE_SIZE;
/* the trampoline template page is in the mscorlib module */
MonoAotModule *amodule = mscorlib_aot_module;
g_assert (amodule);
if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
tpage = load_function (amodule, "specific_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
tpage = load_function (amodule, "rgctx_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_IMT)
tpage = load_function (amodule, "imt_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
tpage = load_function (amodule, "unbox_arbitrary_trampolines_page");
else
g_error ("Incorrect tramp type for trampolines page");
g_assert (tpage);
/*g_warning ("loaded trampolines page at %x", tpage);*/
/* avoid the unlikely case of looping forever */
count = 40;
page = NULL;
while (page == NULL && count-- > 0) {
MonoTrampInfo *gen_info, *sp_info;
addr = 0;
/* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
* while the second will contain the trampolines.
*/
do {
ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
} while (ret == KERN_ABORTED);
if (ret != KERN_SUCCESS) {
g_error ("Cannot allocate memory for trampolines: %d", ret);
break;
}
/*g_warning ("allocated trampoline double page at %x", addr);*/
/* replace the second page with a remapped trampoline page */
taddr = addr + psize;
vm_deallocate (mach_task_self (), taddr, psize);
ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
if (ret != KERN_SUCCESS) {
/* someone else got the page, try again */
vm_deallocate (mach_task_self (), addr, psize);
continue;
}
/*g_warning ("remapped trampoline page at %x", taddr);*/
mono_aot_page_lock ();
page = trampoline_pages [tramp_type];
/* some other thread already allocated, so use that to avoid wasting memory */
if (page && page->trampolines < page->trampolines_end) {
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
vm_deallocate (mach_task_self (), addr, psize);
vm_deallocate (mach_task_self (), taddr, psize);
return code;
}
page = (TrampolinePage*)addr;
page->next = trampoline_pages [tramp_type];
trampoline_pages [tramp_type] = page;
page->trampolines = (guint8*)(taddr + amodule->info.tramp_page_code_offsets [tramp_type]);
page->trampolines_end = (guint8*)(taddr + psize - 64);
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
/* Register the generic part at the beggining of the trampoline page */
gen_info = mono_tramp_info_create (NULL, (guint8*)taddr, amodule->info.tramp_page_code_offsets [tramp_type], NULL, NULL);
read_page_trampoline_uwinfo (gen_info, tramp_type, TRUE);
mono_aot_tramp_info_register (gen_info, NULL);
/*
* FIXME
* Registering each specific trampoline produces a lot of
* MonoJitInfo structures. Jump trampolines are also registered
* separately.
*/
if (tramp_type != MONO_AOT_TRAMP_SPECIFIC) {
/* Register the rest of the page as a single trampoline */
sp_info = mono_tramp_info_create (NULL, code, page->trampolines_end - code, NULL, NULL);
read_page_trampoline_uwinfo (sp_info, tramp_type, FALSE);
mono_aot_tramp_info_register (sp_info, NULL);
}
return code;
}
g_error ("Cannot allocate more trampoline pages: %d", ret);
return NULL;
}
#else
static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
g_error ("Page trampolines not supported.");
return NULL;
}
#endif
static gpointer
get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_imt_trampoline_from_page (gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
/*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_unbox_arbitrary_trampoline_frome_page (gpointer addr)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_UNBOX_ARBITRARY);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = addr;
return MINI_ADDR_TO_FTNPTR (code);
}
/* Return a given kind of trampoline */
/* FIXME set unwind info for these trampolines */
static gpointer
get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
{
#ifndef DISABLE_ASSERT_MESSAGES
MonoImage *image;
#endif
MonoAotModule *amodule = get_mscorlib_aot_module ();
int index, tramp_size;
#ifndef DISABLE_ASSERT_MESSAGES
/* Currently, we keep all trampolines in the mscorlib AOT image */
image = mono_defaults.corlib;
#endif
*out_amodule = amodule;
mono_aot_lock ();
#ifdef MONOTOUCH
#define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
#else
#define MONOTOUCH_TRAMPOLINES_ERROR ""
#endif
if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
g_error ("Ran out of trampolines of type %d in '%s' (limit %d)%s\n",
tramp_type, image ? image->name : MONO_ASSEMBLY_CORLIB_NAME, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
}
index = amodule->trampoline_index [tramp_type] ++;
mono_aot_unlock ();
*got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
tramp_size = amodule->info.trampoline_size [tramp_type];
if (out_tramp_size)
*out_tramp_size = tramp_size;
return amodule->trampolines [tramp_type] + (index * tramp_size);
}
static void
no_specific_trampoline (void)
{
g_assert_not_reached ();
}
/*
* Return a specific trampoline from the AOT file.
*/
gpointer
mono_aot_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, guint32 *code_len)
{
MonoAotModule *amodule;
guint32 got_offset, tramp_size;
guint8 *code, *tramp;
static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
static gboolean inited;
static guint32 num_trampolines;
if (mono_llvm_only) {
*code_len = 1;
return (gpointer)no_specific_trampoline;
}
if (!inited) {
mono_aot_lock ();
if (!inited) {
mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
inited = TRUE;
}
mono_aot_unlock ();
}
num_trampolines ++;
if (!generic_trampolines [tramp_type]) {
const char *symbol;
symbol = mono_get_generic_trampoline_name (tramp_type);
generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
}
tramp = (guint8 *)generic_trampolines [tramp_type];
g_assert (tramp);
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_specific_trampoline_from_page (tramp, arg1);
tramp_size = 8;
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
amodule->got [got_offset] = tramp;
amodule->got [got_offset + 1] = arg1;
}
if (code_len)
*code_len = tramp_size;
return MINI_ADDR_TO_FTNPTR (code);
}
gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_rgctx_trampoline_from_page (addr, ctx);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = ctx;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
gpointer
mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_unbox_arbitrary_trampoline_frome_page (addr);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_UNBOX_ARBITRARY, 1, &amodule, &got_offset, NULL);
amodule->got [got_offset] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
static int
i32_idx_comparer (const void *key, const void *member)
{
gint32 idx1 = GPOINTER_TO_INT (key);
gint32 idx2 = *(gint32*)member;
return idx1 - idx2;
}
static int
ui16_idx_comparer (const void *key, const void *member)
{
int idx1 = GPOINTER_TO_INT (key);
int idx2 = *(guint16*)member;
return idx1 - idx2;
}
static gboolean
aot_is_slim_amodule (MonoAotModule *amodule)
{
if (!amodule)
return FALSE;
/* "slim" only applies to mscorlib.dll */
if (strcmp (amodule->aot_name, MONO_ASSEMBLY_CORLIB_NAME))
return FALSE;
guint32 f = amodule->info.flags;
return (f & MONO_AOT_FILE_FLAG_INTERP) && !(f & MONO_AOT_FILE_FLAG_FULL_AOT);
}
gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
{
ERROR_DECL (error);
guint32 method_index = mono_metadata_token_index (method->token) - 1;
MonoAotModule *amodule;
gpointer code;
guint32 *ut, *ut_end, *entry;
int low, high, entry_index = 0;
MonoTrampInfo *tinfo;
if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
method_index = find_aot_method (method, &amodule);
if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
mono_error_assert_ok (error);
method_index = find_aot_method (shared, &amodule);
}
if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, TRUE)) {
MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
method_index = find_aot_method (shared, &amodule);
}
} else
amodule = m_class_get_image (method->klass)->aot_module;
if (amodule == NULL || method_index == 0xffffff || aot_is_slim_amodule (amodule)) {
/* couldn't find unbox trampoline specifically generated for that
* method. this should only happen when an unbox trampoline is needed
* for `fullAOT code -> native-to-interp -> interp` transition if
* (1) it's a virtual call
* (2) the receiver is a value type, thus needs unboxing */
g_assert (mono_use_interpreter);
return mono_aot_get_unbox_arbitrary_trampoline (addr);
}
if (!amodule->unbox_tramp_per_method) {
gpointer arr = g_new0 (gpointer, amodule->info.nmethods);
mono_memory_barrier ();
gpointer old_arr = mono_atomic_cas_ptr ((volatile gpointer*)&amodule->unbox_tramp_per_method, arr, NULL);
if (old_arr)
g_free (arr);
}
if (amodule->unbox_tramp_per_method [method_index])
return amodule->unbox_tramp_per_method [method_index];
if (amodule->info.llvm_unbox_tramp_indexes) {
int unbox_tramp_idx;
/* Search the llvm_unbox_tramp_indexes table using a binary search */
if (amodule->info.llvm_unbox_tramp_elemsize == sizeof (guint32)) {
void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, i32_idx_comparer);
g_assert (ptr);
g_assert (*(int*)ptr == method_index);
unbox_tramp_idx = (guint32*)ptr - (guint32*)amodule->info.llvm_unbox_tramp_indexes;
} else {
void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, ui16_idx_comparer);
g_assert (ptr);
g_assert (*(guint16*)ptr == method_index);
unbox_tramp_idx = (guint16*)ptr - (guint16*)amodule->info.llvm_unbox_tramp_indexes;
}
g_assert (unbox_tramp_idx < amodule->info.llvm_unbox_tramp_num);
code = ((gpointer*)(amodule->info.llvm_unbox_trampolines))[unbox_tramp_idx];
g_assert (code);
code = MINI_ADDR_TO_FTNPTR (code);
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
return code;
}
if (amodule->info.llvm_get_unbox_tramp) {
gpointer (*get_tramp) (int) = (gpointer (*)(int))amodule->info.llvm_get_unbox_tramp;
code = get_tramp (method_index);
if (code) {
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
return code;
}
}
ut = amodule->unbox_trampolines;
ut_end = amodule->unbox_trampolines_end;
/* Do a binary search in the sorted table */
code = NULL;
low = 0;
high = (ut_end - ut);
while (low < high) {
entry_index = (low + high) / 2;
entry = &ut [entry_index];
if (entry [0] < method_index) {
low = entry_index + 1;
} else if (entry [0] > method_index) {
high = entry_index;
} else {
break;
}
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)
code = ((gpointer*)amodule->unbox_trampoline_addresses) [entry_index];
else
code = get_call_table_entry (amodule->unbox_trampoline_addresses, entry_index, amodule->info.call_table_entry_size);
g_assert (code);
code = MINI_ADDR_TO_FTNPTR (code);
tinfo = mono_tramp_info_create (NULL, (guint8 *)code, 0, NULL, NULL);
gpointer const symbol_addr = read_unwind_info (amodule, tinfo, "unbox_trampoline_p");
if (!symbol_addr) {
mono_tramp_info_free (tinfo);
return FALSE;
}
tinfo->method = method;
tinfo->code_size = *(guint32*)symbol_addr;
tinfo->unwind_ops = mono_arch_get_cie_program ();
mono_aot_tramp_info_register (tinfo, NULL);
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
/* The caller expects an ftnptr */
return mono_create_ftnptr (code);
}
gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
char *symbol;
gpointer code;
MonoAotModule *amodule = mscorlib_aot_module;
guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
static int count = 0;
count ++;
if (index >= amodule->info.num_rgctx_fetch_trampolines) {
static gpointer addr;
gpointer *info;
/*
* Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
*/
if (!addr)
addr = load_function (amodule, "rgctx_fetch_trampoline_general");
info = (void **)mono_mem_manager_alloc0 (get_default_mem_manager (), sizeof (gpointer) * 2);
info [0] = GUINT_TO_POINTER (slot);
info [1] = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, NULL);
code = mono_aot_get_static_rgctx_trampoline (info, addr);
return mono_create_ftnptr (code);
}
symbol = mono_get_rgctx_fetch_trampoline_name (slot);
code = load_function (amodule, symbol);
g_free (symbol);
/* The caller expects an ftnptr */
return mono_create_ftnptr (code);
}
static void
no_imt_trampoline (void)
{
g_assert_not_reached ();
}
gpointer
mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
guint32 got_offset;
gpointer code;
gpointer *buf;
int i, index, real_count;
MonoAotModule *amodule;
if (mono_llvm_only)
return (gpointer)no_imt_trampoline;
real_count = 0;
for (i = 0; i < count; ++i) {
MonoIMTCheckItem *item = imt_entries [i];
if (item->is_equals)
real_count ++;
}
/* Save the entries into an array */
buf = (void **)m_class_alloc0 (vtable->klass, (real_count + 1) * 2 * sizeof (gpointer));
index = 0;
for (i = 0; i < count; ++i) {
MonoIMTCheckItem *item = imt_entries [i];
if (!item->is_equals)
continue;
g_assert (item->key);
buf [(index * 2)] = item->key;
if (item->has_target_code) {
gpointer *p = (gpointer *)m_class_alloc0 (vtable->klass, sizeof (gpointer));
*p = item->value.target_code;
buf [(index * 2) + 1] = p;
} else {
buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
}
index ++;
}
buf [(index * 2)] = NULL;
buf [(index * 2) + 1] = fail_tramp;
if (USE_PAGE_TRAMPOLINES) {
code = get_new_imt_trampoline_from_page (buf);
} else {
code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT, 1, &amodule, &got_offset, NULL);
amodule->got [got_offset] = buf;
}
return MINI_ADDR_TO_FTNPTR (code);
}
gpointer
mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = arg;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
gpointer
mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
g_error ("FIXME: ftnptr_arg page trampolines");
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_FTNPTR_ARG, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = arg;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
#endif
/*
* mono_aot_set_make_unreadable:
*
* Set whenever to make all mmaped memory unreadable. In conjuction with a
* SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
*/
void
mono_aot_set_make_unreadable (gboolean unreadable)
{
static int inited;
make_unreadable = unreadable;
if (make_unreadable && !inited) {
mono_counters_register ("AOT: pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
}
}
typedef struct {
MonoAotModule *module;
guint8 *ptr;
} FindMapUserData;
static void
find_map (gpointer key, gpointer value, gpointer user_data)
{
MonoAotModule *module = (MonoAotModule*)value;
FindMapUserData *data = (FindMapUserData*)user_data;
if (!data->module)
if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
data->module = module;
}
static MonoAotModule*
find_module_for_addr (void *ptr)
{
FindMapUserData data;
if (!make_unreadable)
return NULL;
data.module = NULL;
data.ptr = (guint8*)ptr;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
mono_aot_unlock ();
return data.module;
}
/*
* mono_aot_is_pagefault:
*
* Should be called from a SIGSEGV signal handler to find out whenever @ptr is
* within memory allocated by this module.
*/
gboolean
mono_aot_is_pagefault (void *ptr)
{
if (!make_unreadable)
return FALSE;
/*
* Not signal safe, but SIGSEGV's are synchronous, and
* this is only turned on by a MONO_DEBUG option.
*/
return find_module_for_addr (ptr) != NULL;
}
/*
* mono_aot_handle_pagefault:
*
* Handle a pagefault caused by an unreadable page by making it readable again.
*/
void
mono_aot_handle_pagefault (void *ptr)
{
#ifndef HOST_WIN32
guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
int res;
mono_aot_lock ();
res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
g_assert (res == 0);
n_pagefaults ++;
mono_aot_unlock ();
#endif
}
MonoAotMethodFlags
mono_aot_get_method_flags (guint8 *code)
{
guint32 flags;
if (!code_to_method_flags)
return MONO_AOT_METHOD_FLAG_NONE;
mono_aot_lock ();
/* Not found and no FLAG_NONE are the same, but its not a problem */
flags = GPOINTER_TO_UINT (g_hash_table_lookup (code_to_method_flags, code));
mono_aot_unlock ();
return (MonoAotMethodFlags)flags;
}
#else
/* AOT disabled */
void
mono_aot_init (void)
{
}
guint32
mono_aot_find_method_index (MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_init_llvm_method (gpointer aot_module, gpointer method_info, MonoClass *init_class, MonoError *error)
{
g_assert_not_reached ();
return FALSE;
}
gpointer
mono_aot_get_method (MonoMethod *method, MonoError *error)
{
error_init (error);
return NULL;
}
gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
return FALSE;
}
gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
return FALSE;
}
gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
return FALSE;
}
MonoJitInfo *
mono_aot_find_jit_info (MonoImage *image, gpointer addr)
{
return NULL;
}
gpointer
mono_aot_get_method_from_token (MonoImage *image, guint32 token, MonoError *error)
{
error_init (error);
return NULL;
}
guint8*
mono_aot_get_plt_entry (host_mgreg_t *regs, guint8 *code)
{
return NULL;
}
gpointer
mono_aot_plt_resolve (gpointer aot_module, host_mgreg_t *regs, guint8 *code, MonoError *error)
{
return NULL;
}
void
mono_aot_patch_plt_entry (gpointer aot_module, guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
{
}
gpointer
mono_aot_get_method_from_vt_slot (MonoVTable *vtable, int slot, MonoError *error)
{
error_init (error);
return NULL;
}
guint32
mono_aot_get_plt_info_offset (gpointer aot_module, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code)
{
g_assert_not_reached ();
return 0;
}
gpointer
mono_aot_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, guint32 *code_len)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_trampoline (const char *name)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
gpointer
mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
#endif
void
mono_aot_set_make_unreadable (gboolean unreadable)
{
}
gboolean
mono_aot_is_pagefault (void *ptr)
{
return FALSE;
}
void
mono_aot_handle_pagefault (void *ptr)
{
}
guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
g_assert_not_reached ();
return NULL;
}
GHashTable *
mono_aot_get_weak_field_indexes (MonoImage *image)
{
return NULL;
}
MonoAotMethodFlags
mono_aot_get_method_flags (guint8 *code)
{
return MONO_AOT_METHOD_FLAG_NONE;
}
#endif
| /**
* \file
* mono Ahead of Time compiler
*
* Author:
* Dietmar Maurer ([email protected])
* Zoltan Varga ([email protected])
*
* (C) 2002 Ximian, Inc.
* Copyright 2003-2011 Novell, Inc.
* Copyright 2011 Xamarin, Inc.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fcntl.h>
#include <string.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#if HOST_WIN32
#include <winsock2.h>
#include <windows.h>
#endif
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include <errno.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h> /* for WIFEXITED, WEXITSTATUS */
#endif
#include <mono/metadata/abi-details.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/exception-internals.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/mono-endian.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-digest.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/bsearch.h>
#include <mono/utils/mono-tls-inline.h>
#include "mini.h"
#include "seq-points.h"
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "jit-icalls.h"
#include "mini-runtime.h"
#include <mono/jit/mono-private-unstable.h>
#include "llvmonly-runtime.h"
#include <mono/metadata/components.h>
#ifndef DISABLE_AOT
#ifdef MONO_ARCH_CODE_EXEC_ONLY
extern guint8* mono_aot_arch_get_plt_entry_exec_only (gpointer amodule_info, host_mgreg_t *regs, guint8 *code, guint8 *plt);
extern guint32 mono_arch_get_plt_info_offset_exec_only (gpointer amodule_info, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code, MonoAotResolvePltInfoOffset resolver, gpointer amodule);
extern void mono_arch_patch_plt_entry_exec_only (gpointer amodule_info, guint8 *code, gpointer *got, host_mgreg_t *regs, guint8 *addr);
#endif
#define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
#define JIT_INFO_MAP_BUCKET_SIZE 32
typedef struct _JitInfoMap JitInfoMap;
struct _JitInfoMap {
MonoJitInfo *jinfo;
JitInfoMap *next;
int method_index;
};
#define GOT_INITIALIZING 1
#define GOT_INITIALIZED 2
struct MonoAotModule {
char *aot_name;
/* Pointer to the Global Offset Table */
gpointer *got;
gpointer *llvm_got;
gpointer *shared_got;
GHashTable *name_cache;
GHashTable *extra_methods;
/* Maps methods to their code */
GHashTable *method_to_code;
/* Maps pointers into the method info to the methods themselves */
GHashTable *method_ref_to_method;
MonoAssemblyName *image_names;
char **image_guids;
MonoAssembly *assembly;
MonoImage **image_table;
guint32 image_table_len;
gboolean out_of_date;
gboolean plt_inited;
int got_initialized;
guint8 *mem_begin;
guint8 *mem_end;
guint8 *jit_code_start;
guint8 *jit_code_end;
guint8 *llvm_code_start;
guint8 *llvm_code_end;
guint8 *plt;
guint8 *plt_end;
guint8 *blob;
gpointer weak_field_indexes;
guint8 *method_flags_table;
/* Maps method indexes to their code */
/* Raw pointer on arm64e */
gpointer *methods;
/* Sorted array of method addresses */
gpointer *sorted_methods;
/* Method indexes for each method in sorted_methods */
int *sorted_method_indexes;
/* The length of the two tables above */
int sorted_methods_len;
guint32 *method_info_offsets;
guint32 *ex_info_offsets;
guint32 *class_info_offsets;
guint32 *got_info_offsets;
guint32 *llvm_got_info_offsets;
guint32 *methods_loaded;
guint16 *class_name_table;
guint32 *extra_method_table;
guint32 *extra_method_info_offsets;
guint32 *unbox_trampolines;
guint32 *unbox_trampolines_end;
guint32 *unbox_trampoline_addresses;
guint8 *unwind_info;
/* Maps method index -> unbox tramp */
gpointer *unbox_tramp_per_method;
/* Points to the mono EH data created by LLVM */
guint8 *mono_eh_frame;
/* Points to the data tables if MONO_AOT_FILE_FLAG_SEPARATE_DATA is set */
gpointer tables [MONO_AOT_TABLE_NUM];
/* Points to the trampolines */
guint8 *trampolines [MONO_AOT_TRAMP_NUM];
/* The first unused trampoline of each kind */
guint32 trampoline_index [MONO_AOT_TRAMP_NUM];
gboolean use_page_trampolines;
MonoAotFileInfo info;
gpointer *globals;
MonoDl *sofile;
JitInfoMap **async_jit_info_table;
mono_mutex_t mutex;
};
typedef struct {
void *next;
unsigned char *trampolines;
unsigned char *trampolines_end;
} TrampolinePage;
static GHashTable *aot_modules;
#define mono_aot_lock() mono_os_mutex_lock (&aot_mutex)
#define mono_aot_unlock() mono_os_mutex_unlock (&aot_mutex)
static mono_mutex_t aot_mutex;
/*
* Maps assembly names to the mono_aot_module_<NAME>_info symbols in the
* AOT modules registered by mono_aot_register_module ().
*/
static GHashTable *static_aot_modules;
/*
* Same as above, but tracks module that must be loaded before others are
* This allows us to have a "container" module which contains resources for
* other modules. Since it doesn't provide methods for a managed assembly,
* and it needs to be fully loaded by the time the other code needs it, it
* must be eagerly loaded before other modules.
*/
static char *container_assm_name;
static MonoAotModule *container_amodule;
static GHashTable *loaded_static_aot_modules;
/*
* Maps MonoJitInfo* to the aot module they belong to, this can be different
* from ji->method->klass->image's aot module for generic instances.
*/
static GHashTable *ji_to_amodule;
/* Maps method addresses to MonoAotMethodFlags */
static GHashTable *code_to_method_flags;
/* For debugging */
static gint32 mono_last_aot_method = -1;
static gboolean make_unreadable = FALSE;
static guint32 name_table_accesses = 0;
static guint32 n_pagefaults = 0;
/* Used to speed-up find_aot_module () */
static gsize aot_code_low_addr = (gssize)-1;
static gsize aot_code_high_addr = 0;
/* Stats */
static gint32 async_jit_info_size;
#ifdef MONOTOUCH
#define USE_PAGE_TRAMPOLINES (mscorlib_aot_module->use_page_trampolines)
#else
#define USE_PAGE_TRAMPOLINES 0
#endif
#define mono_aot_page_lock() mono_os_mutex_lock (&aot_page_mutex)
#define mono_aot_page_unlock() mono_os_mutex_unlock (&aot_page_mutex)
static mono_mutex_t aot_page_mutex;
static MonoAotModule *mscorlib_aot_module;
/* Embedding API hooks to load the AOT data for AOT images compiled with MONO_AOT_FILE_FLAG_SEPARATE_DATA */
static MonoLoadAotDataFunc aot_data_load_func;
static MonoFreeAotDataFunc aot_data_free_func;
static gpointer aot_data_func_user_data;
static void
init_plt (MonoAotModule *info);
static void
compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end);
static gboolean
init_method (MonoAotModule *amodule, gpointer info, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoError *error);
static MonoJumpInfo*
decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets);
static MonoMethodSignature*
decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf);
static void
load_container_amodule (MonoAssemblyLoadContext *alc);
static void
sort_methods (MonoAotModule *amodule);
static void
amodule_lock (MonoAotModule *amodule)
{
mono_os_mutex_lock (&amodule->mutex);
}
static void
amodule_unlock (MonoAotModule *amodule)
{
mono_os_mutex_unlock (&amodule->mutex);
}
/*
* load_image:
*
* Load one of the images referenced by AMODULE. Returns NULL if the image is not
* found, and sets @error for what happened
*/
static MonoImage *
load_image (MonoAotModule *amodule, int index, MonoError *error)
{
MonoAssembly *assembly;
MonoImageOpenStatus status;
MonoAssemblyLoadContext *alc = mono_alc_get_ambient ();
g_assert (index < amodule->image_table_len);
error_init (error);
if (amodule->image_table [index])
return amodule->image_table [index];
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s wants to load image %d: %s", amodule->aot_name, index, amodule->image_names[index].name);
if (amodule->out_of_date) {
mono_error_set_bad_image_by_name (error, amodule->aot_name, "Image out of date: %s", amodule->aot_name);
return NULL;
}
/*
* LoadFile allows loading more than one assembly with the same name.
* That means that just calling mono_assembly_load is unlikely to find
* the correct assembly (it'll just return the first one loaded). But
* we shouldn't hardcode the full assembly filepath into the AOT image,
* so it's not obvious that we can call mono_assembly_open_predicate.
*
* In the JIT, an assembly opened with LoadFile is supposed to only
* refer to already-loaded assemblies (or to GAC & MONO_PATH)
* assemblies - so nothing new should be loading. And for the
* LoadFile'd assembly itself, we can check if the name and guid of the
* current AOT module matches the wanted name and guid and just return
* the AOT module's assembly.
*/
if (!strcmp (amodule->assembly->image->guid, amodule->image_guids [index])) {
assembly = amodule->assembly;
} else if (mono_get_corlib () && !strcmp (mono_get_corlib ()->guid, amodule->image_guids [index])) {
/* This might be called before corlib is added to the root domain */
assembly = mono_get_corlib ()->assembly;
} else {
MonoAssemblyByNameRequest req;
mono_assembly_request_prepare_byname (&req, alc);
req.basedir = amodule->assembly->basedir;
assembly = mono_assembly_request_byname (&amodule->image_names [index], &req, &status);
}
if (!assembly) {
mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_AOT, "AOT: module %s is unusable because dependency %s is not found.", amodule->aot_name, amodule->image_names [index].name);
mono_error_set_bad_image_by_name (error, amodule->aot_name, "module '%s' is unusable because dependency %s is not found (error %d).\n", amodule->aot_name, amodule->image_names [index].name, status);
amodule->out_of_date = TRUE;
return NULL;
}
if (strcmp (assembly->image->guid, amodule->image_guids [index])) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s')).", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
mono_error_set_bad_image_by_name (error, amodule->aot_name, "module '%s' is unusable (GUID of dependent assembly %s doesn't match (expected '%s', got '%s')).", amodule->aot_name, amodule->image_names [index].name, amodule->image_guids [index], assembly->image->guid);
amodule->out_of_date = TRUE;
return NULL;
}
amodule->image_table [index] = assembly->image;
return assembly->image;
}
static gint32
decode_value (guint8 *ptr, guint8 **rptr)
{
guint8 b = *ptr;
gint32 len;
if ((b & 0x80) == 0){
len = b;
++ptr;
} else if ((b & 0x40) == 0){
len = ((b & 0x3f) << 8 | ptr [1]);
ptr += 2;
} else if (b != 0xff) {
len = ((b & 0x1f) << 24) |
(ptr [1] << 16) |
(ptr [2] << 8) |
ptr [3];
ptr += 4;
}
else {
len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
ptr += 5;
}
if (rptr)
*rptr = ptr;
//printf ("DECODE: %d.\n", len);
return len;
}
/*
* mono_aot_get_offset:
*
* Decode an offset table emitted by emit_offset_table (), returning the INDEXth
* entry.
*/
static guint32
mono_aot_get_offset (guint32 *table, int index)
{
int i, group, ngroups, index_entry_size;
int start_offset, offset, group_size;
guint8 *data_start, *p;
guint32 *index32 = NULL;
guint16 *index16 = NULL;
/* noffsets = table [0]; */
group_size = table [1];
ngroups = table [2];
index_entry_size = table [3];
group = index / group_size;
if (index_entry_size == 2) {
index16 = (guint16*)&table [4];
data_start = (guint8*)&index16 [ngroups];
p = data_start + index16 [group];
} else {
index32 = (guint32*)&table [4];
data_start = (guint8*)&index32 [ngroups];
p = data_start + index32 [group];
}
/* offset will contain the value of offsets [group * group_size] */
offset = start_offset = decode_value (p, &p);
for (i = group * group_size + 1; i <= index; ++i) {
offset += decode_value (p, &p);
}
//printf ("Offset lookup: %d -> %d, start=%d, p=%d\n", index, offset, start_offset, table [3 + group]);
return offset;
}
static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error);
static MonoGenericInst*
decode_generic_inst (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
int type_argc, i;
MonoType **type_argv;
MonoGenericInst *inst;
guint8 *p = buf;
error_init (error);
type_argc = decode_value (p, &p);
type_argv = g_new0 (MonoType*, type_argc);
for (i = 0; i < type_argc; ++i) {
MonoClass *pclass = decode_klass_ref (module, p, &p, error);
if (!pclass) {
g_free (type_argv);
return NULL;
}
type_argv [i] = m_class_get_byval_arg (pclass);
}
inst = mono_metadata_get_generic_inst (type_argc, type_argv);
g_free (type_argv);
*endbuf = p;
return inst;
}
static gboolean
decode_generic_context (MonoAotModule *amodule, MonoGenericContext *ctx, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint8 *p = buf;
guint8 *p2;
guint32 offset, flags;
/* Either the class_inst or method_inst offset */
flags = decode_value (p, &p);
if (flags & 1) {
offset = decode_value (p, &p);
p2 = amodule->blob + offset;
ctx->class_inst = decode_generic_inst (amodule, p2, &p2, error);
if (!ctx->class_inst)
return FALSE;
}
if (flags & 2) {
offset = decode_value (p, &p);
p2 = amodule->blob + offset;
ctx->method_inst = decode_generic_inst (amodule, p2, &p2, error);
if (!ctx->method_inst)
return FALSE;
}
*endbuf = p;
return TRUE;
}
static MonoClass*
decode_klass_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
MonoImage *image;
MonoClass *klass = NULL, *eklass;
guint32 token, rank, idx;
guint8 *p = buf;
int reftype;
error_init (error);
reftype = decode_value (p, &p);
if (reftype == 0) {
*endbuf = p;
mono_error_set_bad_image_by_name (error, module->aot_name, "Decoding a null class ref: %s", module->aot_name);
return NULL;
}
switch (reftype) {
case MONO_AOT_TYPEREF_TYPEDEF_INDEX:
idx = decode_value (p, &p);
image = load_image (module, 0, error);
if (!image)
return NULL;
klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
break;
case MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE:
idx = decode_value (p, &p);
image = load_image (module, decode_value (p, &p), error);
if (!image)
return NULL;
klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF + idx, error);
break;
case MONO_AOT_TYPEREF_TYPESPEC_TOKEN:
token = decode_value (p, &p);
image = module->assembly->image;
if (!image) {
mono_error_set_bad_image_by_name (error, module->aot_name, "No image associated with the aot module: %s", module->aot_name);
return NULL;
}
klass = mono_class_get_checked (image, token, error);
break;
case MONO_AOT_TYPEREF_GINST: {
MonoClass *gclass;
MonoGenericContext ctx;
MonoType *type;
gclass = decode_klass_ref (module, p, &p, error);
if (!gclass)
return NULL;
g_assert (mono_class_is_gtd (gclass));
memset (&ctx, 0, sizeof (ctx));
guint32 offset = decode_value (p, &p);
guint8 *p2 = module->blob + offset;
ctx.class_inst = decode_generic_inst (module, p2, &p2, error);
if (!ctx.class_inst)
return NULL;
type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
if (!type)
return NULL;
klass = mono_class_from_mono_type_internal (type);
mono_metadata_free_type (type);
break;
}
case MONO_AOT_TYPEREF_VAR: {
MonoType *t = NULL;
MonoGenericContainer *container = NULL;
gboolean has_constraint = decode_value (p, &p);
if (has_constraint) {
MonoClass *par_klass;
MonoType *gshared_constraint;
gshared_constraint = decode_type (module, p, &p, error);
if (!gshared_constraint)
return NULL;
par_klass = decode_klass_ref (module, p, &p, error);
if (!par_klass)
return NULL;
t = mini_get_shared_gparam (m_class_get_byval_arg (par_klass), gshared_constraint);
mono_metadata_free_type (gshared_constraint);
klass = mono_class_from_mono_type_internal (t);
} else {
int type = decode_value (p, &p);
int num = decode_value (p, &p);
gboolean is_not_anonymous = decode_value (p, &p);
if (is_not_anonymous) {
gboolean is_method = decode_value (p, &p);
if (is_method) {
MonoMethod *method_def;
g_assert (type == MONO_TYPE_MVAR);
method_def = decode_resolve_method_ref (module, p, &p, error);
if (!method_def)
return NULL;
container = mono_method_get_generic_container (method_def);
} else {
MonoClass *class_def;
g_assert (type == MONO_TYPE_VAR);
class_def = decode_klass_ref (module, p, &p, error);
if (!class_def)
return NULL;
container = mono_class_try_get_generic_container (class_def); //FIXME is this a case for a try_get?
}
} else {
// We didn't decode is_method, so we have to infer it from type enum.
container = mono_get_anonymous_container_for_image (module->assembly->image, type == MONO_TYPE_MVAR);
}
t = g_new0 (MonoType, 1);
t->type = (MonoTypeEnum)type;
if (is_not_anonymous) {
t->data.generic_param = mono_generic_container_get_param (container, num);
} else {
/* Anonymous */
MonoGenericParam *par = mono_metadata_create_anon_gparam (module->assembly->image, num, type == MONO_TYPE_MVAR);
t->data.generic_param = par;
// FIXME: maybe do this for all anon gparams?
((MonoGenericParamFull*)par)->info.name = mono_make_generic_name_string (module->assembly->image, num);
}
// FIXME: Maybe use types directly to avoid
// the overhead of creating MonoClass-es
klass = mono_class_from_mono_type_internal (t);
g_free (t);
}
break;
}
case MONO_AOT_TYPEREF_ARRAY:
/* Array */
rank = decode_value (p, &p);
eklass = decode_klass_ref (module, p, &p, error);
if (!eklass)
return NULL;
klass = mono_class_create_array (eklass, rank);
break;
case MONO_AOT_TYPEREF_PTR: {
MonoType *t;
t = decode_type (module, p, &p, error);
if (!t)
return NULL;
klass = mono_class_from_mono_type_internal (t);
g_free (t);
break;
}
case MONO_AOT_TYPEREF_BLOB_INDEX: {
guint32 offset = decode_value (p, &p);
guint8 *p2;
p2 = module->blob + offset;
klass = decode_klass_ref (module, p2, &p2, error);
break;
}
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid klass reftype %d: %s", reftype, module->aot_name);
}
//g_assert (klass);
//printf ("BLA: %s\n", mono_type_full_name (m_class_get_byval_arg (klass)));
*endbuf = p;
return klass;
}
static MonoClassField*
decode_field_info (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
MonoClass *klass = decode_klass_ref (module, buf, &buf, error);
guint32 token;
guint8 *p = buf;
if (!klass) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
return NULL;
}
token = MONO_TOKEN_FIELD_DEF + decode_value (p, &p);
*endbuf = p;
return mono_class_get_field (klass, token);
}
/*
* Parse a MonoType encoded by encode_type () in aot-compiler.c. Return malloc-ed
* memory.
*/
static MonoType*
decode_type (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint8 *p = buf;
MonoType *t;
if (*p == MONO_TYPE_CMOD_REQD) {
++p;
int count = decode_value (p, &p);
/* TODO: encode aggregate cmods differently than simple cmods and make it possible to use the more compact encoding here. */
t = (MonoType*)g_malloc0 (mono_sizeof_type_with_mods (count, TRUE));
mono_type_with_mods_init (t, count, TRUE);
/* Try not to blow up the stack. See comment on MONO_MAX_EXPECTED_CMODS */
g_assert (count < MONO_MAX_EXPECTED_CMODS);
MonoAggregateModContainer *cm = g_alloca (mono_sizeof_aggregate_modifiers (count));
cm->count = count;
for (int i = 0; i < count; ++i) {
MonoSingleCustomMod *cmod = &cm->modifiers [i];
cmod->required = decode_value (p, &p);
cmod->type = decode_type (module, p, &p, error);
goto_if_nok (error, fail);
}
mono_type_set_amods (t, mono_metadata_get_canonical_aggregate_modifiers (cm));
for (int i = 0; i < count; ++i)
mono_metadata_free_type (cm->modifiers [i].type);
} else {
t = (MonoType *) g_malloc0 (MONO_SIZEOF_TYPE);
}
while (TRUE) {
if (*p == MONO_TYPE_PINNED) {
t->pinned = TRUE;
++p;
} else if (*p == MONO_TYPE_BYREF) {
t->byref__ = TRUE;
++p;
} else {
break;
}
}
t->type = (MonoTypeEnum)*p;
++p;
switch (t->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:
t->data.klass = decode_klass_ref (module, p, &p, error);
if (!t->data.klass)
goto fail;
break;
case MONO_TYPE_SZARRAY:
t->data.klass = decode_klass_ref (module, p, &p, error);
if (!t->data.klass)
goto fail;
break;
case MONO_TYPE_PTR:
t->data.type = decode_type (module, p, &p, error);
if (!t->data.type)
goto fail;
break;
case MONO_TYPE_FNPTR:
t->data.method = decode_signature (module, p, &p);
if (!t->data.method)
goto fail;
break;
case MONO_TYPE_GENERICINST: {
MonoClass *gclass;
MonoGenericContext ctx;
MonoType *type;
MonoClass *klass;
gclass = decode_klass_ref (module, p, &p, error);
if (!gclass)
goto fail;
g_assert (mono_class_is_gtd (gclass));
memset (&ctx, 0, sizeof (ctx));
ctx.class_inst = decode_generic_inst (module, p, &p, error);
if (!ctx.class_inst)
goto fail;
type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (gclass), &ctx, error);
if (!type)
goto fail;
klass = mono_class_from_mono_type_internal (type);
t->data.generic_class = mono_class_get_generic_class (klass);
break;
}
case MONO_TYPE_ARRAY: {
MonoArrayType *array;
int i;
// FIXME: memory management
array = g_new0 (MonoArrayType, 1);
array->eklass = decode_klass_ref (module, p, &p, error);
if (!array->eklass)
goto fail;
array->rank = decode_value (p, &p);
array->numsizes = decode_value (p, &p);
if (array->numsizes)
array->sizes = (int *)g_malloc0 (sizeof (int) * array->numsizes);
for (i = 0; i < array->numsizes; ++i)
array->sizes [i] = decode_value (p, &p);
array->numlobounds = decode_value (p, &p);
if (array->numlobounds)
array->lobounds = (int *)g_malloc0 (sizeof (int) * array->numlobounds);
for (i = 0; i < array->numlobounds; ++i)
array->lobounds [i] = decode_value (p, &p);
t->data.array = array;
break;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR: {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
goto fail;
t->data.generic_param = m_class_get_byval_arg (klass)->data.generic_param;
break;
}
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid encoded type %d: %s", t->type, module->aot_name);
goto fail;
}
*endbuf = p;
return t;
fail:
g_free (t);
return NULL;
}
// FIXME: Error handling, memory management
static MonoMethodSignature*
decode_signature_with_target (MonoAotModule *module, MonoMethodSignature *target, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
MonoMethodSignature *sig;
guint32 flags;
int i, gen_param_count = 0, param_count, call_conv;
guint8 *p = buf;
gboolean hasthis, explicit_this, has_gen_params, pinvoke;
flags = *p;
p ++;
has_gen_params = (flags & 0x10) != 0;
hasthis = (flags & 0x20) != 0;
explicit_this = (flags & 0x40) != 0;
pinvoke = (flags & 0x80) != 0;
call_conv = flags & 0x0F;
if (has_gen_params)
gen_param_count = decode_value (p, &p);
param_count = decode_value (p, &p);
if (target && param_count != target->param_count)
return NULL;
sig = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + param_count * sizeof (MonoType *));
sig->param_count = param_count;
sig->sentinelpos = -1;
sig->hasthis = hasthis;
sig->explicit_this = explicit_this;
sig->pinvoke = pinvoke;
sig->call_convention = call_conv;
sig->generic_param_count = gen_param_count;
sig->ret = decode_type (module, p, &p, error);
if (!sig->ret)
goto fail;
for (i = 0; i < param_count; ++i) {
if (*p == MONO_TYPE_SENTINEL) {
g_assert (sig->call_convention == MONO_CALL_VARARG);
sig->sentinelpos = i;
p ++;
}
sig->params [i] = decode_type (module, p, &p, error);
if (!sig->params [i])
goto fail;
}
if (sig->call_convention == MONO_CALL_VARARG && sig->sentinelpos == -1)
sig->sentinelpos = sig->param_count;
*endbuf = p;
return sig;
fail:
mono_error_cleanup (error); /* FIXME don't swallow the error */
g_free (sig);
return NULL;
}
static MonoMethodSignature*
decode_signature (MonoAotModule *module, guint8 *buf, guint8 **endbuf)
{
return decode_signature_with_target (module, NULL, buf, endbuf);
}
static gboolean
sig_matches_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf)
{
MonoMethodSignature *sig;
gboolean res;
guint8 *p = buf;
sig = decode_signature_with_target (module, mono_method_signature_internal (target), p, &p);
res = sig && mono_metadata_signature_equal (mono_method_signature_internal (target), sig);
g_free (sig);
*endbuf = p;
return res;
}
/* Stores information returned by decode_method_ref () */
typedef struct {
MonoImage *image;
guint32 token;
MonoMethod *method;
gboolean no_aot_trampoline;
} MethodRef;
/*
* decode_method_ref_with_target:
*
* Decode a method reference, storing the image/token into a MethodRef structure.
* This avoids loading metadata for the method if the caller does not need it. If the method has
* no token, then it is loaded from metadata and ref->method is set to the method instance.
* If TARGET is non-NULL, abort decoding if it can be determined that the decoded method
* couldn't resolve to TARGET, and return FALSE.
* There are some kinds of method references which only support a non-null TARGET.
* This means that its not possible to decode this into a method, only to check
* that the method reference matches a given method. This is normally not a problem
* as these wrappers only occur in the extra_methods table, where we already have
* a method we want to lookup.
*
* If there was a decoding error, we return FALSE and set @error
*/
static gboolean
decode_method_ref_with_target (MonoAotModule *module, MethodRef *ref, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
{
guint32 image_index, value;
MonoImage *image = NULL;
guint8 *p = buf;
memset (ref, 0, sizeof (MethodRef));
error_init (error);
value = decode_value (p, &p);
image_index = value >> 24;
if (image_index == MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE) {
ref->no_aot_trampoline = TRUE;
value = decode_value (p, &p);
image_index = value >> 24;
}
if (image_index < MONO_AOT_METHODREF_MIN || image_index == MONO_AOT_METHODREF_METHODSPEC ||
image_index == MONO_AOT_METHODREF_GINST || image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
if (target && target->wrapper_type) {
return FALSE;
}
}
if (image_index == MONO_AOT_METHODREF_WRAPPER) {
WrapperInfo *info;
guint32 wrapper_type;
wrapper_type = decode_value (p, &p);
if (target && target->wrapper_type != wrapper_type)
return FALSE;
/* Doesn't matter */
image = mono_defaults.corlib;
switch (wrapper_type) {
case MONO_WRAPPER_ALLOC: {
int atype = decode_value (p, &p);
ManagedAllocatorVariant variant =
mono_profiler_allocations_enabled () ?
MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR;
ref->method = mono_gc_get_managed_allocator_by_type (atype, variant);
/* Try to fallback to the slow path version */
if (!ref->method)
ref->method = mono_gc_get_managed_allocator_by_type (atype, MANAGED_ALLOCATOR_SLOW_PATH);
if (!ref->method) {
mono_error_set_bad_image_by_name (error, module->aot_name, "Error: No managed allocator, but we need one for AOT.\nAre you using non-standard GC options?\n%s\n", module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_WRITE_BARRIER: {
ref->method = mono_gc_get_write_barrier ();
break;
}
case MONO_WRAPPER_STELEMREF: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_NONE) {
ref->method = mono_marshal_get_stelemref ();
} else if (subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF) {
int kind;
kind = decode_value (p, &p);
ref->method = mono_marshal_get_virtual_stelemref_wrapper ((MonoStelemrefKind)kind);
} else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid STELEMREF subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_SYNCHRONIZED: {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_synchronized_wrapper (m);
break;
}
case MONO_WRAPPER_OTHER: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE || subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
if (!target)
return FALSE;
if (klass != target->klass)
return FALSE;
if (subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE) {
if (strcmp (target->name, "PtrToStructure"))
return FALSE;
ref->method = mono_marshal_get_ptr_to_struct (klass);
} else {
if (strcmp (target->name, "StructureToPtr"))
return FALSE;
ref->method = mono_marshal_get_struct_to_ptr (klass);
}
} else if (subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_synchronized_inner_wrapper (m);
} else if (subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_array_accessor_wrapper (m);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN) {
ref->method = mono_marshal_get_gsharedvt_in_wrapper ();
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
ref->method = mono_marshal_get_gsharedvt_out_wrapper ();
} else if (subtype == WRAPPER_SUBTYPE_INTERP_IN) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_interp_in_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_INTERP_LMF) {
MonoJitICallInfo *info = mono_find_jit_icall_info ((MonoJitICallId)decode_value (p, &p));
ref->method = mini_get_interp_lmf_wrapper (info->name, (gpointer) info->func);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_gsharedvt_in_sig_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mini_get_gsharedvt_out_sig_wrapper (sig);
g_free (sig);
} else if (subtype == WRAPPER_SUBTYPE_AOT_INIT) {
guint32 init_type = decode_value (p, &p);
ref->method = mono_marshal_get_aot_init_wrapper ((MonoAotInitSubtype) init_type);
} else if (subtype == WRAPPER_SUBTYPE_LLVM_FUNC) {
guint32 init_type = decode_value (p, &p);
ref->method = mono_marshal_get_llvm_func_wrapper ((MonoLLVMFuncWrapperSubtype) init_type);
} else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid UNKNOWN wrapper subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_MANAGED_TO_MANAGED: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
int rank = decode_value (p, &p);
int elem_size = decode_value (p, &p);
ref->method = mono_marshal_get_array_address (rank, elem_size);
} else if (subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
MonoMethod *m;
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
if (!target)
return FALSE;
g_assert (target->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED);
info = mono_marshal_get_wrapper_info (target);
if (info && info->subtype == subtype && info->d.string_ctor.method == m)
ref->method = target;
else
return FALSE;
} else if (subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
int name_idx = decode_value (p, &p);
const char *name = (const char*)module->blob + name_idx;
ref->method = mono_marshal_get_generic_array_helper (klass, name, m);
}
break;
}
case MONO_WRAPPER_MANAGED_TO_NATIVE: {
MonoMethod *m;
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
MonoJitICallInfo *info = mono_find_jit_icall_info ((MonoJitICallId)decode_value (p, &p));
ref->method = mono_icall_get_wrapper_method (info);
} else if (subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_INDIRECT) {
MonoClass *klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
MonoMethodSignature *sig = decode_signature (module, p, &p);
if (!sig)
return FALSE;
ref->method = mono_marshal_get_native_func_wrapper_indirect (klass, sig, TRUE);
} else {
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
/* This should only happen when looking for an extra method */
if (!target)
return FALSE;
if (mono_marshal_method_from_wrapper (target) == m)
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_CASTCLASS: {
int subtype = decode_value (p, &p);
if (subtype == WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE)
ref->method = mono_marshal_get_castclass_with_cache ();
else if (subtype == WRAPPER_SUBTYPE_ISINST_WITH_CACHE)
ref->method = mono_marshal_get_isinst_with_cache ();
else {
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid CASTCLASS wrapper subtype %d: %s", subtype, module->aot_name);
return FALSE;
}
break;
}
case MONO_WRAPPER_RUNTIME_INVOKE: {
int subtype = decode_value (p, &p);
if (!target)
return FALSE;
if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC) {
if (strcmp (target->name, "runtime_invoke_dynamic") != 0)
return FALSE;
ref->method = target;
} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT) {
/* Direct wrapper */
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_runtime_invoke (m, FALSE);
} else if (subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL) {
/* Virtual direct wrapper */
MonoMethod *m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
ref->method = mono_marshal_get_runtime_invoke (m, TRUE);
} else {
MonoMethodSignature *sig;
sig = decode_signature_with_target (module, NULL, p, &p);
info = mono_marshal_get_wrapper_info (target);
g_assert (info);
if (info->subtype != subtype) {
g_free (sig);
return FALSE;
}
g_assert (info->d.runtime_invoke.sig);
const gboolean same_sig = mono_metadata_signature_equal (sig, info->d.runtime_invoke.sig);
g_free (sig);
if (same_sig)
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_DELEGATE_INVOKE:
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
case MONO_WRAPPER_DELEGATE_END_INVOKE: {
gboolean is_inflated = decode_value (p, &p);
WrapperSubtype subtype;
if (is_inflated) {
MonoClass *klass;
MonoMethod *invoke, *wrapper;
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
switch (wrapper_type) {
case MONO_WRAPPER_DELEGATE_INVOKE:
invoke = mono_get_delegate_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_invoke (invoke, NULL);
break;
case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
invoke = mono_get_delegate_begin_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_begin_invoke (invoke);
break;
case MONO_WRAPPER_DELEGATE_END_INVOKE:
invoke = mono_get_delegate_end_invoke_internal (klass);
wrapper = mono_marshal_get_delegate_end_invoke (invoke);
break;
default:
g_assert_not_reached ();
break;
}
if (target) {
/*
* Due to the way mini_get_shared_method_full () works, we could end up with
* multiple copies of the same wrapper.
*/
if (wrapper->klass != target->klass)
return FALSE;
ref->method = target;
} else {
ref->method = wrapper;
}
} else {
/*
* These wrappers are associated with a signature, not with a method.
* Since we can't decode them into methods, they need a target method.
*/
if (!target)
return FALSE;
if (wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
subtype = (WrapperSubtype)decode_value (p, &p);
info = mono_marshal_get_wrapper_info (target);
if (info) {
if (info->subtype != subtype)
return FALSE;
} else {
if (subtype != WRAPPER_SUBTYPE_NONE)
return FALSE;
}
}
if (sig_matches_target (module, target, p, &p))
ref->method = target;
else
return FALSE;
}
break;
}
case MONO_WRAPPER_NATIVE_TO_MANAGED: {
MonoMethod *m;
MonoClass *klass;
m = decode_resolve_method_ref (module, p, &p, error);
if (!m)
return FALSE;
gboolean has_class = decode_value (p, &p);
if (has_class) {
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
} else
klass = NULL;
ref->method = mono_marshal_get_managed_wrapper (m, klass, 0, error);
if (!is_ok (error))
return FALSE;
break;
}
default:
g_assert_not_reached ();
}
} else if (image_index == MONO_AOT_METHODREF_METHODSPEC) {
image_index = decode_value (p, &p);
ref->token = decode_value (p, &p);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_BLOB_INDEX) {
guint32 offset = decode_value (p, &p);
guint8 *p2;
p2 = module->blob + offset;
if (!decode_method_ref_with_target (module, ref, target, p2, &p2, error))
return FALSE;
image = ref->image;
if (!image)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_GINST) {
MonoClass *klass;
MonoGenericContext ctx;
guint32 token_index;
/*
* These methods do not have a token which resolves them, so we
* resolve them immediately.
*/
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
if (target && target->klass != klass)
return FALSE;
image_index = decode_value (p, &p);
token_index = decode_value (p, &p);
ref->token = mono_metadata_make_token (MONO_TABLE_METHOD, token_index);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
ref->method = mono_get_method_checked (image, ref->token, NULL, NULL, error);
if (!ref->method)
return FALSE;
memset (&ctx, 0, sizeof (ctx));
if (FALSE && mono_class_is_ginst (klass)) {
ctx.class_inst = mono_class_get_generic_class (klass)->context.class_inst;
ctx.method_inst = NULL;
ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
if (!ref->method)
return FALSE;
}
memset (&ctx, 0, sizeof (ctx));
if (!decode_generic_context (module, &ctx, p, &p, error))
return FALSE;
ref->method = mono_class_inflate_generic_method_full_checked (ref->method, klass, &ctx, error);
if (!ref->method)
return FALSE;
} else if (image_index == MONO_AOT_METHODREF_ARRAY) {
MonoClass *klass;
int method_type;
klass = decode_klass_ref (module, p, &p, error);
if (!klass)
return FALSE;
method_type = decode_value (p, &p);
switch (method_type) {
case 0:
ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass), 0, error);
return_val_if_nok (error, FALSE);
break;
case 1:
ref->method = mono_class_get_method_from_name_checked (klass, ".ctor", m_class_get_rank (klass) * 2, 0, error);
return_val_if_nok (error, FALSE);
break;
case 2:
ref->method = mono_class_get_method_from_name_checked (klass, "Get", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
case 3:
ref->method = mono_class_get_method_from_name_checked (klass, "Address", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
case 4:
ref->method = mono_class_get_method_from_name_checked (klass, "Set", -1, 0, error);
return_val_if_nok (error, FALSE);
break;
default:
mono_error_set_bad_image_by_name (error, module->aot_name, "Invalid METHODREF_ARRAY method type %d: %s", method_type, module->aot_name);
return FALSE;
}
} else {
if (image_index == MONO_AOT_METHODREF_LARGE_IMAGE_INDEX) {
image_index = decode_value (p, &p);
value = decode_value (p, &p);
}
ref->token = MONO_TOKEN_METHOD_DEF | (value & 0xffffff);
image = load_image (module, image_index, error);
if (!image)
return FALSE;
}
*endbuf = p;
ref->image = image;
return TRUE;
}
static gboolean
decode_method_ref (MonoAotModule *module, MethodRef *ref, guint8 *buf, guint8 **endbuf, MonoError *error)
{
return decode_method_ref_with_target (module, ref, NULL, buf, endbuf, error);
}
/*
* decode_resolve_method_ref_with_target:
*
* Similar to decode_method_ref, but resolve and return the method itself.
*/
static MonoMethod*
decode_resolve_method_ref_with_target (MonoAotModule *module, MonoMethod *target, guint8 *buf, guint8 **endbuf, MonoError *error)
{
MethodRef ref;
error_init (error);
if (!decode_method_ref_with_target (module, &ref, target, buf, endbuf, error))
return NULL;
if (ref.method)
return ref.method;
if (!ref.image) {
mono_error_set_bad_image_by_name (error, module->aot_name, "No image found for methodref with target: %s", module->aot_name);
return NULL;
}
return mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
}
static MonoMethod*
decode_resolve_method_ref (MonoAotModule *module, guint8 *buf, guint8 **endbuf, MonoError *error)
{
return decode_resolve_method_ref_with_target (module, NULL, buf, endbuf, error);
}
static void
find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *value)
{
if (globals) {
int global_index;
guint16 *table, *entry;
guint16 table_size;
guint32 hash;
char *symbol = (char*)name;
#ifdef TARGET_MACH
symbol = g_strdup_printf ("_%s", name);
#endif
/* The first entry points to the hash */
table = (guint16 *)globals [0];
globals ++;
table_size = table [0];
table ++;
hash = mono_metadata_str_hash (symbol) % table_size;
entry = &table [hash * 2];
/* Search the hash for the index into the globals table */
global_index = -1;
while (entry [0] != 0) {
guint32 index = entry [0] - 1;
guint32 next = entry [1];
//printf ("X: %s %s\n", (char*)globals [index * 2], name);
if (!strcmp ((const char*)globals [index * 2], symbol)) {
global_index = index;
break;
}
if (next != 0) {
entry = &table [next * 2];
} else {
break;
}
}
if (global_index != -1)
*value = globals [global_index * 2 + 1];
else
*value = NULL;
if (symbol != name)
g_free (symbol);
} else {
char *err = mono_dl_symbol (module, name, value);
if (err)
g_free (err);
}
}
static void
find_amodule_symbol (MonoAotModule *amodule, const char *name, gpointer *value)
{
g_assert (!(amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY));
find_symbol (amodule->sofile, amodule->globals, name, value);
}
void
mono_install_load_aot_data_hook (MonoLoadAotDataFunc load_func, MonoFreeAotDataFunc free_func, gpointer user_data)
{
aot_data_load_func = load_func;
aot_data_free_func = free_func;
aot_data_func_user_data = user_data;
}
/* Load the separate aot data file for ASSEMBLY */
static guint8*
open_aot_data (MonoAssembly *assembly, MonoAotFileInfo *info, void **ret_handle)
{
MonoFileMap *map;
char *filename;
guint8 *data;
if (aot_data_load_func) {
data = aot_data_load_func (assembly, info->datafile_size, aot_data_func_user_data, ret_handle);
g_assert (data);
return data;
}
/*
* Use <assembly name>.aotdata as the default implementation if no callback is given
*/
filename = g_strdup_printf ("%s.aotdata", assembly->image->name);
map = mono_file_map_open (filename);
g_assert (map);
data = (guint8*)mono_file_map (info->datafile_size, MONO_MMAP_READ, mono_file_map_fd (map), 0, ret_handle);
g_assert (data);
return data;
}
static gboolean
check_usable (MonoAssembly *assembly, MonoAotFileInfo *info, guint8 *blob, char **out_msg)
{
char *build_info;
char *msg = NULL;
gboolean usable = TRUE;
gboolean full_aot, interp, safepoints;
guint32 excluded_cpu_optimizations;
if (strcmp (assembly->image->guid, (const char*)info->assembly_guid)) {
msg = g_strdup ("doesn't match assembly");
usable = FALSE;
}
build_info = mono_get_runtime_build_info ();
if (strlen ((const char *)info->runtime_version) > 0 && strcmp (info->runtime_version, build_info)) {
msg = g_strdup_printf ("compiled against runtime version '%s' while this runtime has version '%s'", info->runtime_version, build_info);
usable = FALSE;
}
g_free (build_info);
full_aot = info->flags & MONO_AOT_FILE_FLAG_FULL_AOT;
interp = info->flags & MONO_AOT_FILE_FLAG_INTERP;
if (mono_aot_only && !full_aot) {
if (!interp) {
msg = g_strdup ("not compiled with --aot=full");
usable = FALSE;
}
}
if (!mono_aot_only && full_aot) {
msg = g_strdup ("compiled with --aot=full");
usable = FALSE;
}
if (mono_use_interpreter && !interp && !strcmp (assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME)) {
/* mscorlib contains necessary interpreter trampolines */
msg = g_strdup ("not compiled with --aot=interp");
usable = FALSE;
}
if (mono_llvm_only && !(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
msg = g_strdup ("not compiled with --aot=llvmonly");
usable = FALSE;
}
if (mono_use_llvm && !(info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)) {
/* Prefer LLVM JITted code when using --llvm */
msg = g_strdup ("not compiled with --aot=llvm");
usable = FALSE;
}
if (mini_debug_options.mdb_optimizations && !(info->flags & MONO_AOT_FILE_FLAG_DEBUG) && !full_aot && !interp) {
msg = g_strdup ("not compiled for debugging");
usable = FALSE;
}
mono_arch_cpu_optimizations (&excluded_cpu_optimizations);
if (info->opts & excluded_cpu_optimizations) {
msg = g_strdup ("compiled with unsupported CPU optimizations");
usable = FALSE;
}
if (info->gc_name_index != -1) {
char *gc_name = (char*)&blob [info->gc_name_index];
const char *current_gc_name = mono_gc_get_gc_name ();
if (strcmp (current_gc_name, gc_name) != 0) {
msg = g_strdup_printf ("compiled against GC %s, while the current runtime uses GC %s.\n", gc_name, current_gc_name);
usable = FALSE;
}
}
safepoints = info->flags & MONO_AOT_FILE_FLAG_SAFEPOINTS;
if (!safepoints && mono_threads_are_safepoints_enabled ()) {
msg = g_strdup ("not compiled with safepoints");
usable = FALSE;
}
#ifdef MONO_ARCH_CODE_EXEC_ONLY
if (!(info->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)) {
msg = g_strdup ("not compiled targeting a runtime configured as CODE_EXEC_ONLY");
usable = FALSE;
}
#else
if (info->flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
msg = g_strdup ("compiled targeting a runtime configured as CODE_EXEC_ONLY");
usable = FALSE;
}
#endif
*out_msg = msg;
return usable;
}
/*
* TABLE should point to a table of call instructions. Return the address called by the INDEXth entry.
*/
static void*
get_call_table_entry (void *table, int index, int entry_size)
{
#if defined(TARGET_ARM)
guint32 *ins_addr;
guint32 ins;
gint32 offset;
if (entry_size == 8) {
ins_addr = (guint32 *)table + (index * 2);
g_assert ((guint32) *ins_addr == (guint32 ) 0xe51ff004); // ldr pc, =<label>
return *((char **) (ins_addr + 1));
}
g_assert (entry_size == 4);
ins_addr = (guint32*)table + index;
ins = *ins_addr;
if ((ins >> ARMCOND_SHIFT) == ARMCOND_NV) {
/* blx */
offset = (((int)(((ins & 0xffffff) << 1) | ((ins >> 24) & 0x1))) << 7) >> 7;
return (char*)ins_addr + (offset * 2) + 8 + 1;
} else {
g_assert ((ins >> ARMCOND_SHIFT) == ARMCOND_AL);
/* bl */
offset = (((int)ins & 0xffffff) << 8) >> 8;
return (char*)ins_addr + (offset * 4) + 8;
}
#elif defined(TARGET_ARM64)
return mono_arch_get_call_target ((guint8*)table + (index * 4) + 4);
#elif defined(TARGET_X86) || defined(TARGET_AMD64)
/* The callee expects an ip which points after the call */
return mono_arch_get_call_target ((guint8*)table + (index * 5) + 5);
#else
g_assert_not_reached ();
return NULL;
#endif
}
/*
* init_amodule_got:
*
* Initialize the shared got entries for AMODULE.
*/
static void
init_amodule_got (MonoAotModule *amodule, gboolean preinit)
{
MonoJumpInfo *ji;
MonoMemPool *mp;
MonoJumpInfo *patches;
guint32 got_offsets [128];
ERROR_DECL (error);
int i, npatches;
/* These can't be initialized in load_aot_module () */
if (amodule->got_initialized == GOT_INITIALIZED)
return;
mono_loader_lock ();
/*
* If it is initialized some other thread did it in the meantime. If it is
* initializing it means the current thread is initializing it since we are
* holding the loader lock, skip it.
*/
if (amodule->got_initialized) {
mono_loader_unlock ();
return;
}
if (!preinit)
amodule->got_initialized = GOT_INITIALIZING;
mp = mono_mempool_new ();
npatches = amodule->info.nshared_got_entries;
for (i = 0; i < npatches; ++i)
got_offsets [i] = i;
if (amodule->got)
patches = decode_patches (amodule, mp, npatches, FALSE, got_offsets);
else
patches = decode_patches (amodule, mp, npatches, TRUE, got_offsets);
g_assert (patches);
for (i = 0; i < npatches; ++i) {
ji = &patches [i];
if (amodule->shared_got [i]) {
} else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
amodule->shared_got [i] = amodule;
} else if (preinit) {
/*
* This is called from init_amodule () during startup, so some things might not
* be setup. Initialize just the slots needed to make method initialization work.
*/
if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
if (ji->data.jit_icall_id == MONO_JIT_ICALL_mini_llvm_init_method)
amodule->shared_got [i] = (gpointer)mini_llvm_init_method;
}
} else if (ji->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_START && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_GC_NURSERY_BITS && !mono_gc_is_moving ()) {
amodule->shared_got [i] = NULL;
} else if (ji->type == MONO_PATCH_INFO_IMAGE) {
amodule->shared_got [i] = amodule->assembly->image;
} else if (ji->type == MONO_PATCH_INFO_MSCORLIB_GOT_ADDR) {
if (mono_defaults.corlib) {
MonoAotModule *mscorlib_amodule = mono_defaults.corlib->aot_module;
if (mscorlib_amodule)
amodule->shared_got [i] = mscorlib_amodule->got;
} else {
amodule->shared_got [i] = amodule->got;
}
} else if (ji->type == MONO_PATCH_INFO_AOT_MODULE) {
amodule->shared_got [i] = amodule;
} else if (ji->type == MONO_PATCH_INFO_NONE) {
} else {
amodule->shared_got [i] = mono_resolve_patch_target (NULL, NULL, ji, FALSE, error);
mono_error_assert_ok (error);
}
}
if (amodule->got) {
for (i = 0; i < npatches; ++i)
amodule->got [i] = amodule->shared_got [i];
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_WITH_LLVM) {
void (*init_aotconst) (int, gpointer) = (void (*)(int, gpointer))amodule->info.llvm_init_aotconst;
for (i = 0; i < npatches; ++i) {
amodule->llvm_got [i] = amodule->shared_got [i];
init_aotconst (i, amodule->llvm_got [i]);
}
}
mono_mempool_destroy (mp);
if (!preinit) {
mono_memory_barrier ();
amodule->got_initialized = GOT_INITIALIZED;
}
mono_loader_unlock ();
}
#ifdef MONOTOUCH
// Follow branch islands on ARM iOS machines.
static inline guint8 *
method_address_resolve (guint8 *code_addr)
{
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
#if defined(TARGET_ARM)
// Skip branches to thumb destinations; the convention used is that the
// lowest bit is set if the destination is thumb. See
// get_call_table_entry.
if (((uintptr_t) code_addr) & 0x1)
return code_addr;
#endif
for (;;) {
// `mono_arch_get_call_target` takes the IP after the branch
// instruction, not before. Add 4 bytes to compensate.
guint8 *next = mono_arch_get_call_target (code_addr + 4);
if (next == NULL) return code_addr;
code_addr = next;
}
#endif
return code_addr;
}
#else
static inline guint8 *
method_address_resolve (guint8 *code_addr) {
return code_addr;
}
#endif
#ifdef HOST_WASM
static void
register_methods_in_jinfo (MonoAotModule *amodule)
{
MonoAssembly *assembly = amodule->assembly;
int i;
static MonoBitSet *registered;
static int registered_len;
/*
* Register the methods in AMODULE in the jit info table. There are 2 issues:
* - emscripten could reorder code so methods from different aot images are intermixed.
* - if linkonce linking is used, multiple aot images could refer to the same method.
*/
sort_methods (amodule);
if (amodule->sorted_methods_len == 0)
return;
mono_aot_lock ();
/* The 'registered' bitset contains whenever we have already registered a method in the jit info table */
int max = -1;
for (i = 0; i < amodule->sorted_methods_len; ++i)
max = MAX (max, GPOINTER_TO_INT (amodule->sorted_methods [i]));
g_assert (max != -1);
if (registered == NULL) {
registered = mono_bitset_new (max, 0);
registered_len = max;
} else if (max > registered_len) {
MonoBitSet *new_registered = mono_bitset_clone (registered, max);
mono_bitset_free (registered);
registered = new_registered;
registered_len = max;
}
#if 0
for (i = 0; i < amodule->sorted_methods_len; ++i) {
printf ("%s %d\n", amodule->assembly->aname.name, amodule->sorted_methods [i]);
}
#endif
int start = 0;
while (start < amodule->sorted_methods_len) {
/* Find beginning of interval */
int start_method = GPOINTER_TO_INT (amodule->sorted_methods [start]);
if (mono_bitset_test_fast (registered, start_method)) {
start ++;
continue;
}
/* Find end of interval */
int end = start + 1;
while (end < amodule->sorted_methods_len && GPOINTER_TO_INT (amodule->sorted_methods [end]) == GPOINTER_TO_INT (amodule->sorted_methods [end - 1]) + 1 && !mono_bitset_test_fast (registered, GPOINTER_TO_INT (amodule->sorted_methods [end])))
end ++;
int end_method = GPOINTER_TO_INT (amodule->sorted_methods [end - 1]);
//printf ("%s [%d %d]\n", amodule->assembly->aname.name, start_method, end_method);
/* The 'end' parameter is exclusive */
mono_jit_info_add_aot_module (assembly->image, GINT_TO_POINTER (start_method), GINT_TO_POINTER (end_method + 1));
for (int j = start_method; j < end_method + 1; ++j)
g_assert (!mono_bitset_test_fast (registered, j));
start = end;
}
for (i = 0; i < amodule->sorted_methods_len; ++i)
mono_bitset_set_fast (registered, GPOINTER_TO_INT (amodule->sorted_methods [i]));
mono_aot_unlock ();
}
#endif
static void
load_aot_module (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error)
{
char *aot_name, *found_aot_name;
MonoAotModule *amodule;
MonoDl *sofile;
gboolean usable = TRUE;
char *version_symbol = NULL;
char *msg = NULL;
gpointer *globals = NULL;
MonoAotFileInfo *info = NULL;
int i, version;
gboolean do_load_image = TRUE;
int align_double, align_int64;
guint8 *aot_data = NULL;
if (mono_compile_aot)
return;
if (mono_aot_mode == MONO_AOT_MODE_NONE)
return;
if (assembly->image->aot_module)
/*
* Already loaded. This can happen because the assembly loading code might invoke
* the assembly load hooks multiple times for the same assembly.
*/
return;
if (image_is_dynamic (assembly->image))
return;
gboolean loaded = FALSE;
mono_aot_lock ();
if (static_aot_modules)
info = (MonoAotFileInfo *)g_hash_table_lookup (static_aot_modules, assembly->aname.name);
if (info) {
if (!loaded_static_aot_modules)
loaded_static_aot_modules = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (loaded_static_aot_modules, info))
loaded = TRUE;
else
g_hash_table_insert (loaded_static_aot_modules, info, info);
}
mono_aot_unlock ();
if (loaded)
/*
* Already loaded by another assembly with the same name, or the same assembly loaded
* in another ALC.
*/
return;
sofile = NULL;
found_aot_name = NULL;
if (info) {
/* Statically linked AOT module */
aot_name = g_strdup_printf ("%s", assembly->aname.name);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "Found statically linked AOT module '%s'.", aot_name);
if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
globals = (void **)info->globals;
g_assert (globals);
}
found_aot_name = g_strdup (aot_name);
} else {
char *err;
aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
if (sofile) {
found_aot_name = g_strdup (aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
g_free (err);
}
g_free (aot_name);
if (!sofile) {
GList *l;
for (l = mono_aot_paths; l; l = l->next) {
char *path = (char*)l->data;
char *basename = g_path_get_basename (assembly->image->name);
aot_name = g_strdup_printf ("%s/%s%s", path, basename, MONO_SOLIB_EXT);
sofile = mono_dl_open (aot_name, MONO_DL_LAZY, &err);
if (sofile) {
found_aot_name = g_strdup (aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' not found: %s", aot_name, err);
g_free (err);
}
g_free (basename);
g_free (aot_name);
if (sofile)
break;
}
}
if (!sofile) {
// Maybe do these on more platforms ?
#ifndef HOST_WASM
if (mono_aot_only && !mono_use_interpreter && table_info_get_rows (&assembly->image->tables [MONO_TABLE_METHOD])) {
aot_name = g_strdup_printf ("%s%s", assembly->image->name, MONO_SOLIB_EXT);
g_error ("Failed to load AOT module '%s' ('%s') in aot-only mode.\n", aot_name, assembly->image->name);
g_free (aot_name);
}
#endif
return;
}
}
if (!info) {
find_symbol (sofile, globals, "mono_aot_version", (gpointer *) &version_symbol);
find_symbol (sofile, globals, "mono_aot_file_info", (gpointer*)&info);
}
// Copy aotid to MonoImage
memcpy(&assembly->image->aotid, info->aotid, 16);
if (version_symbol) {
/* Old file format */
version = atoi (version_symbol);
} else {
g_assert (info);
version = info->version;
}
if (version != MONO_AOT_FILE_VERSION) {
msg = g_strdup_printf ("wrong file format version (expected %d got %d)", MONO_AOT_FILE_VERSION, version);
usable = FALSE;
} else {
guint8 *blob;
void *handle;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
aot_data = open_aot_data (assembly, info, &handle);
blob = aot_data + info->table_offsets [MONO_AOT_TABLE_BLOB];
} else {
blob = (guint8 *)info->blob;
}
usable = check_usable (assembly, info, blob, &msg);
}
if (!usable) {
if (mono_aot_only) {
g_error ("Failed to load AOT module '%s' while running in aot-only mode: %s.\n", found_aot_name, msg);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: module %s is unusable: %s.", found_aot_name, msg);
}
g_free (msg);
g_free (found_aot_name);
if (sofile)
mono_dl_close (sofile);
assembly->image->aot_module = NULL;
return;
}
/* Sanity check */
align_double = MONO_ABI_ALIGNOF (double);
align_int64 = MONO_ABI_ALIGNOF (gint64);
int card_table_shift_bits = 0;
gpointer card_table_mask = NULL;
mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
g_assert (info->double_align == align_double);
g_assert (info->long_align == align_int64);
g_assert (info->generic_tramp_num == MONO_TRAMPOLINE_NUM);
g_assert (info->card_table_shift_bits == card_table_shift_bits);
g_assert (info->card_table_mask == GPOINTER_TO_UINT (card_table_mask));
amodule = g_new0 (MonoAotModule, 1);
amodule->aot_name = found_aot_name;
amodule->assembly = assembly;
memcpy (&amodule->info, info, sizeof (*info));
amodule->got = (void **)amodule->info.jit_got;
/*
* The llvm code keeps its data in separate scalar variables, so this just used by this module.
*/
amodule->llvm_got = g_malloc0 (sizeof (gpointer) * amodule->info.llvm_got_size);
amodule->globals = globals;
amodule->sofile = sofile;
amodule->method_to_code = g_hash_table_new (mono_aligned_addr_hash, NULL);
amodule->extra_methods = g_hash_table_new (NULL, NULL);
amodule->shared_got = g_new0 (gpointer, info->nshared_got_entries);
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
amodule->tables [i] = aot_data + info->table_offsets [i];
}
mono_os_mutex_init_recursive (&amodule->mutex);
/* Read image table */
{
guint32 table_len, i;
char *table = NULL;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA)
table = (char *)amodule->tables [MONO_AOT_TABLE_IMAGE_TABLE];
else
table = (char *)info->image_table;
g_assert (table);
table_len = *(guint32*)table;
table += sizeof (guint32);
amodule->image_table = g_new0 (MonoImage*, table_len);
amodule->image_names = g_new0 (MonoAssemblyName, table_len);
amodule->image_guids = g_new0 (char*, table_len);
amodule->image_table_len = table_len;
for (i = 0; i < table_len; ++i) {
MonoAssemblyName *aname = &(amodule->image_names [i]);
aname->name = g_strdup (table);
table += strlen (table) + 1;
amodule->image_guids [i] = g_strdup (table);
table += strlen (table) + 1;
if (table [0] != 0)
aname->culture = g_strdup (table);
table += strlen (table) + 1;
memcpy (aname->public_key_token, table, strlen (table) + 1);
table += strlen (table) + 1;
table = (char *)ALIGN_PTR_TO (table, 8);
aname->flags = *(guint32*)table;
table += 4;
aname->major = *(guint32*)table;
table += 4;
aname->minor = *(guint32*)table;
table += 4;
aname->build = *(guint32*)table;
table += 4;
aname->revision = *(guint32*)table;
table += 4;
}
}
amodule->jit_code_start = (guint8 *)info->jit_code_start;
amodule->jit_code_end = (guint8 *)info->jit_code_end;
if (info->flags & MONO_AOT_FILE_FLAG_SEPARATE_DATA) {
amodule->blob = (guint8*)amodule->tables [MONO_AOT_TABLE_BLOB];
amodule->method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_METHOD_INFO_OFFSETS];
amodule->ex_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EX_INFO_OFFSETS];
amodule->class_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_CLASS_INFO_OFFSETS];
amodule->class_name_table = (guint16*)amodule->tables [MONO_AOT_TABLE_CLASS_NAME];
amodule->extra_method_table = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_TABLE];
amodule->extra_method_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS];
amodule->got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_GOT_INFO_OFFSETS];
amodule->llvm_got_info_offsets = (guint32*)amodule->tables [MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS];
amodule->weak_field_indexes = (guint32*)amodule->tables [MONO_AOT_TABLE_WEAK_FIELD_INDEXES];
amodule->method_flags_table = (guint8*)amodule->tables [MONO_AOT_TABLE_METHOD_FLAGS_TABLE];
} else {
amodule->blob = (guint8*)info->blob;
amodule->method_info_offsets = (guint32 *)info->method_info_offsets;
amodule->ex_info_offsets = (guint32 *)info->ex_info_offsets;
amodule->class_info_offsets = (guint32 *)info->class_info_offsets;
amodule->class_name_table = (guint16 *)info->class_name_table;
amodule->extra_method_table = (guint32 *)info->extra_method_table;
amodule->extra_method_info_offsets = (guint32 *)info->extra_method_info_offsets;
amodule->got_info_offsets = (guint32*)info->got_info_offsets;
amodule->llvm_got_info_offsets = (guint32*)info->llvm_got_info_offsets;
amodule->weak_field_indexes = (guint32*)info->weak_field_indexes;
amodule->method_flags_table = (guint8*)info->method_flags_table;
}
amodule->unbox_trampolines = (guint32 *)info->unbox_trampolines;
amodule->unbox_trampolines_end = (guint32 *)info->unbox_trampolines_end;
amodule->unbox_trampoline_addresses = (guint32 *)info->unbox_trampoline_addresses;
amodule->unwind_info = (guint8 *)info->unwind_info;
amodule->mem_begin = (guint8*)amodule->jit_code_start;
amodule->mem_end = (guint8 *)info->mem_end;
amodule->plt = (guint8 *)info->plt;
amodule->plt_end = (guint8 *)info->plt_end;
amodule->mono_eh_frame = (guint8 *)info->mono_eh_frame;
amodule->trampolines [MONO_AOT_TRAMP_SPECIFIC] = (guint8 *)info->specific_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = (guint8 *)info->static_rgctx_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_IMT] = (guint8 *)info->imt_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = (guint8 *)info->gsharedvt_arg_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = (guint8 *)info->ftnptr_arg_trampolines;
amodule->trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = (guint8 *)info->unbox_arbitrary_trampolines;
if (mono_is_corlib_image (assembly->image) || !strcmp (assembly->aname.name, MONO_ASSEMBLY_CORLIB_NAME)) {
g_assert (!mscorlib_aot_module);
mscorlib_aot_module = amodule;
}
/* Compute method addresses */
amodule->methods = (void **)g_malloc0 (amodule->info.nmethods * sizeof (gpointer));
for (i = 0; i < amodule->info.nmethods; ++i) {
void *addr = NULL;
if (amodule->info.llvm_get_method) {
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
addr = get_method (i);
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY) {
addr = ((gpointer*)amodule->info.method_addresses) [i];
} else {
/* method_addresses () contains a table of branches, since the ios linker can update those correctly */
if (!addr && amodule->info.method_addresses) {
addr = get_call_table_entry (amodule->info.method_addresses, i, amodule->info.call_table_entry_size);
g_assert (addr);
if (addr == amodule->info.method_addresses)
addr = NULL;
else
addr = method_address_resolve ((guint8 *) addr);
}
}
if (addr == NULL)
amodule->methods [i] = GINT_TO_POINTER (-1);
else
amodule->methods [i] = addr;
}
if (make_unreadable) {
#ifndef TARGET_WIN32
guint8 *addr;
guint8 *page_start, *page_end;
int err, len;
addr = amodule->mem_begin;
g_assert (addr);
len = amodule->mem_end - amodule->mem_begin;
/* Round down in both directions to avoid modifying data which is not ours */
page_start = (guint8 *) (((gssize) (addr)) & ~ (mono_pagesize () - 1)) + mono_pagesize ();
page_end = (guint8 *) (((gssize) (addr + len)) & ~ (mono_pagesize () - 1));
if (page_end > page_start) {
err = mono_mprotect (page_start, (page_end - page_start), MONO_MMAP_NONE);
g_assert (err == 0);
}
#endif
}
/* Compute the boundaries of LLVM code */
if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
compute_llvm_code_range (amodule, &amodule->llvm_code_start, &amodule->llvm_code_end);
mono_aot_lock ();
if (amodule->jit_code_start) {
aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->jit_code_start);
aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->jit_code_end);
}
if (amodule->llvm_code_start) {
aot_code_low_addr = MIN (aot_code_low_addr, (gsize)amodule->llvm_code_start);
aot_code_high_addr = MAX (aot_code_high_addr, (gsize)amodule->llvm_code_end);
}
g_hash_table_insert (aot_modules, assembly, amodule);
mono_aot_unlock ();
init_amodule_got (amodule, TRUE);
#ifdef HOST_WASM
register_methods_in_jinfo (amodule);
#else
if (amodule->jit_code_start)
mono_jit_info_add_aot_module (assembly->image, amodule->jit_code_start, amodule->jit_code_end);
if (amodule->llvm_code_start)
mono_jit_info_add_aot_module (assembly->image, amodule->llvm_code_start, amodule->llvm_code_end);
#endif
assembly->image->aot_module = amodule;
if (mono_aot_only && !mono_llvm_only) {
char *code;
find_amodule_symbol (amodule, "specific_trampolines_page", (gpointer *)&code);
amodule->use_page_trampolines = code != NULL;
/*g_warning ("using page trampolines: %d", amodule->use_page_trampolines);*/
}
if (info->flags & MONO_AOT_FILE_FLAG_WITH_LLVM)
/* Directly called methods might make calls through the PLT */
init_plt (amodule);
/*
* Register the plt region as a single trampoline so we can unwind from this code
*/
mono_aot_tramp_info_register (
mono_tramp_info_create (
NULL,
amodule->plt,
amodule->plt_end - amodule->plt,
NULL,
mono_unwind_get_cie_program ()
),
NULL
);
/*
* Since we store methoddef and classdef tokens when referring to methods/classes in
* referenced assemblies, we depend on the exact versions of the referenced assemblies.
* MS calls this 'hard binding'. This means we have to load all referenced assemblies
* non-lazily, since we can't handle out-of-date errors later.
* The cached class info also depends on the exact assemblies.
*/
if (do_load_image) {
for (i = 0; i < amodule->image_table_len; ++i) {
ERROR_DECL (error);
load_image (amodule, i, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
if (amodule->out_of_date) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: Module %s is unusable because a dependency is out-of-date.", assembly->image->name);
if (mono_aot_only && (mono_aot_mode != MONO_AOT_MODE_LLVMONLY_INTERP))
g_error ("Failed to load AOT module '%s' while running in aot-only mode because a dependency cannot be found or it is out of date.\n", found_aot_name);
} else {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: image '%s' found.", found_aot_name);
}
}
/*
* mono_aot_register_module:
*
* This should be called by embedding code to register normal AOT modules statically linked
* into the executable.
*
* \param aot_info the value of the 'mono_aot_module_<ASSEMBLY_NAME>_info' global symbol from the AOT module.
*/
void
mono_aot_register_module (gpointer *aot_info)
{
gpointer *globals;
char *aname;
MonoAotFileInfo *info = (MonoAotFileInfo *)aot_info;
g_assert (info->version == MONO_AOT_FILE_VERSION);
if (!(info->flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) {
globals = (void **)info->globals;
g_assert (globals);
}
aname = (char *)info->assembly_name;
/* This could be called before startup */
if (aot_modules)
mono_aot_lock ();
if (!static_aot_modules)
static_aot_modules = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (static_aot_modules, aname, info);
if (info->flags & MONO_AOT_FILE_FLAG_EAGER_LOAD) {
/*
* This assembly contains shared generic instances/wrappers, etc. It needs be be loaded
* before AOT code is loaded.
*/
g_assert (!container_assm_name);
container_assm_name = aname;
}
if (aot_modules)
mono_aot_unlock ();
}
void
mono_aot_init (void)
{
mono_os_mutex_init_recursive (&aot_mutex);
mono_os_mutex_init_recursive (&aot_page_mutex);
aot_modules = g_hash_table_new (NULL, NULL);
mono_install_assembly_load_hook_v2 (load_aot_module, NULL, FALSE);
mono_counters_register ("Async JIT info size", MONO_COUNTER_INT|MONO_COUNTER_JIT, &async_jit_info_size);
char *lastaot = g_getenv ("MONO_LASTAOT");
if (lastaot) {
mono_last_aot_method = atoi (lastaot);
g_free (lastaot);
}
}
/*
* load_container_amodule:
*
* Load the container assembly and its AOT image.
*/
static void
load_container_amodule (MonoAssemblyLoadContext *alc)
{
ERROR_DECL (error);
if (!container_assm_name || container_amodule)
return;
char *local_ref = container_assm_name;
container_assm_name = NULL;
MonoImageOpenStatus status = MONO_IMAGE_OK;
MonoAssemblyOpenRequest req;
gchar *dll = g_strdup_printf ( "%s.dll", local_ref);
/*
* Don't fire managed assembly load events whose execution
* might require this module to be already loaded.
*/
mono_assembly_request_prepare_open (&req, alc);
req.request.no_managed_load_event = TRUE;
MonoAssembly *assm = mono_assembly_request_open (dll, &req, &status);
if (!assm) {
gchar *exe = g_strdup_printf ("%s.exe", local_ref);
assm = mono_assembly_request_open (exe, &req, &status);
}
g_assert (assm);
load_aot_module (alc, assm, NULL, error);
container_amodule = assm->image->aot_module;
}
static gboolean
decode_cached_class_info (MonoAotModule *module, MonoCachedClassInfo *info, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
guint32 flags;
MethodRef ref;
gboolean res;
info->vtable_size = decode_value (buf, &buf);
if (info->vtable_size == -1)
/* Generic type */
return FALSE;
flags = decode_value (buf, &buf);
info->ghcimpl = (flags >> 0) & 0x1;
info->has_finalize = (flags >> 1) & 0x1;
info->has_cctor = (flags >> 2) & 0x1;
info->has_nested_classes = (flags >> 3) & 0x1;
info->blittable = (flags >> 4) & 0x1;
info->has_references = (flags >> 5) & 0x1;
info->has_static_refs = (flags >> 6) & 0x1;
info->no_special_static_fields = (flags >> 7) & 0x1;
info->is_generic_container = (flags >> 8) & 0x1;
info->has_weak_fields = (flags >> 9) & 0x1;
if (info->has_cctor) {
res = decode_method_ref (module, &ref, buf, &buf, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
return FALSE;
info->cctor_token = ref.token;
}
if (info->has_finalize) {
res = decode_method_ref (module, &ref, buf, &buf, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
return FALSE;
info->finalize_image = ref.image;
info->finalize_token = ref.token;
}
info->instance_size = decode_value (buf, &buf);
info->class_size = decode_value (buf, &buf);
info->packing_size = decode_value (buf, &buf);
info->min_align = decode_value (buf, &buf);
*endbuf = buf;
return TRUE;
}
gpointer
mono_aot_get_method_from_vt_slot (MonoVTable *vtable, int slot, MonoError *error)
{
int i;
MonoClass *klass = vtable->klass;
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *info, *p;
MonoCachedClassInfo class_info;
gboolean err;
MethodRef ref;
gboolean res;
gpointer addr;
ERROR_DECL (inner_error);
error_init (error);
if (MONO_CLASS_IS_INTERFACE_INTERNAL (klass) || m_class_get_rank (klass) || !amodule)
return NULL;
info = &amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
p = info;
err = decode_cached_class_info (amodule, &class_info, p, &p);
if (!err)
return NULL;
for (i = 0; i < slot; ++i) {
decode_method_ref (amodule, &ref, p, &p, inner_error);
mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
}
res = decode_method_ref (amodule, &ref, p, &p, inner_error);
mono_error_cleanup (inner_error); /* FIXME don't swallow the error */
if (!res)
return NULL;
if (ref.no_aot_trampoline)
return NULL;
if (mono_metadata_token_index (ref.token) == 0 || mono_metadata_token_table (ref.token) != MONO_TABLE_METHOD)
return NULL;
addr = mono_aot_get_method_from_token (ref.image, ref.token, error);
return addr;
}
gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *p;
gboolean err;
if (m_class_get_rank (klass) || !m_class_get_type_token (klass) || !amodule)
return FALSE;
p = (guint8*)&amodule->blob [mono_aot_get_offset (amodule->class_info_offsets, mono_metadata_token_index (m_class_get_type_token (klass)) - 1)];
err = decode_cached_class_info (amodule, res, p, &p);
if (!err)
return FALSE;
return TRUE;
}
/**
* mono_aot_get_class_from_name:
*
* Obtains a MonoClass with a given namespace and a given name which is located in IMAGE,
* using a cache stored in the AOT file.
* Stores the resulting class in *KLASS if found, stores NULL otherwise.
*
* Returns: TRUE if the klass was found/not found in the cache, FALSE if no aot file was
* found.
*/
gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
MonoAotModule *amodule = image->aot_module;
guint16 *table, *entry;
guint16 table_size;
guint32 hash;
char full_name_buf [1024];
char *full_name;
const char *name2, *name_space2;
MonoTableInfo *t;
guint32 cols [MONO_TYPEDEF_SIZE];
GHashTable *nspace_table;
if (!amodule || !amodule->class_name_table)
return FALSE;
amodule_lock (amodule);
*klass = NULL;
/* First look in the cache */
if (!amodule->name_cache)
amodule->name_cache = g_hash_table_new (g_str_hash, g_str_equal);
nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
if (nspace_table) {
*klass = (MonoClass *)g_hash_table_lookup (nspace_table, name);
if (*klass) {
amodule_unlock (amodule);
return TRUE;
}
}
table_size = amodule->class_name_table [0];
table = amodule->class_name_table + 1;
if (name_space [0] == '\0')
full_name = g_strdup_printf ("%s", name);
else {
if (strlen (name_space) + strlen (name) < 1000) {
sprintf (full_name_buf, "%s.%s", name_space, name);
full_name = full_name_buf;
} else {
full_name = g_strdup_printf ("%s.%s", name_space, name);
}
}
hash = mono_metadata_str_hash (full_name) % table_size;
if (full_name != full_name_buf)
g_free (full_name);
entry = &table [hash * 2];
if (entry [0] != 0) {
t = &image->tables [MONO_TABLE_TYPEDEF];
while (TRUE) {
guint32 index = entry [0];
guint32 next = entry [1];
guint32 token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, index);
name_table_accesses ++;
mono_metadata_decode_row (t, index - 1, cols, MONO_TYPEDEF_SIZE);
name2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAME]);
name_space2 = mono_metadata_string_heap (image, cols [MONO_TYPEDEF_NAMESPACE]);
if (!strcmp (name, name2) && !strcmp (name_space, name_space2)) {
ERROR_DECL (error);
amodule_unlock (amodule);
*klass = mono_class_get_checked (image, token, error);
if (!is_ok (error))
mono_error_cleanup (error); /* FIXME don't swallow the error */
/* Add to cache */
if (*klass) {
amodule_lock (amodule);
nspace_table = (GHashTable *)g_hash_table_lookup (amodule->name_cache, name_space);
if (!nspace_table) {
nspace_table = g_hash_table_new (g_str_hash, g_str_equal);
g_hash_table_insert (amodule->name_cache, (char*)name_space2, nspace_table);
}
g_hash_table_insert (nspace_table, (char*)name2, *klass);
amodule_unlock (amodule);
}
return TRUE;
}
if (next != 0) {
entry = &table [next * 2];
} else {
break;
}
}
}
amodule_unlock (amodule);
return TRUE;
}
GHashTable *
mono_aot_get_weak_field_indexes (MonoImage *image)
{
MonoAotModule *amodule = image->aot_module;
if (!amodule)
return NULL;
#if ENABLE_WEAK_ATTR
/* Initialize weak field indexes from the cached copy */
guint32 *indexes = (guint32*)amodule->weak_field_indexes;
int len = indexes [0];
GHashTable *indexes_hash = g_hash_table_new (NULL, NULL);
for (int i = 0; i < len; ++i)
g_hash_table_insert (indexes_hash, GUINT_TO_POINTER (indexes [i + 1]), GUINT_TO_POINTER (1));
return indexes_hash;
#else
g_assert_not_reached ();
#endif
}
/* Compute the boundaries of the LLVM code for AMODULE. */
static void
compute_llvm_code_range (MonoAotModule *amodule, guint8 **code_start, guint8 **code_end)
{
guint8 *p;
int version, fde_count;
gint32 *table;
if (amodule->info.llvm_get_method) {
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
#ifdef HOST_WASM
gsize min = 1 << 30, max = 0;
//gsize prev = 0;
// FIXME: This depends on emscripten allocating ftnptr ids sequentially
for (int i = 0; i < amodule->info.nmethods; ++i) {
void *addr = NULL;
addr = get_method (i);
gsize val = (gsize)addr;
if (val) {
//g_assert (val > prev);
if (val < min)
min = val;
else if (val > max)
max = val;
//prev = val;
}
}
if (max) {
*code_start = (guint8*)min;
*code_end = (guint8*)(max + 1);
} else {
*code_start = NULL;
*code_end = NULL;
}
#else
*code_start = (guint8 *)get_method (-1);
*code_end = (guint8 *)get_method (-2);
g_assert (*code_end > *code_start);
#endif
return;
}
g_assert (amodule->mono_eh_frame);
p = amodule->mono_eh_frame;
/* p points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
/* Header */
version = *p;
g_assert (version == 3);
p ++;
p ++;
p = (guint8 *)ALIGN_PTR_TO (p, 4);
fde_count = *(guint32*)p;
p += 4;
table = (gint32*)p;
if (fde_count > 0) {
*code_start = (guint8 *)amodule->methods [table [0]];
*code_end = (guint8*)amodule->methods [table [(fde_count - 1) * 2]] + table [fde_count * 2];
} else {
*code_start = NULL;
*code_end = NULL;
}
}
static gboolean
is_llvm_code (MonoAotModule *amodule, guint8 *code)
{
#if HOST_WASM
return TRUE;
#else
if ((guint8*)code >= amodule->llvm_code_start && (guint8*)code < amodule->llvm_code_end)
return TRUE;
else
return FALSE;
#endif
}
static gboolean
is_thumb_code (MonoAotModule *amodule, guint8 *code)
{
if (is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_THUMB))
return TRUE;
else
return FALSE;
}
/*
* decode_llvm_mono_eh_frame:
*
* Decode the EH information emitted by our modified LLVM compiler and construct a
* MonoJitInfo structure from it.
* If JINFO is NULL, set OUT_LLVM_CLAUSES to the number of llvm level clauses.
* This function is async safe when called in async context.
*/
static void
decode_llvm_mono_eh_frame (MonoAotModule *amodule, MonoJitInfo *jinfo,
guint8 *code, guint32 code_len,
MonoJitExceptionInfo *clauses, int num_clauses,
GSList **nesting,
int *this_reg, int *this_offset, int *out_llvm_clauses)
{
guint8 *p, *code1, *code2;
guint8 *fde, *cie, *code_start, *code_end;
int version, fde_count;
gint32 *table;
int i, pos, left, right;
MonoJitExceptionInfo *ei;
MonoMemoryManager *mem_manager;
guint32 fde_len, ei_len, nested_len, nindex;
gpointer *type_info;
MonoLLVMFDEInfo info;
guint8 *unw_info;
gboolean async;
mem_manager = m_image_get_mem_manager (amodule->assembly->image);
async = mono_thread_info_is_async_context ();
if (!amodule->mono_eh_frame) {
if (!jinfo) {
*out_llvm_clauses = num_clauses;
return;
}
memcpy (jinfo->clauses, clauses, num_clauses * sizeof (MonoJitExceptionInfo));
return;
}
g_assert (amodule->mono_eh_frame && code);
p = amodule->mono_eh_frame;
/* p points to data emitted by LLVM in DwarfMonoException::EmitMonoEHFrame () */
/* Header */
version = *p;
g_assert (version == 3);
p ++;
/* func_encoding = *p; */
p ++;
p = (guint8 *)ALIGN_PTR_TO (p, 4);
fde_count = *(guint32*)p;
p += 4;
table = (gint32*)p;
/* There is +1 entry in the table */
cie = p + ((fde_count + 1) * 8);
/* Binary search in the table to find the entry for code */
left = 0;
right = fde_count;
while (TRUE) {
pos = (left + right) / 2;
/* The table contains method index/fde offset pairs */
g_assert (table [(pos * 2)] != -1);
code1 = (guint8 *)amodule->methods [table [(pos * 2)]];
if (pos + 1 == fde_count) {
code2 = amodule->llvm_code_end;
} else {
g_assert (table [(pos + 1) * 2] != -1);
code2 = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
}
if (code < code1)
right = pos;
else if (code >= code2)
left = pos + 1;
else
break;
}
code_start = (guint8 *)amodule->methods [table [(pos * 2)]];
if (pos + 1 == fde_count) {
/* The +1 entry in the table contains the length of the last method */
int len = table [(pos + 1) * 2];
code_end = code_start + len;
} else {
code_end = (guint8 *)amodule->methods [table [(pos + 1) * 2]];
}
if (!code_len)
code_len = code_end - code_start;
g_assert (code >= code_start && code < code_end);
if (is_thumb_code (amodule, code_start))
/* Clear thumb flag */
code_start = (guint8*)(((gsize)code_start) & ~1);
fde = amodule->mono_eh_frame + table [(pos * 2) + 1];
/* This won't overflow because there is +1 entry in the table */
fde_len = table [(pos * 2) + 2 + 1] - table [(pos * 2) + 1];
/* Compute lengths */
mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, NULL, NULL, NULL);
if (async) {
/* These are leaked, but the leak is bounded */
ei = mono_mem_manager_alloc0_lock_free (mem_manager, info.ex_info_len * sizeof (MonoJitExceptionInfo));
type_info = mono_mem_manager_alloc0_lock_free (mem_manager, info.ex_info_len * sizeof (gpointer));
unw_info = mono_mem_manager_alloc0_lock_free (mem_manager, info.unw_info_len);
} else {
ei = (MonoJitExceptionInfo *)g_malloc0 (info.ex_info_len * sizeof (MonoJitExceptionInfo));
type_info = (gpointer *)g_malloc0 (info.ex_info_len * sizeof (gpointer));
unw_info = (guint8*)g_malloc0 (info.unw_info_len);
}
mono_unwind_decode_llvm_mono_fde (fde, fde_len, cie, code_start, &info, ei, type_info, unw_info);
ei_len = info.ex_info_len;
*this_reg = info.this_reg;
*this_offset = info.this_offset;
/*
* LLVM might represent one IL region with multiple regions.
*/
/* Count number of nested clauses */
nested_len = 0;
for (i = 0; i < ei_len; ++i) {
/* This might be unaligned */
gint32 cindex1 = read32 (type_info [i]);
GSList *l;
for (l = nesting [cindex1]; l; l = l->next)
nested_len ++;
}
if (!jinfo) {
*out_llvm_clauses = ei_len + nested_len;
return;
}
/* Store the unwind info addr/length in the MonoJitInfo structure itself so its async safe */
MonoUnwindJitInfo *jinfo_unwind = mono_jit_info_get_unwind_info (jinfo);
g_assert (jinfo_unwind);
jinfo_unwind->unw_info = unw_info;
jinfo_unwind->unw_info_len = info.unw_info_len;
for (i = 0; i < ei_len; ++i) {
/*
* clauses contains the original IL exception info saved by the AOT
* compiler, we have to combine that with the information produced by LLVM
*/
/* The type_info entries contain IL clause indexes */
int clause_index = read32 (type_info [i]);
MonoJitExceptionInfo *jei = &jinfo->clauses [i];
MonoJitExceptionInfo *orig_jei = &clauses [clause_index];
g_assert (clause_index < num_clauses);
jei->flags = orig_jei->flags;
jei->data.catch_class = orig_jei->data.catch_class;
jei->try_start = ei [i].try_start;
jei->try_end = ei [i].try_end;
jei->handler_start = ei [i].handler_start;
jei->clause_index = clause_index;
if (is_thumb_code (amodule, (guint8 *)jei->try_start)) {
jei->try_start = (void*)((gsize)jei->try_start & ~1);
jei->try_end = (void*)((gsize)jei->try_end & ~1);
/* Make sure we transition to thumb when a handler starts */
jei->handler_start = (void*)((gsize)jei->handler_start + 1);
}
}
/* See exception_cb () in mini-llvm.c as to why this is needed */
nindex = ei_len;
for (i = 0; i < ei_len; ++i) {
gint32 cindex1 = read32 (type_info [i]);
GSList *l;
for (l = nesting [cindex1]; l; l = l->next) {
gint32 nesting_cindex = GPOINTER_TO_INT (l->data);
MonoJitExceptionInfo *nesting_ei;
MonoJitExceptionInfo *nesting_clause = &clauses [nesting_cindex];
nesting_ei = &jinfo->clauses [nindex];
nindex ++;
memcpy (nesting_ei, &jinfo->clauses [i], sizeof (MonoJitExceptionInfo));
nesting_ei->flags = nesting_clause->flags;
nesting_ei->data.catch_class = nesting_clause->data.catch_class;
nesting_ei->clause_index = nesting_cindex;
}
}
g_assert (nindex == ei_len + nested_len);
}
static gpointer
alloc0_jit_info_data (MonoMemoryManager *mem_manager, int size, gboolean async_context)
#define alloc0_jit_info_data(mem_manager, size, async_context) (g_cast (alloc0_jit_info_data ((mem_manager), (size), (async_context))))
{
gpointer res;
if (async_context) {
res = mono_mem_manager_alloc0_lock_free (mem_manager, size);
mono_atomic_fetch_add_i32 (&async_jit_info_size, size);
} else {
res = mono_mem_manager_alloc0 (mem_manager, size);
}
return res;
}
/*
* In async context, this is async safe.
*/
static MonoJitInfo*
decode_exception_debug_info (MonoAotModule *amodule,
MonoMethod *method, guint8* ex_info,
guint8 *code, guint32 code_len)
{
ERROR_DECL (error);
int i, buf_len, num_clauses, len;
MonoJitInfo *jinfo;
MonoJitInfoFlags flags = JIT_INFO_NONE;
guint unwind_info, eflags;
gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes, has_arch_eh_jit_info;
gboolean from_llvm, has_gc_map;
guint8 *p;
int try_holes_info_size, num_holes;
int this_reg = 0, this_offset = 0;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (amodule->assembly->image);
gboolean async;
code = (guint8*)MINI_FTNPTR_TO_ADDR (code);
/* Load the method info from the AOT file */
async = mono_thread_info_is_async_context ();
p = ex_info;
eflags = decode_value (p, &p);
has_generic_jit_info = (eflags & 1) != 0;
has_dwarf_unwind_info = (eflags & 2) != 0;
has_clauses = (eflags & 4) != 0;
has_seq_points = (eflags & 8) != 0;
from_llvm = (eflags & 16) != 0;
has_try_block_holes = (eflags & 32) != 0;
has_gc_map = (eflags & 64) != 0;
has_arch_eh_jit_info = (eflags & 128) != 0;
if (has_dwarf_unwind_info) {
unwind_info = decode_value (p, &p);
g_assert (unwind_info < (1 << 30));
} else {
unwind_info = decode_value (p, &p);
}
if (has_generic_jit_info)
flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
if (has_try_block_holes) {
num_holes = decode_value (p, &p);
flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
} else {
num_holes = try_holes_info_size = 0;
}
if (has_arch_eh_jit_info) {
flags |= JIT_INFO_HAS_ARCH_EH_INFO;
/* Overwrite the original code_len which includes alignment padding */
code_len = decode_value (p, &p);
}
/* Exception table */
if (has_clauses)
num_clauses = decode_value (p, &p);
else
num_clauses = 0;
if (from_llvm) {
MonoJitExceptionInfo *clauses;
GSList **nesting;
/*
* Part of the info is encoded by the AOT compiler, the rest is in the .eh_frame
* section.
*/
if (async) {
if (num_clauses < 16) {
clauses = g_newa (MonoJitExceptionInfo, num_clauses);
nesting = g_newa (GSList*, num_clauses);
} else {
clauses = alloc0_jit_info_data (mem_manager, sizeof (MonoJitExceptionInfo) * num_clauses, TRUE);
nesting = alloc0_jit_info_data (mem_manager, sizeof (GSList*) * num_clauses, TRUE);
}
memset (clauses, 0, sizeof (MonoJitExceptionInfo) * num_clauses);
memset (nesting, 0, sizeof (GSList*) * num_clauses);
} else {
clauses = g_new0 (MonoJitExceptionInfo, num_clauses);
nesting = g_new0 (GSList*, num_clauses);
}
for (i = 0; i < num_clauses; ++i) {
MonoJitExceptionInfo *ei = &clauses [i];
ei->flags = decode_value (p, &p);
if (!(ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
int len = decode_value (p, &p);
if (len > 0) {
if (async) {
p += len;
} else {
ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
}
ei->clause_index = i;
ei->try_offset = decode_value (p, &p);
ei->try_len = decode_value (p, &p);
ei->handler_offset = decode_value (p, &p);
ei->handler_len = decode_value (p, &p);
/* Read the list of nesting clauses */
while (TRUE) {
int nesting_index = decode_value (p, &p);
if (nesting_index == -1)
break;
// FIXME: async
g_assert (!async);
nesting [i] = g_slist_prepend (nesting [i], GINT_TO_POINTER (nesting_index));
}
}
flags |= JIT_INFO_HAS_UNWIND_INFO;
int num_llvm_clauses;
/* Get the length first */
decode_llvm_mono_eh_frame (amodule, NULL, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, &num_llvm_clauses);
len = mono_jit_info_size (flags, num_llvm_clauses, num_holes);
jinfo = (MonoJitInfo *)alloc0_jit_info_data (mem_manager, len, async);
mono_jit_info_init (jinfo, method, code, code_len, flags, num_llvm_clauses, num_holes);
decode_llvm_mono_eh_frame (amodule, jinfo, code, code_len, clauses, num_clauses, nesting, &this_reg, &this_offset, NULL);
if (!async) {
g_free (clauses);
for (i = 0; i < num_clauses; ++i)
g_slist_free (nesting [i]);
g_free (nesting);
}
jinfo->from_llvm = 1;
} else {
len = mono_jit_info_size (flags, num_clauses, num_holes);
jinfo = (MonoJitInfo *)alloc0_jit_info_data (mem_manager, len, async);
/* The jit info table needs to sort addresses so it contains non-authenticated pointers on arm64e */
mono_jit_info_init (jinfo, method, code, code_len, flags, num_clauses, num_holes);
for (i = 0; i < jinfo->num_clauses; ++i) {
MonoJitExceptionInfo *ei = &jinfo->clauses [i];
ei->flags = decode_value (p, &p);
#ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
/* Not used for catch clauses */
if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
ei->exvar_offset = decode_value (p, &p);
#else
ei->exvar_offset = decode_value (p, &p);
#endif
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
ei->data.filter = code + decode_value (p, &p);
} else {
int len = decode_value (p, &p);
if (len > 0) {
if (async) {
p += len;
} else {
ei->data.catch_class = decode_klass_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
}
}
ei->try_start = code + decode_value (p, &p);
ei->try_end = code + decode_value (p, &p);
ei->handler_start = code + decode_value (p, &p);
/* Keep try_start/end non-authenticated, they are never branched to */
//ei->try_start = MINI_ADDR_TO_FTNPTR (ei->try_start);
//ei->try_end = MINI_ADDR_TO_FTNPTR (ei->try_end);
ei->handler_start = MINI_ADDR_TO_FTNPTR (ei->handler_start);
if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ei->data.filter = MINI_ADDR_TO_FTNPTR (ei->data.filter);
else if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
ei->data.handler_end = MINI_ADDR_TO_FTNPTR (ei->data.handler_end);
}
jinfo->unwind_info = unwind_info;
jinfo->from_aot = 1;
}
if (has_try_block_holes) {
MonoTryBlockHoleTableJitInfo *table;
g_assert (jinfo->has_try_block_holes);
table = mono_jit_info_get_try_block_hole_table_info (jinfo);
g_assert (table);
table->num_holes = (guint16)num_holes;
for (i = 0; i < num_holes; ++i) {
MonoTryBlockHoleJitInfo *hole = &table->holes [i];
hole->clause = decode_value (p, &p);
hole->length = decode_value (p, &p);
hole->offset = decode_value (p, &p);
}
}
if (has_arch_eh_jit_info) {
MonoArchEHJitInfo *eh_info;
g_assert (jinfo->has_arch_eh_info);
eh_info = mono_jit_info_get_arch_eh_info (jinfo);
eh_info->stack_size = decode_value (p, &p);
eh_info->epilog_size = decode_value (p, &p);
}
if (async) {
/* The rest is not needed in async mode */
jinfo->async = TRUE;
jinfo->d.aot_info = amodule;
// FIXME: Cache
return jinfo;
}
if (has_generic_jit_info) {
MonoGenericJitInfo *gi;
int len;
g_assert (jinfo->has_generic_jit_info);
gi = mono_jit_info_get_generic_jit_info (jinfo);
g_assert (gi);
gi->nlocs = decode_value (p, &p);
if (gi->nlocs) {
gi->locations = (MonoDwarfLocListEntry *)alloc0_jit_info_data (mem_manager, gi->nlocs * sizeof (MonoDwarfLocListEntry), async);
for (i = 0; i < gi->nlocs; ++i) {
MonoDwarfLocListEntry *entry = &gi->locations [i];
entry->is_reg = decode_value (p, &p);
entry->reg = decode_value (p, &p);
if (!entry->is_reg)
entry->offset = decode_value (p, &p);
if (i > 0)
entry->from = decode_value (p, &p);
entry->to = decode_value (p, &p);
}
gi->has_this = 1;
} else {
if (from_llvm) {
gi->has_this = this_reg != -1;
gi->this_reg = this_reg;
gi->this_offset = this_offset;
} else {
gi->has_this = decode_value (p, &p);
gi->this_reg = decode_value (p, &p);
gi->this_offset = decode_value (p, &p);
}
}
len = decode_value (p, &p);
if (async) {
p += len;
} else {
jinfo->d.method = decode_resolve_method_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
gi->generic_sharing_context = alloc0_jit_info_data (mem_manager, sizeof (MonoGenericSharingContext), async);
if (decode_value (p, &p)) {
/* gsharedvt */
MonoGenericSharingContext *gsctx = gi->generic_sharing_context;
gsctx->is_gsharedvt = TRUE;
}
}
if (method && has_seq_points) {
MonoSeqPointInfo *seq_points;
p += mono_seq_point_info_read (&seq_points, p, FALSE);
if (!async) {
// FIXME: Call a function in seq-points.c
// FIXME:
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
/* This could be set already since this function can be called more than once for the same method */
if (!g_hash_table_lookup (jit_mm->seq_points, method))
g_hash_table_insert (jit_mm->seq_points, method, seq_points);
else
mono_seq_point_info_free (seq_points);
jit_mm_unlock (jit_mm);
}
jinfo->seq_points = seq_points;
}
/* Load debug info */
buf_len = decode_value (p, &p);
if (!async)
mono_debug_add_aot_method (method, code, p, buf_len);
p += buf_len;
if (has_gc_map) {
int map_size = decode_value (p, &p);
/* The GC map requires 4 bytes of alignment */
while ((guint64)(gsize)p % 4)
p ++;
jinfo->gc_info = p;
p += map_size;
}
if (amodule != m_class_get_image (jinfo->d.method->klass)->aot_module && !async) {
mono_aot_lock ();
if (!ji_to_amodule)
ji_to_amodule = g_hash_table_new (NULL, NULL);
g_hash_table_insert (ji_to_amodule, jinfo, amodule);
mono_aot_unlock ();
}
return jinfo;
}
static gboolean
amodule_contains_code_addr (MonoAotModule *amodule, guint8 *code)
{
return (code >= amodule->jit_code_start && code <= amodule->jit_code_end) ||
(code >= amodule->llvm_code_start && code <= amodule->llvm_code_end);
}
/*
* mono_aot_get_unwind_info:
*
* Return a pointer to the DWARF unwind info belonging to JI.
*/
guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
MonoAotModule *amodule;
guint8 *p;
guint8 *code = (guint8 *)ji->code_start;
if (ji->async)
amodule = ji->d.aot_info;
else
amodule = m_class_get_image (jinfo_get_method (ji)->klass)->aot_module;
g_assert (amodule);
g_assert (ji->from_aot);
if (!amodule_contains_code_addr (amodule, code)) {
/* ji belongs to a different aot module than amodule */
mono_aot_lock ();
g_assert (ji_to_amodule);
amodule = (MonoAotModule *)g_hash_table_lookup (ji_to_amodule, ji);
g_assert (amodule);
g_assert (amodule_contains_code_addr (amodule, code));
mono_aot_unlock ();
}
p = amodule->unwind_info + ji->unwind_info;
*unwind_info_len = decode_value (p, &p);
return p;
}
static void
msort_method_addresses_internal (gpointer *array, int *indexes, int lo, int hi, gpointer *scratch, int *scratch_indexes)
{
int mid = (lo + hi) / 2;
int i, t_lo, t_hi;
if (lo >= hi)
return;
if (hi - lo < 32) {
for (i = lo; i < hi; ++i)
if (array [i] > array [i + 1])
break;
if (i == hi)
/* Already sorted */
return;
}
msort_method_addresses_internal (array, indexes, lo, mid, scratch, scratch_indexes);
msort_method_addresses_internal (array, indexes, mid + 1, hi, scratch, scratch_indexes);
if (array [mid] < array [mid + 1])
return;
/* Merge */
t_lo = lo;
t_hi = mid + 1;
for (i = lo; i <= hi; i ++) {
if (t_lo <= mid && ((t_hi > hi) || array [t_lo] < array [t_hi])) {
scratch [i] = array [t_lo];
scratch_indexes [i] = indexes [t_lo];
t_lo ++;
} else {
scratch [i] = array [t_hi];
scratch_indexes [i] = indexes [t_hi];
t_hi ++;
}
}
for (i = lo; i <= hi; ++i) {
array [i] = scratch [i];
indexes [i] = scratch_indexes [i];
}
}
static void
msort_method_addresses (gpointer *array, int *indexes, int len)
{
gpointer *scratch;
int *scratch_indexes;
scratch = g_new (gpointer, len);
scratch_indexes = g_new (int, len);
msort_method_addresses_internal (array, indexes, 0, len - 1, scratch, scratch_indexes);
g_free (scratch);
g_free (scratch_indexes);
}
static void
sort_methods (MonoAotModule *amodule)
{
int nmethods = amodule->info.nmethods;
/* Compute a sorted table mapping code to method indexes. */
if (amodule->sorted_methods)
return;
// FIXME: async
gpointer *methods = g_new0 (gpointer, nmethods);
int *method_indexes = g_new0 (int, nmethods);
int methods_len = 0;
for (int i = 0; i < nmethods; ++i) {
/* Skip the -1 entries to speed up sorting */
if (amodule->methods [i] == GINT_TO_POINTER (-1))
continue;
methods [methods_len] = amodule->methods [i];
method_indexes [methods_len] = i;
methods_len ++;
}
/* Use a merge sort as this is mostly sorted */
msort_method_addresses (methods, method_indexes, methods_len);
for (int i = 0; i < methods_len -1; ++i)
g_assert (methods [i] <= methods [i + 1]);
amodule->sorted_methods_len = methods_len;
if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_methods, methods, NULL) != NULL)
/* Somebody got in before us */
g_free (methods);
if (mono_atomic_cas_ptr ((gpointer*)&amodule->sorted_method_indexes, method_indexes, NULL) != NULL)
/* Somebody got in before us */
g_free (method_indexes);
}
/*
* mono_aot_find_jit_info:
*
* In async context, the resulting MonoJitInfo will not have its method field set, and it will not be added
* to the jit info tables.
* FIXME: Large sizes in the lock free allocator
*/
MonoJitInfo *
mono_aot_find_jit_info (MonoImage *image, gpointer addr)
{
ERROR_DECL (error);
int pos, left, right, code_len;
int method_index, table_len;
guint32 token;
MonoAotModule *amodule = image->aot_module;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (image);
MonoMethod *method = NULL;
MonoJitInfo *jinfo;
guint8 *code, *ex_info, *p;
guint32 *table;
gpointer *methods;
guint8 *code1, *code2;
int methods_len;
gboolean async;
if (!amodule)
return NULL;
addr = MINI_FTNPTR_TO_ADDR (addr);
if (!amodule_contains_code_addr (amodule, (guint8 *)addr))
return NULL;
async = mono_thread_info_is_async_context ();
sort_methods (amodule);
/* Binary search in the sorted_methods table */
methods = amodule->sorted_methods;
methods_len = amodule->sorted_methods_len;
code = (guint8 *)addr;
left = 0;
right = methods_len;
while (TRUE) {
pos = (left + right) / 2;
code1 = (guint8 *)methods [pos];
if (pos + 1 == methods_len) {
#ifdef HOST_WASM
code2 = code1 + 1;
#else
if (code1 >= amodule->jit_code_start && code1 < amodule->jit_code_end)
code2 = amodule->jit_code_end;
else
code2 = amodule->llvm_code_end;
#endif
} else {
code2 = (guint8 *)methods [pos + 1];
}
if (code < code1)
right = pos;
else if (code >= code2)
left = pos + 1;
else
break;
}
#ifdef HOST_WASM
if (addr != methods [pos])
return NULL;
#endif
g_assert (addr >= methods [pos]);
if (pos + 1 < methods_len)
g_assert (addr < methods [pos + 1]);
method_index = amodule->sorted_method_indexes [pos];
/* In async mode, jinfo is not added to the normal jit info table, so have to cache it ourselves */
if (async) {
JitInfoMap **table = amodule->async_jit_info_table;
LOAD_ACQUIRE_FENCE;
if (table) {
int buckets = (amodule->info.nmethods / JIT_INFO_MAP_BUCKET_SIZE) + 1;
JitInfoMap *current_item = table [method_index % buckets];
LOAD_ACQUIRE_FENCE;
while (current_item) {
if (current_item->method_index == method_index)
return current_item->jinfo;
current_item = current_item->next;
LOAD_ACQUIRE_FENCE;
}
}
}
code = (guint8 *)amodule->methods [method_index];
ex_info = &amodule->blob [mono_aot_get_offset (amodule->ex_info_offsets, method_index)];
#ifdef HOST_WASM
/* WASM methods have no length, can only look up the method address */
code_len = 1;
#else
if (pos == methods_len - 1) {
if (code >= amodule->jit_code_start && code < amodule->jit_code_end)
code_len = amodule->jit_code_end - code;
else
code_len = amodule->llvm_code_end - code;
} else {
guint8* code_end = (guint8*)methods [pos + 1];
if (code >= amodule->jit_code_start && code < amodule->jit_code_end && code_end > amodule->jit_code_end) {
code_end = amodule->jit_code_end;
}
if (code >= amodule->llvm_code_start && code < amodule->llvm_code_end && code_end > amodule->llvm_code_end) {
code_end = amodule->llvm_code_end;
}
code_len = code_end - code;
}
#endif
g_assert ((guint8*)code <= (guint8*)addr && (guint8*)addr < (guint8*)code + code_len);
/* Might be a wrapper/extra method */
if (!async) {
if (amodule->extra_methods) {
amodule_lock (amodule);
method = (MonoMethod *)g_hash_table_lookup (amodule->extra_methods, GUINT_TO_POINTER (method_index));
amodule_unlock (amodule);
} else {
method = NULL;
}
if (!method) {
if (method_index >= table_info_get_rows (&image->tables [MONO_TABLE_METHOD])) {
/*
* This is hit for extra methods which are called directly, so they are
* not in amodule->extra_methods.
*/
table_len = amodule->extra_method_info_offsets [0];
table = amodule->extra_method_info_offsets + 1;
left = 0;
right = table_len;
pos = 0;
/* Binary search */
while (TRUE) {
pos = ((left + right) / 2);
g_assert (pos < table_len);
if (table [pos * 2] < method_index)
left = pos + 1;
else if (table [pos * 2] > method_index)
right = pos;
else
break;
}
p = amodule->blob + table [(pos * 2) + 1];
method = decode_resolve_method_ref (amodule, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!method)
/* Happens when a random address is passed in which matches a not-yey called wrapper encoded using its name */
return NULL;
} else {
ERROR_DECL (error);
token = mono_metadata_make_token (MONO_TABLE_METHOD, method_index + 1);
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
}
}
/* FIXME: */
g_assert (method);
}
//printf ("F: %s\n", mono_method_full_name (method, TRUE));
jinfo = decode_exception_debug_info (amodule, method, ex_info, code, code_len);
g_assert ((guint8*)addr >= (guint8*)jinfo->code_start);
if (async) {
/* Add it to the async JitInfo tables */
JitInfoMap **current_table, **new_table;
JitInfoMap *current_item, *new_item;
int buckets = (amodule->info.nmethods / JIT_INFO_MAP_BUCKET_SIZE) + 1;
for (;;) {
current_table = amodule->async_jit_info_table;
LOAD_ACQUIRE_FENCE;
if (current_table)
break;
new_table = alloc0_jit_info_data (mem_manager, buckets * sizeof (JitInfoMap*), async);
STORE_RELEASE_FENCE;
if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table, new_table, current_table) == current_table)
break;
}
new_item = alloc0_jit_info_data (mem_manager, sizeof (JitInfoMap), async);
new_item->method_index = method_index;
new_item->jinfo = jinfo;
for (;;) {
current_item = amodule->async_jit_info_table [method_index % buckets];
LOAD_ACQUIRE_FENCE;
new_item->next = current_item;
STORE_RELEASE_FENCE;
if (mono_atomic_cas_ptr ((volatile gpointer *)&amodule->async_jit_info_table [method_index % buckets], new_item, current_item) == current_item)
break;
}
} else {
/* Add it to the normal JitInfo tables */
mono_jit_info_table_add (jinfo);
}
if ((guint8*)addr >= (guint8*)jinfo->code_start + jinfo->code_size)
/* addr is in the padding between methods, see the adjustment of code_size in decode_exception_debug_info () */
return NULL;
return jinfo;
}
static gboolean
decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guint8 *buf, guint8 **endbuf)
{
ERROR_DECL (error);
guint8 *p = buf;
gpointer *table;
MonoImage *image;
int i;
MonoMemoryManager *mem_manager = m_image_get_mem_manager (aot_module->assembly->image);
switch (ji->type) {
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
MethodRef ref;
gboolean res;
res = decode_method_ref (aot_module, &ref, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
if (!res)
goto cleanup;
if (!ref.method && !mono_aot_only && !ref.no_aot_trampoline && (ji->type == MONO_PATCH_INFO_METHOD) && (mono_metadata_token_table (ref.token) == MONO_TABLE_METHOD)) {
ji->data.target = mono_create_ftnptr (mono_create_jit_trampoline_from_token (ref.image, ref.token));
ji->type = MONO_PATCH_INFO_ABS;
}
else {
if (ref.method) {
ji->data.method = ref.method;
}else {
ERROR_DECL (error);
ji->data.method = mono_get_method_checked (ref.image, ref.token, NULL, NULL, error);
if (!ji->data.method)
g_error ("AOT Runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
}
g_assert (ji->data.method);
mono_class_init_internal (ji->data.method->klass);
}
break;
}
case MONO_PATCH_INFO_LDSTR_LIT:
{
guint32 len = decode_value (p, &p);
ji->data.name = (char*)p;
p += len + 1;
break;
}
case MONO_PATCH_INFO_METHODCONST:
/* Shared */
ji->data.method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.method)
goto cleanup;
break;
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
/* Shared */
ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.klass)
goto cleanup;
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
ji->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
ji->data.del_tramp->klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.del_tramp->klass)
goto cleanup;
if (decode_value (p, &p)) {
ji->data.del_tramp->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.del_tramp->method)
goto cleanup;
}
ji->data.del_tramp->is_virtual = decode_value (p, &p) ? TRUE : FALSE;
break;
case MONO_PATCH_INFO_IMAGE:
ji->data.image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.image)
goto cleanup;
break;
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
/* Shared */
ji->data.field = decode_field_info (aot_module, p, &p);
if (!ji->data.field)
goto cleanup;
break;
case MONO_PATCH_INFO_SWITCH:
ji->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoBBTable));
ji->data.table->table_size = decode_value (p, &p);
table = (void **)mono_mem_manager_alloc (mem_manager, sizeof (gpointer) * ji->data.table->table_size);
ji->data.table->table = (MonoBasicBlock**)table;
for (i = 0; i < ji->data.table->table_size; i++)
table [i] = (gpointer)(gssize)decode_value (p, &p);
break;
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT: {
guint32 val;
ji->data.target = mono_mem_manager_alloc0 (mem_manager, sizeof (float));
val = decode_value (p, &p);
*(float*)ji->data.target = *(float*)&val;
break;
}
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT: {
guint32 val [2];
guint64 v;
// FIXME: Align to 16 bytes ?
ji->data.target = mono_mem_manager_alloc0 (mem_manager, sizeof (double));
val [0] = decode_value (p, &p);
val [1] = decode_value (p, &p);
v = ((guint64)val [1] << 32) | ((guint64)val [0]);
*(double*)ji->data.target = *(double*)&v;
break;
}
case MONO_PATCH_INFO_LDSTR:
image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!image)
goto cleanup;
ji->data.token = mono_jump_info_token_new (mp, image, MONO_TOKEN_STRING + decode_value (p, &p));
break;
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_DECLSEC:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
/* Shared */
image = load_image (aot_module, decode_value (p, &p), error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!image)
goto cleanup;
ji->data.token = mono_jump_info_token_new (mp, image, decode_value (p, &p));
ji->data.token->has_context = decode_value (p, &p);
if (ji->data.token->has_context) {
gboolean res = decode_generic_context (aot_module, &ji->data.token->context, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!res)
goto cleanup;
}
break;
case MONO_PATCH_INFO_EXC_NAME:
ji->data.klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!ji->data.klass)
goto cleanup;
ji->data.name = m_class_get_name (ji->data.klass);
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
break;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
ji->data.uindex = decode_value (p, &p);
break;
case MONO_PATCH_INFO_CASTCLASS_CACHE:
ji->data.index = decode_value (p, &p);
break;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
ji->data.jit_icall_id = (MonoJitICallId)decode_value (p, &p);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
gboolean res;
MonoJumpInfoRgctxEntry *entry;
guint32 offset, val;
guint8 *p2;
offset = decode_value (p, &p);
val = decode_value (p, &p);
entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
p2 = aot_module->blob + offset;
entry->in_mrgctx = ((val & 1) > 0) ? TRUE : FALSE;
if (entry->in_mrgctx)
entry->d.method = decode_resolve_method_ref (aot_module, p2, &p2, error);
else
entry->d.klass = decode_klass_ref (aot_module, p2, &p2, error);
entry->info_type = (MonoRgctxInfoType)((val >> 1) & 0xff);
entry->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
entry->data->type = (MonoJumpInfoType)((val >> 9) & 0xff);
mono_error_cleanup (error); /* FIXME don't swallow the error */
res = decode_patch (aot_module, mp, entry->data, p, &p);
if (!res)
goto cleanup;
ji->data.rgctx_entry = entry;
break;
}
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_AOT_MODULE:
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
break;
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
ji->data.target = decode_signature (aot_module, p, &p);
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL: {
MonoJumpInfoGSharedVtCall *info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
info->sig = decode_signature (aot_module, p, &p);
g_assert (info->sig);
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
int i;
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
info->num_entries = decode_value (p, &p);
info->count_entries = info->num_entries;
info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
for (i = 0; i < info->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
template_->info_type = (MonoRgctxInfoType)decode_value (p, &p);
switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
case MONO_PATCH_INFO_CLASS: {
MonoClass *klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!klass)
goto cleanup;
template_->data = m_class_get_byval_arg (klass);
break;
}
case MONO_PATCH_INFO_FIELD:
template_->data = decode_field_info (aot_module, p, &p);
if (!template_->data)
goto cleanup;
break;
case MONO_PATCH_INFO_METHOD:
template_->data = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
if (!template_->data)
goto cleanup;
break;
default:
g_assert_not_reached ();
break;
}
}
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
info->klass = decode_klass_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
info->method = decode_resolve_method_ref (aot_module, p, &p, error);
mono_error_assert_ok (error); /* FIXME don't swallow the error */
ji->data.target = info;
break;
}
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
break;
case MONO_PATCH_INFO_AOT_JIT_INFO:
ji->data.index = decode_value (p, &p);
break;
default:
g_error ("unhandled type %d", ji->type);
break;
}
*endbuf = p;
return TRUE;
cleanup:
return FALSE;
}
/*
* decode_patches:
*
* Decode a list of patches identified by the got offsets in GOT_OFFSETS. Return an array of
* MonoJumpInfo structures allocated from MP. GOT entries already loaded have their
* ji->type set to MONO_PATCH_INFO_NONE.
*/
static MonoJumpInfo*
decode_patches (MonoAotModule *amodule, MonoMemPool *mp, int n_patches, gboolean llvm, guint32 *got_offsets)
{
MonoJumpInfo *patches;
MonoJumpInfo *ji;
gpointer *got;
guint32 *got_info_offsets;
int i;
gboolean res;
if (llvm) {
got = amodule->llvm_got;
got_info_offsets = (guint32 *)amodule->llvm_got_info_offsets;
} else {
got = amodule->got;
got_info_offsets = (guint32 *)amodule->got_info_offsets;
}
patches = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo) * n_patches);
for (i = 0; i < n_patches; ++i) {
guint8 *p = amodule->blob + mono_aot_get_offset (got_info_offsets, got_offsets [i]);
ji = &patches [i];
ji->type = (MonoJumpInfoType)decode_value (p, &p);
/* See load_method () for SFLDA */
if (got && got [got_offsets [i]] && ji->type != MONO_PATCH_INFO_SFLDA) {
/* Already loaded */
ji->type = MONO_PATCH_INFO_NONE;
} else {
res = decode_patch (amodule, mp, ji, p, &p);
if (!res)
return NULL;
}
}
return patches;
}
static MonoJumpInfo*
load_patch_info (MonoAotModule *amodule, MonoMemPool *mp, int n_patches,
gboolean llvm, guint32 **got_slots,
guint8 *buf, guint8 **endbuf)
{
MonoJumpInfo *patches;
int pindex;
guint8 *p;
p = buf;
*got_slots = (guint32 *)g_malloc (sizeof (guint32) * n_patches);
for (pindex = 0; pindex < n_patches; ++pindex) {
(*got_slots)[pindex] = decode_value (p, &p);
}
patches = decode_patches (amodule, mp, n_patches, llvm, *got_slots);
if (!patches) {
g_free (*got_slots);
*got_slots = NULL;
return NULL;
}
*endbuf = p;
return patches;
}
static void
register_jump_target_got_slot (MonoMethod *method, gpointer *got_slot)
{
/*
* Jump addresses cannot be patched by the trampoline code since it
* does not have access to the caller's address. Instead, we collect
* the addresses of the GOT slots pointing to a method, and patch
* them after the method has been compiled.
*/
GSList *list;
MonoJitMemoryManager *jit_mm;
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
if (!jit_mm->jump_target_got_slot_hash)
jit_mm->jump_target_got_slot_hash = g_hash_table_new (NULL, NULL);
list = (GSList *)g_hash_table_lookup (jit_mm->jump_target_got_slot_hash, method);
list = g_slist_prepend (list, got_slot);
g_hash_table_insert (jit_mm->jump_target_got_slot_hash, method, list);
jit_mm_unlock (jit_mm);
}
/*
* load_method:
*
* Load the method identified by METHOD_INDEX from the AOT image. Return a
* pointer to the native code of the method, or NULL if not found.
* METHOD might not be set if the caller only has the image/token info.
*/
static gpointer
load_method (MonoAotModule *amodule, MonoImage *image, MonoMethod *method, guint32 token, int method_index,
MonoError *error)
{
MonoJitInfo *jinfo = NULL;
guint8 *code = NULL, *info;
gboolean res;
error_init (error);
init_amodule_got (amodule, FALSE);
if (amodule->out_of_date)
return NULL;
if (amodule->info.llvm_get_method) {
/*
* Obtain the method address by calling a generated function in the LLVM module.
*/
gpointer (*get_method) (int) = (gpointer (*)(int))amodule->info.llvm_get_method;
code = (guint8 *)get_method (method_index);
}
if (!code) {
if (method_index < amodule->info.nmethods)
code = (guint8*)MINI_ADDR_TO_FTNPTR ((guint8 *)amodule->methods [method_index]);
else
return NULL;
/* JITted method */
if (amodule->methods [method_index] == GINT_TO_POINTER (-1)) {
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
full_name = mono_method_full_name (method, TRUE);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: NOT FOUND: %s.", full_name);
g_free (full_name);
}
}
return NULL;
}
}
info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
if (!amodule->methods_loaded) {
amodule_lock (amodule);
if (!amodule->methods_loaded) {
guint32 *loaded;
loaded = g_new0 (guint32, amodule->info.nmethods / 32 + 1);
mono_memory_barrier ();
amodule->methods_loaded = loaded;
}
amodule_unlock (amodule);
}
if ((amodule->methods_loaded [method_index / 32] >> (method_index % 32)) & 0x1)
return code;
if (mini_debug_options.aot_skip_set && !(method && method->wrapper_type)) {
gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
methods_aot += mono_atomic_load_i32 (&mono_jit_stats.methods_aot_llvm);
if (methods_aot == mini_debug_options.aot_skip) {
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (method) {
char *name = mono_method_full_name (method, TRUE);
g_print ("NON AOT METHOD: %s.\n", name);
g_free (name);
} else {
g_print ("NON AOT METHOD: %p %d\n", code, method_index);
}
mini_debug_options.aot_skip_set = FALSE;
return NULL;
}
}
if (mono_last_aot_method != -1) {
gint32 methods_aot = mono_atomic_load_i32 (&mono_jit_stats.methods_aot);
methods_aot += mono_atomic_load_i32 (&mono_jit_stats.methods_aot_llvm);
if (methods_aot >= mono_last_aot_method)
return NULL;
else if (methods_aot == mono_last_aot_method - 1) {
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
if (method) {
char *name = mono_method_full_name (method, TRUE);
g_print ("LAST AOT METHOD: %s.\n", name);
g_free (name);
} else {
g_print ("LAST AOT METHOD: %p %d\n", code, method_index);
}
}
}
if (!(is_llvm_code (amodule, code) && (amodule->info.flags & MONO_AOT_FILE_FLAG_LLVM_ONLY)) ||
(mono_llvm_only && method && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)) {
/* offset == 0 means its llvm code */
if (mono_aot_get_offset (amodule->method_info_offsets, method_index) != 0) {
res = init_method (amodule, NULL, method_index, method, NULL, error);
if (!res)
goto cleanup;
}
}
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
if (!method) {
method = mono_get_method_checked (image, token, NULL, NULL, error);
if (!method)
return NULL;
}
full_name = mono_method_full_name (method, TRUE);
if (!jinfo)
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND method %s [%p - %p %p]", full_name, code, code + jinfo->code_size, info);
g_free (full_name);
}
if (mono_llvm_only) {
guint8 flags = amodule->method_flags_table [method_index];
/* The caller needs to looks this up, but its hard to do without constructing the full MonoJitInfo, so save it here */
if (flags & (MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE | MONO_AOT_METHOD_FLAG_INTERP_ENTRY_ONLY)) {
mono_aot_lock ();
if (!code_to_method_flags)
code_to_method_flags = g_hash_table_new (NULL, NULL);
g_hash_table_insert (code_to_method_flags, code, GUINT_TO_POINTER (flags));
mono_aot_unlock ();
}
}
init_plt (amodule);
amodule_lock (amodule);
if (is_llvm_code (amodule, code))
mono_atomic_inc_i32 (&mono_jit_stats.methods_aot_llvm);
else
mono_atomic_inc_i32 (&mono_jit_stats.methods_aot);
if (method && method->wrapper_type)
g_hash_table_insert (amodule->method_to_code, method, code);
/* Commit changes since methods_loaded is accessed outside the lock */
mono_memory_barrier ();
amodule->methods_loaded [method_index / 32] |= 1 << (method_index % 32);
amodule_unlock (amodule);
if (MONO_PROFILER_ENABLED (jit_begin) || MONO_PROFILER_ENABLED (jit_done)) {
MonoJitInfo *jinfo;
if (!method) {
method = mono_get_method_checked (amodule->assembly->image, token, NULL, NULL, error);
if (!method)
return NULL;
}
MONO_PROFILER_RAISE (jit_begin, (method));
jinfo = mono_jit_info_table_find_internal (code, TRUE, FALSE);
g_assert (jinfo);
MONO_PROFILER_RAISE (jit_done, (method, jinfo));
}
return code;
cleanup:
if (jinfo)
g_free (jinfo);
return NULL;
}
/** find_aot_method_in_amodule
*
* \param code_amodule The AOT module containing the code pointer
* \param method The method to find the code index for
* \param hash_full The hash for the method
*/
static guint32
find_aot_method_in_amodule (MonoAotModule *code_amodule, MonoMethod *method, guint32 hash_full)
{
ERROR_DECL (error);
guint32 table_size, entry_size, hash;
guint32 *table, *entry;
guint32 index;
static guint32 n_extra_decodes;
// The AOT module containing the MonoMethod
// The reference to the metadata amodule will differ among multiple dedup methods
// which mangle to the same name but live in different assemblies. This leads to
// the caching breaking. The solution seems to be to cache using the "metadata" amodule.
MonoAotModule *metadata_amodule = m_class_get_image (method->klass)->aot_module;
if (!metadata_amodule || metadata_amodule->out_of_date || !code_amodule || code_amodule->out_of_date)
return 0xffffff;
table_size = code_amodule->extra_method_table [0];
hash = hash_full % table_size;
table = code_amodule->extra_method_table + 1;
entry_size = 3;
entry = &table [hash * entry_size];
if (entry [0] == 0)
return 0xffffff;
index = 0xffffff;
while (TRUE) {
guint32 key = entry [0];
guint32 value = entry [1];
guint32 next = entry [entry_size - 1];
MonoMethod *m;
guint8 *p, *orig_p;
p = code_amodule->blob + key;
orig_p = p;
amodule_lock (metadata_amodule);
if (!metadata_amodule->method_ref_to_method)
metadata_amodule->method_ref_to_method = g_hash_table_new (NULL, NULL);
m = (MonoMethod *)g_hash_table_lookup (metadata_amodule->method_ref_to_method, p);
amodule_unlock (metadata_amodule);
if (!m) {
m = decode_resolve_method_ref_with_target (code_amodule, method, p, &p, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
/*
* Can't catche runtime invoke wrappers since it would break
* the check in decode_method_ref_with_target ().
*/
if (m && m->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE) {
amodule_lock (metadata_amodule);
g_hash_table_insert (metadata_amodule->method_ref_to_method, orig_p, m);
amodule_unlock (metadata_amodule);
}
}
if (m == method) {
index = value;
break;
}
/* Methods decoded needlessly */
if (m) {
//printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
n_extra_decodes ++;
}
if (next != 0)
entry = &table [next * entry_size];
else
break;
}
if (index != 0xffffff)
g_assert (index < code_amodule->info.nmethods);
return index;
}
static void
add_module_cb (gpointer key, gpointer value, gpointer user_data)
{
g_ptr_array_add ((GPtrArray*)user_data, value);
}
static gboolean
inst_is_private (MonoGenericInst *inst)
{
for (int i = 0; i < inst->type_argc; ++i) {
MonoType *t = inst->type_argv [i];
if ((t->type == MONO_TYPE_CLASS || t->type == MONO_TYPE_VALUETYPE)) {
int access_level = mono_class_get_flags (t->data.klass) & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (access_level == TYPE_ATTRIBUTE_NESTED_PRIVATE || access_level == TYPE_ATTRIBUTE_NOT_PUBLIC)
return TRUE;
}
}
return FALSE;
}
gboolean
mono_aot_can_dedup (MonoMethod *method)
{
#ifdef TARGET_WASM
/* Use a set of wrappers/instances which work and useful */
switch (method->wrapper_type) {
case MONO_WRAPPER_RUNTIME_INVOKE:
return TRUE;
break;
case MONO_WRAPPER_OTHER: {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR ||
info->subtype == WRAPPER_SUBTYPE_INTERP_LMF ||
info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
return FALSE;
#if 0
// See is_linkonce_method () in mini-llvm.c
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
/* Handled using linkonce */
return FALSE;
#endif
return TRUE;
}
default:
break;
}
if (method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) &&
!mini_is_gsharedvt_signature (mono_method_signature_internal (method)) &&
!mini_is_gsharedvt_klass (method->klass)) {
MonoGenericContext *context = mono_method_get_context (method);
if (context->method_inst && mini_is_gsharedvt_inst (context->method_inst))
return FALSE;
/* No point in dedup-ing private instances */
if ((context->class_inst && inst_is_private (context->class_inst)) ||
(context->method_inst && inst_is_private (context->method_inst)))
return FALSE;
return TRUE;
}
return FALSE;
#else
gboolean not_normal_gshared = method->is_inflated && !mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE);
gboolean extra_method = (method->wrapper_type != MONO_WRAPPER_NONE) || not_normal_gshared;
return extra_method;
#endif
}
/*
* find_aot_method:
*
* Try finding METHOD in the extra_method table in all AOT images.
* Return its method index, or 0xffffff if not found. Set OUT_AMODULE to the AOT
* module where the method was found.
*/
static guint32
find_aot_method (MonoMethod *method, MonoAotModule **out_amodule)
{
guint32 index;
GPtrArray *modules;
int i;
guint32 hash = mono_aot_method_hash (method);
/* Try the place we expect to have moved the method only
* We don't probe, as that causes hard-to-debug issues when we fail
* to find the method */
if (container_amodule && mono_aot_can_dedup (method)) {
*out_amodule = container_amodule;
index = find_aot_method_in_amodule (container_amodule, method, hash);
return index;
}
/* Try the method's module first */
*out_amodule = m_class_get_image (method->klass)->aot_module;
index = find_aot_method_in_amodule (m_class_get_image (method->klass)->aot_module, method, hash);
if (index != 0xffffff)
return index;
/*
* Try all other modules.
* This is needed because generic instances klass->image points to the image
* containing the generic definition, but the native code is generated to the
* AOT image which contains the reference.
*/
/* Make a copy to avoid doing the search inside the aot lock */
modules = g_ptr_array_new ();
mono_aot_lock ();
g_hash_table_foreach (aot_modules, add_module_cb, modules);
mono_aot_unlock ();
index = 0xffffff;
for (i = 0; i < modules->len; ++i) {
MonoAotModule *amodule = (MonoAotModule *)g_ptr_array_index (modules, i);
if (amodule != m_class_get_image (method->klass)->aot_module)
index = find_aot_method_in_amodule (amodule, method, hash);
if (index != 0xffffff) {
*out_amodule = amodule;
break;
}
}
g_ptr_array_free (modules, TRUE);
return index;
}
guint32
mono_aot_find_method_index (MonoMethod *method)
{
MonoAotModule *out_amodule;
return find_aot_method (method, &out_amodule);
}
static gboolean
init_method (MonoAotModule *amodule, gpointer info, guint32 method_index, MonoMethod *method, MonoClass *init_class, MonoError *error)
{
MonoMemPool *mp;
MonoClass *klass_to_run_ctor = NULL;
gboolean from_plt = method == NULL;
int pindex, n_patches;
guint8 *p;
MonoJitInfo *jinfo = NULL;
guint8 *code;
MonoGenericContext *context;
MonoGenericContext ctx;
/* Might be needed if the method is externally called */
init_plt (amodule);
init_amodule_got (amodule, FALSE);
memset (&ctx, 0, sizeof (ctx));
error_init (error);
if (!info)
info = &amodule->blob [mono_aot_get_offset (amodule->method_info_offsets, method_index)];
p = (guint8*)info;
// FIXME: Is this aligned ?
guint32 encoded_method_index = *(guint32*)p;
if (method_index)
g_assert (method_index == encoded_method_index);
method_index = encoded_method_index;
p += 4;
code = (guint8 *)amodule->methods [method_index];
guint8 flags = amodule->method_flags_table [method_index];
if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
klass_to_run_ctor = decode_klass_ref (amodule, p, &p, error);
if (!is_ok (error))
return FALSE;
//FIXME old code would use the class from @method if not null and ignore the one encoded. I don't know if we need to honor that -- @kumpera
if (method)
klass_to_run_ctor = method->klass;
context = NULL;
if (flags & MONO_AOT_METHOD_FLAG_HAS_CTX) {
decode_generic_context (amodule, &ctx, p, &p, error);
mono_error_assert_ok (error);
context = &ctx;
}
if (flags & MONO_AOT_METHOD_FLAG_HAS_PATCHES)
n_patches = decode_value (p, &p);
else
n_patches = 0;
if (n_patches) {
MonoJumpInfo *patches;
guint32 *got_slots;
gboolean llvm;
gpointer *got;
mp = mono_mempool_new ();
if ((gpointer)code >= amodule->info.jit_code_start && (gpointer)code <= amodule->info.jit_code_end) {
llvm = FALSE;
got = amodule->got;
} else {
llvm = TRUE;
got = amodule->llvm_got;
g_assert (got);
}
patches = load_patch_info (amodule, mp, n_patches, llvm, &got_slots, p, &p);
if (patches == NULL) {
mono_mempool_destroy (mp);
goto cleanup;
}
for (pindex = 0; pindex < n_patches; ++pindex) {
MonoJumpInfo *ji = &patches [pindex];
gpointer addr;
/*
* For SFLDA, we need to call resolve_patch_target () since the GOT slot could have
* been initialized by load_method () for a static cctor before the cctor has
* finished executing (#23242).
*/
if (ji->type == MONO_PATCH_INFO_NONE) {
} else if (!got [got_slots [pindex]] || ji->type == MONO_PATCH_INFO_SFLDA) {
/* In llvm-only made, we might encounter shared methods */
if (mono_llvm_only && ji->type == MONO_PATCH_INFO_METHOD && mono_method_check_context_used (ji->data.method)) {
g_assert (context);
ji->data.method = mono_class_inflate_generic_method_checked (ji->data.method, context, error);
if (!is_ok (error)) {
g_free (got_slots);
mono_mempool_destroy (mp);
return FALSE;
}
}
/* This cannot be resolved in mono_resolve_patch_target () */
if (ji->type == MONO_PATCH_INFO_AOT_JIT_INFO) {
// FIXME: Lookup using the index
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
ji->type = MONO_PATCH_INFO_ABS;
ji->data.target = jinfo;
}
addr = mono_resolve_patch_target (method, code, ji, TRUE, error);
if (!is_ok (error)) {
g_free (got_slots);
mono_mempool_destroy (mp);
return FALSE;
}
if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
addr = mono_create_ftnptr (addr);
mono_memory_barrier ();
got [got_slots [pindex]] = addr;
if (ji->type == MONO_PATCH_INFO_METHOD_JUMP)
register_jump_target_got_slot (ji->data.method, &(got [got_slots [pindex]]));
if (llvm) {
void (*init_aotconst) (int, gpointer) = (void (*)(int, gpointer))amodule->info.llvm_init_aotconst;
init_aotconst (got_slots [pindex], addr);
}
}
ji->type = MONO_PATCH_INFO_NONE;
}
g_free (got_slots);
mono_mempool_destroy (mp);
}
if (mini_debug_options.load_aot_jit_info_eagerly)
jinfo = mono_aot_find_jit_info (amodule->assembly->image, code);
gboolean inited_ok;
inited_ok = TRUE;
if (init_class) {
MonoVTable *vt = mono_class_vtable_checked (init_class, error);
if (!is_ok (error))
inited_ok = FALSE;
else
inited_ok = mono_runtime_class_init_full (vt, error);
} else if (from_plt && klass_to_run_ctor && !mono_class_is_gtd (klass_to_run_ctor)) {
MonoVTable *vt = mono_class_vtable_checked (klass_to_run_ctor, error);
if (!is_ok (error))
inited_ok = FALSE;
else
inited_ok = mono_runtime_class_init_full (vt, error);
}
if (!inited_ok)
return FALSE;
return TRUE;
cleanup:
if (jinfo)
g_free (jinfo);
return FALSE;
}
/*
* mono_aot_init_llvm_method:
*
* Initialize the LLVM method identified by METHOD_INFO.
*/
gboolean
mono_aot_init_llvm_method (gpointer aot_module, gpointer method_info, MonoClass *init_class, MonoError *error)
{
MonoAotModule *amodule = (MonoAotModule*)aot_module;
return init_method (amodule, method_info, 0, NULL, init_class, error);
}
/*
* mono_aot_get_method:
*
* Return a pointer to the AOTed native code for METHOD if it can be found,
* NULL otherwise.
* On platforms with function pointers, this doesn't return a function pointer.
*/
gpointer
mono_aot_get_method (MonoMethod *method, MonoError *error)
{
MonoClass *klass = method->klass;
MonoMethod *orig_method = method;
guint32 method_index;
MonoAotModule *amodule = m_class_get_image (klass)->aot_module;
guint8 *code;
gboolean cache_result = FALSE;
ERROR_DECL (inner_error);
error_init (error);
if (!amodule)
return NULL;
if (amodule->out_of_date)
return NULL;
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT))
return NULL;
/* Load the dedup module lazily */
load_container_amodule (mono_assembly_get_alc (amodule->assembly));
g_assert (m_class_is_inited (klass));
/* Find method index */
method_index = 0xffffff;
gboolean dedupable = mono_aot_can_dedup (method);
if (method->is_inflated && !method->wrapper_type && mono_method_is_generic_sharable_full (method, TRUE, FALSE, FALSE) && !dedupable) {
MonoMethod *orig_method = method;
/*
* For generic methods, we store the fully shared instance in place of the
* original method.
*/
method = mono_method_get_declaring_generic_method (method);
method_index = mono_metadata_token_index (method->token) - 1;
if (amodule->info.flags & MONO_AOT_FILE_FLAG_WITH_LLVM) {
/* Needed by mini_llvm_init_gshared_method_this () */
/* orig_method is a random instance but it is enough to make init_method () work */
amodule_lock (amodule);
g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), orig_method);
amodule_unlock (amodule);
}
}
if (method_index == 0xffffff && (method->is_inflated || !method->token)) {
/* This hash table is used to avoid the slower search in the extra_method_table in the AOT image */
amodule_lock (amodule);
code = (guint8 *)g_hash_table_lookup (amodule->method_to_code, method);
amodule_unlock (amodule);
if (code)
return code;
cache_result = TRUE;
if (method_index == 0xffffff)
method_index = find_aot_method (method, &amodule);
/*
* Special case the ICollection<T> wrappers for arrays, as they cannot
* be statically enumerated, and each wrapper ends up calling the same
* method in Array.
*/
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && m_class_get_rank (method->klass) && strstr (method->name, "System.Collections.Generic")) {
MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
/*
* Special case Array.GetGenericValue_icall which is a generic icall.
* Generic sharing currently can't handle it, but the icall returns data using
* an out parameter, so the managed-to-native wrappers can share the same code.
*/
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE && method->klass == mono_defaults.array_class && !strcmp (method->name, "GetGenericValue_icall")) {
MonoMethod *m;
MonoGenericContext ctx;
if (mono_method_signature_internal (method)->params [1]->type == MONO_TYPE_OBJECT)
/* Avoid recursion */
return NULL;
m = mono_class_get_method_from_name_checked (mono_defaults.array_class, "GetGenericValue_icall", 3, 0, error);
mono_error_assert_ok (error);
g_assert (m);
memset (&ctx, 0, sizeof (ctx));
MonoType *args [ ] = { m_class_get_byval_arg (mono_defaults.object_class) };
ctx.method_inst = mono_metadata_get_generic_inst (1, args);
m = mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE);
if (!m)
g_error ("AOT runtime could not load method due to %s", mono_error_get_message (error)); /* FIXME don't swallow the error */
/*
* Get the code for the <object> instantiation which should be emitted into
* the mscorlib aot image by the AOT compiler.
*/
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
/* For ARRAY_ACCESSOR wrappers with reference types, use the <object> instantiation saved in corlib */
if (method_index == 0xffffff && method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR) {
MonoMethod *array_method = info->d.array_accessor.method;
if (MONO_TYPE_IS_REFERENCE (m_class_get_byval_arg (m_class_get_element_class (array_method->klass)))) {
int rank;
if (!strcmp (array_method->name, "Set"))
rank = mono_method_signature_internal (array_method)->param_count - 1;
else if (!strcmp (array_method->name, "Get") || !strcmp (array_method->name, "Address"))
rank = mono_method_signature_internal (array_method)->param_count;
else
g_assert_not_reached ();
MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, rank);
MonoMethod *m = mono_class_get_method_from_name_checked (obj_array_class, array_method->name, mono_method_signature_internal (array_method)->param_count, 0, error);
mono_error_assert_ok (error);
g_assert (m);
m = mono_marshal_get_array_accessor_wrapper (m);
if (m != method) {
code = (guint8 *)mono_aot_get_method (m, inner_error);
mono_error_cleanup (inner_error);
if (code)
return code;
}
}
}
}
if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
/* Partial sharing */
MonoMethod *shared;
shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
return_val_if_nok (error, NULL);
method_index = find_aot_method (shared, &amodule);
if (method_index != 0xffffff)
method = shared;
}
if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
MonoMethod *shared;
/* gsharedvt */
/* Use the all-vt shared method since this is what was AOTed */
shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
if (!shared)
return NULL;
method_index = find_aot_method (shared, &amodule);
if (method_index != 0xffffff) {
method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
if (!method)
return NULL;
}
}
if (method_index == 0xffffff) {
if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
char *full_name;
full_name = mono_method_full_name (method, TRUE);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT NOT FOUND: %s.", full_name);
g_free (full_name);
}
return NULL;
}
if (method_index == 0xffffff)
return NULL;
/* Needed by find_jit_info */
amodule_lock (amodule);
g_hash_table_insert (amodule->extra_methods, GUINT_TO_POINTER (method_index), method);
amodule_unlock (amodule);
} else {
/* Common case */
method_index = mono_metadata_token_index (method->token) - 1;
if (!mono_llvm_only) {
guint32 num_methods = amodule->info.nmethods - amodule->info.nextra_methods;
if (method_index >= num_methods)
/* method not available in AOT image */
return NULL;
}
}
code = (guint8 *)load_method (amodule, m_class_get_image (klass), method, method->token, method_index, error);
if (!is_ok (error))
return NULL;
if (code && cache_result) {
amodule_lock (amodule);
g_hash_table_insert (amodule->method_to_code, orig_method, code);
amodule_unlock (amodule);
}
return code;
}
/**
* Same as mono_aot_get_method, but we try to avoid loading any metadata from the
* method.
*/
gpointer
mono_aot_get_method_from_token (MonoImage *image, guint32 token, MonoError *error)
{
MonoAotModule *aot_module = image->aot_module;
int method_index;
gpointer res;
error_init (error);
if (!aot_module)
return NULL;
method_index = mono_metadata_token_index (token) - 1;
res = load_method (aot_module, image, NULL, token, method_index, error);
return res;
}
typedef struct {
guint8 *addr;
gboolean res;
} IsGotEntryUserData;
static void
check_is_got_entry (gpointer key, gpointer value, gpointer user_data)
{
IsGotEntryUserData *data = (IsGotEntryUserData*)user_data;
MonoAotModule *aot_module = (MonoAotModule*)value;
if (aot_module->got && (data->addr >= (guint8*)(aot_module->got)) && (data->addr < (guint8*)(aot_module->got + aot_module->info.got_size)))
data->res = TRUE;
}
gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
IsGotEntryUserData user_data;
if (!aot_modules)
return FALSE;
user_data.addr = addr;
user_data.res = FALSE;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, check_is_got_entry, &user_data);
mono_aot_unlock ();
return user_data.res;
}
typedef struct {
guint8 *addr;
MonoAotModule *module;
} FindAotModuleUserData;
static void
find_aot_module_cb (gpointer key, gpointer value, gpointer user_data)
{
FindAotModuleUserData *data = (FindAotModuleUserData*)user_data;
MonoAotModule *aot_module = (MonoAotModule*)value;
if (amodule_contains_code_addr (aot_module, data->addr))
data->module = aot_module;
}
static MonoAotModule*
find_aot_module (guint8 *code)
{
FindAotModuleUserData user_data;
if (!aot_modules)
return NULL;
/* Reading these need no locking */
if (((gsize)code < aot_code_low_addr) || ((gsize)code > aot_code_high_addr))
return NULL;
user_data.addr = code;
user_data.module = NULL;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, find_aot_module_cb, &user_data);
mono_aot_unlock ();
return user_data.module;
}
#ifdef MONO_ARCH_CODE_EXEC_ONLY
static guint32
aot_resolve_plt_info_offset (gpointer amodule, guint32 plt_entry_index)
{
MonoAotModule *module = (MonoAotModule*)amodule;
return mono_aot_get_offset (module->got_info_offsets, module->info.plt_got_info_offset_base + plt_entry_index);
}
#endif
void
mono_aot_patch_plt_entry (gpointer aot_module, guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
{
MonoAotModule *amodule = (MonoAotModule *)aot_module;
if (!amodule)
amodule = find_aot_module (code);
#ifdef MONO_ARCH_CODE_EXEC_ONLY
mono_arch_patch_plt_entry_exec_only (&amodule->info, plt_entry, amodule->got, regs, addr);
#else
mono_arch_patch_plt_entry (plt_entry, amodule->got, regs, addr);
#endif
}
/*
* mono_aot_plt_resolve:
*
* This function is called by the entries in the PLT to resolve the actual method that
* needs to be called. It returns a trampoline to the method and patches the PLT entry.
* Returns NULL if the something cannot be loaded.
*/
gpointer
mono_aot_plt_resolve (gpointer aot_module, host_mgreg_t *regs, guint8 *code, MonoError *error)
{
#ifdef MONO_ARCH_AOT_SUPPORTED
guint8 *p, *target, *plt_entry;
guint32 plt_info_offset;
MonoJumpInfo ji;
MonoAotModule *module = (MonoAotModule*)aot_module;
gboolean res, no_ftnptr = FALSE;
MonoMemPool *mp;
gboolean using_gsharedvt = FALSE;
error_init (error);
plt_entry = mono_aot_get_plt_entry (regs, code);
g_assert (plt_entry);
plt_info_offset = mono_aot_get_plt_info_offset (aot_module, plt_entry, regs, code);
//printf ("DYN: %p %d\n", aot_module, plt_info_offset);
p = &module->blob [plt_info_offset];
ji.type = (MonoJumpInfoType)decode_value (p, &p);
mp = mono_mempool_new ();
res = decode_patch (module, mp, &ji, p, &p);
if (!res) {
mono_mempool_destroy (mp);
return NULL;
}
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
using_gsharedvt = TRUE;
#endif
/*
* Avoid calling resolve_patch_target in the full-aot case if possible, since
* it would create a trampoline, and we don't need that.
* We could do this only if the method does not need the special handling
* in mono_magic_trampoline ().
*/
if (mono_aot_only && ji.type == MONO_PATCH_INFO_METHOD && !ji.data.method->is_generic && !mono_method_check_context_used (ji.data.method) && !(ji.data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) &&
!mono_method_needs_static_rgctx_invoke (ji.data.method, FALSE) && !using_gsharedvt) {
target = (guint8 *)mono_jit_compile_method (ji.data.method, error);
if (!is_ok (error)) {
mono_mempool_destroy (mp);
return NULL;
}
no_ftnptr = TRUE;
} else {
target = (guint8 *)mono_resolve_patch_target (NULL, NULL, &ji, TRUE, error);
if (!is_ok (error)) {
mono_mempool_destroy (mp);
return NULL;
}
}
/*
* The trampoline expects us to return a function descriptor on platforms which use
* it, but resolve_patch_target returns a direct function pointer for some type of
* patches, so have to translate between the two.
* FIXME: Clean this up, but how ?
*/
if (ji.type == MONO_PATCH_INFO_ABS
|| ji.type == MONO_PATCH_INFO_JIT_ICALL_ID
|| ji.type == MONO_PATCH_INFO_ICALL_ADDR
|| ji.type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR
|| ji.type == MONO_PATCH_INFO_JIT_ICALL_ADDR
|| ji.type == MONO_PATCH_INFO_RGCTX_FETCH) {
/* These should already have a function descriptor */
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
/* Our function descriptors have a 0 environment, gcc created ones don't */
if (ji.type != MONO_PATCH_INFO_JIT_ICALL_ID
&& ji.type != MONO_PATCH_INFO_JIT_ICALL_ADDR
&& ji.type != MONO_PATCH_INFO_ICALL_ADDR
&& ji.type != MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR)
g_assert (((gpointer*)target) [2] == 0);
#endif
/* Empty */
} else if (!no_ftnptr) {
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
g_assert (((gpointer*)target) [2] != 0);
#endif
target = (guint8 *)mono_create_ftnptr (target);
}
mono_mempool_destroy (mp);
/* Patch the PLT entry with target which might be the actual method not a trampoline */
mono_aot_patch_plt_entry (aot_module, code, plt_entry, module->got, regs, target);
return target;
#else
g_assert_not_reached ();
return NULL;
#endif
}
/**
* init_plt:
*
* Initialize the PLT table of the AOT module. Called lazily when the first AOT
* method in the module is loaded to avoid committing memory by writing to it.
*/
static void
init_plt (MonoAotModule *amodule)
{
int i;
gpointer tramp;
if (amodule->plt_inited)
return;
tramp = mono_create_specific_trampoline (get_default_mem_manager (), amodule, MONO_TRAMPOLINE_AOT_PLT, NULL);
tramp = mono_create_ftnptr (tramp);
amodule_lock (amodule);
if (amodule->plt_inited) {
amodule_unlock (amodule);
return;
}
if (amodule->info.plt_size <= 1) {
amodule->plt_inited = TRUE;
amodule_unlock (amodule);
return;
}
/*
* Initialize the PLT entries in the GOT to point to the default targets.
*/
for (i = 1; i < amodule->info.plt_size; ++i)
/* All the default entries point to the AOT trampoline */
((gpointer*)amodule->got)[amodule->info.plt_got_offset_base + i] = tramp;
mono_memory_barrier ();
amodule->plt_inited = TRUE;
amodule_unlock (amodule);
}
/*
* mono_aot_get_plt_entry:
*
* Return the address of the PLT entry called by the code at CODE if exists.
*/
guint8*
mono_aot_get_plt_entry (host_mgreg_t *regs, guint8 *code)
{
MonoAotModule *amodule = find_aot_module (code);
guint8 *target = NULL;
if (!amodule)
return NULL;
#ifdef TARGET_ARM
if (is_thumb_code (amodule, code - 4))
return mono_arm_get_thumb_plt_entry (code);
#endif
#ifdef MONO_ARCH_AOT_SUPPORTED
#ifdef MONO_ARCH_CODE_EXEC_ONLY
target = mono_aot_arch_get_plt_entry_exec_only (&amodule->info, regs, code, amodule->plt);
#else
target = mono_arch_get_call_target (code);
#endif
#else
g_assert_not_reached ();
#endif
#ifdef MONOTOUCH
while (target != NULL) {
if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
return target;
// Add 4 since mono_arch_get_call_target assumes we're passing
// the instruction after the actual branch instruction.
target = mono_arch_get_call_target (target + 4);
}
return NULL;
#else
if ((target >= (guint8*)(amodule->plt)) && (target < (guint8*)(amodule->plt_end)))
return target;
else
return NULL;
#endif
}
/*
* mono_aot_get_plt_info_offset:
*
* Return the PLT info offset belonging to the plt entry called by CODE.
*/
guint32
mono_aot_get_plt_info_offset (gpointer aot_module, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code)
{
if (!plt_entry) {
plt_entry = mono_aot_get_plt_entry (regs, code);
g_assert (plt_entry);
}
/* The offset is embedded inside the code after the plt entry */
#ifdef MONO_ARCH_AOT_SUPPORTED
#ifdef MONO_ARCH_CODE_EXEC_ONLY
return mono_arch_get_plt_info_offset_exec_only (&((MonoAotModule*)aot_module)->info, plt_entry, regs, code, aot_resolve_plt_info_offset, aot_module);
#else
return mono_arch_get_plt_info_offset (plt_entry, regs, code);
#endif
#else
g_assert_not_reached ();
return 0;
#endif
}
static gpointer
mono_create_ftnptr_malloc (guint8 *code)
{
#ifdef PPC_USES_FUNCTION_DESCRIPTOR
MonoPPCFunctionDescriptor *ftnptr = g_malloc0 (sizeof (MonoPPCFunctionDescriptor));
ftnptr->code = code;
ftnptr->toc = NULL;
ftnptr->env = NULL;
return ftnptr;
#else
return code;
#endif
}
/*
* load_function_full:
*
* Load the function named NAME from the aot image.
*/
static gpointer
load_function_full (MonoAotModule *amodule, const char *name, MonoTrampInfo **out_tinfo)
{
char *symbol;
guint8 *p;
int n_patches, pindex;
MonoMemPool *mp;
gpointer code;
guint32 info_offset;
/* Load the code */
find_amodule_symbol (amodule, name, &code);
g_assertf (code, "Symbol '%s' not found in AOT file '%s'.\n", name, amodule->aot_name);
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "AOT: FOUND function '%s' in AOT file '%s'.", name, amodule->aot_name);
/* Load info */
symbol = g_strdup_printf ("%s_p", name);
find_amodule_symbol (amodule, symbol, (gpointer *)&p);
g_free (symbol);
if (!p)
/* Nothing to patch */
return code;
info_offset = *(guint32*)p;
if (out_tinfo) {
MonoTrampInfo *tinfo;
guint32 code_size, uw_info_len, uw_offset;
guint8 *uw_info;
/* Construct a MonoTrampInfo from the data in the AOT image */
p += sizeof (guint32);
code_size = *(guint32*)p;
p += sizeof (guint32);
uw_offset = *(guint32*)p;
uw_info = amodule->unwind_info + uw_offset;
uw_info_len = decode_value (uw_info, &uw_info);
tinfo = g_new0 (MonoTrampInfo, 1);
tinfo->code = (guint8 *)code;
tinfo->code_size = code_size;
tinfo->uw_info_len = uw_info_len;
if (uw_info_len)
tinfo->uw_info = uw_info;
*out_tinfo = tinfo;
}
p = amodule->blob + info_offset;
/* Similar to mono_aot_load_method () */
n_patches = decode_value (p, &p);
if (n_patches) {
MonoJumpInfo *patches;
guint32 *got_slots;
mp = mono_mempool_new ();
patches = load_patch_info (amodule, mp, n_patches, FALSE, &got_slots, p, &p);
g_assert (patches);
for (pindex = 0; pindex < n_patches; ++pindex) {
MonoJumpInfo *ji = &patches [pindex];
ERROR_DECL (error);
gpointer target;
if (amodule->got [got_slots [pindex]])
continue;
/*
* When this code is executed, the runtime may not be initalized yet, so
* resolve the patch info by hand.
*/
if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR) {
target = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (ji->data.uindex), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, NULL);
target = mono_create_ftnptr_malloc ((guint8 *)target);
} else if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES) {
target = amodule->info.specific_trampolines;
g_assert (target);
} else if (ji->type == MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE) {
target = &amodule->got [amodule->info.trampoline_got_offset_base [MONO_AOT_TRAMP_SPECIFIC]];
} else if (ji->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
const MonoJitICallId jit_icall_id = (MonoJitICallId)ji->data.jit_icall_id;
switch (jit_icall_id) {
#undef MONO_AOT_ICALL
#define MONO_AOT_ICALL(x) case MONO_JIT_ICALL_ ## x: target = (gpointer)x; break;
MONO_AOT_ICALL (mono_get_lmf_addr)
MONO_AOT_ICALL (mono_thread_force_interruption_checkpoint_noraise)
MONO_AOT_ICALL (mono_exception_from_token)
case MONO_JIT_ICALL_mono_debugger_agent_single_step_from_context:
target = (gpointer)mono_component_debugger ()->single_step_from_context;
break;
case MONO_JIT_ICALL_mono_debugger_agent_breakpoint_from_context:
target = (gpointer)mono_component_debugger ()->breakpoint_from_context;
break;
case MONO_JIT_ICALL_mono_throw_exception:
target = mono_get_throw_exception_addr ();
break;
case MONO_JIT_ICALL_mono_rethrow_preserve_exception:
target = mono_get_rethrow_preserve_exception_addr ();
break;
case MONO_JIT_ICALL_generic_trampoline_jit:
case MONO_JIT_ICALL_generic_trampoline_jump:
case MONO_JIT_ICALL_generic_trampoline_rgctx_lazy_fetch:
case MONO_JIT_ICALL_generic_trampoline_aot:
case MONO_JIT_ICALL_generic_trampoline_aot_plt:
case MONO_JIT_ICALL_generic_trampoline_delegate:
case MONO_JIT_ICALL_generic_trampoline_vcall:
target = (gpointer)mono_get_trampoline_func (mono_jit_icall_id_to_trampoline_type (jit_icall_id));
break;
default:
target = mono_arch_load_function (jit_icall_id);
g_assertf (target, "Unknown relocation '%p'\n", ji->data.target);
}
} else {
/* Hopefully the code doesn't have patches which need method to be set.
*/
target = mono_resolve_patch_target (NULL, (guint8 *)code, ji, FALSE, error);
mono_error_assert_ok (error);
g_assert (target);
}
if (ji->type != MONO_PATCH_INFO_NONE)
amodule->got [got_slots [pindex]] = target;
}
g_free (got_slots);
mono_mempool_destroy (mp);
}
return code;
}
static gpointer
load_function (MonoAotModule *amodule, const char *name)
{
return load_function_full (amodule, name, NULL);
}
static MonoAotModule*
get_mscorlib_aot_module (void)
{
MonoImage *image;
MonoAotModule *amodule;
image = mono_defaults.corlib;
if (image && image->aot_module)
amodule = image->aot_module;
else
amodule = mscorlib_aot_module;
g_assert (amodule);
return amodule;
}
static void
mono_no_trampolines (void)
{
g_assert_not_reached ();
}
/*
* Return the trampoline identified by NAME from the mscorlib AOT file.
* On ppc64, this returns a function descriptor.
*/
gpointer
mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
{
MonoAotModule *amodule = get_mscorlib_aot_module ();
if (mono_llvm_only) {
*out_tinfo = NULL;
return (gpointer)mono_no_trampolines;
}
return mono_create_ftnptr_malloc ((guint8 *)load_function_full (amodule, name, out_tinfo));
}
gpointer
mono_aot_get_trampoline (const char *name)
{
MonoTrampInfo *out_tinfo;
gpointer code;
code = mono_aot_get_trampoline_full (name, &out_tinfo);
mono_aot_tramp_info_register (out_tinfo, NULL);
return code;
}
static gpointer
read_unwind_info (MonoAotModule *amodule, MonoTrampInfo *info, const char *symbol_name)
{
gpointer symbol_addr;
guint32 uw_offset, uw_info_len;
guint8 *uw_info;
find_amodule_symbol (amodule, symbol_name, &symbol_addr);
if (!symbol_addr)
return NULL;
uw_offset = *(guint32*)symbol_addr;
uw_info = amodule->unwind_info + uw_offset;
uw_info_len = decode_value (uw_info, &uw_info);
info->uw_info_len = uw_info_len;
if (uw_info_len)
info->uw_info = uw_info;
else
info->uw_info = NULL;
/* If successful return the address of the following data */
return (guint32*)symbol_addr + 1;
}
#ifdef MONOTOUCH
#include <mach/mach.h>
static TrampolinePage* trampoline_pages [MONO_AOT_TRAMP_NUM];
static void
read_page_trampoline_uwinfo (MonoTrampInfo *info, int tramp_type, gboolean is_generic)
{
char symbol_name [128];
if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
sprintf (symbol_name, "specific_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
sprintf (symbol_name, "rgctx_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_IMT)
sprintf (symbol_name, "imt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
sprintf (symbol_name, "gsharedvt_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
sprintf (symbol_name, "unbox_arbitrary_trampolines_page_%s_p", is_generic ? "gen" : "sp");
else
g_assert_not_reached ();
read_unwind_info (mscorlib_aot_module, info, symbol_name);
}
static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
TrampolinePage *page;
int count;
void *tpage;
vm_address_t addr, taddr;
kern_return_t ret;
vm_prot_t prot, max_prot;
int psize, specific_trampoline_size;
unsigned char *code;
specific_trampoline_size = 2 * sizeof (gpointer);
mono_aot_page_lock ();
page = trampoline_pages [tramp_type];
if (page && page->trampolines < page->trampolines_end) {
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
return code;
}
mono_aot_page_unlock ();
psize = MONO_AOT_TRAMP_PAGE_SIZE;
/* the trampoline template page is in the mscorlib module */
MonoAotModule *amodule = mscorlib_aot_module;
g_assert (amodule);
if (tramp_type == MONO_AOT_TRAMP_SPECIFIC)
tpage = load_function (amodule, "specific_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_STATIC_RGCTX)
tpage = load_function (amodule, "rgctx_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_IMT)
tpage = load_function (amodule, "imt_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_GSHAREDVT_ARG)
tpage = load_function (amodule, "gsharedvt_arg_trampolines_page");
else if (tramp_type == MONO_AOT_TRAMP_UNBOX_ARBITRARY)
tpage = load_function (amodule, "unbox_arbitrary_trampolines_page");
else
g_error ("Incorrect tramp type for trampolines page");
g_assert (tpage);
/*g_warning ("loaded trampolines page at %x", tpage);*/
/* avoid the unlikely case of looping forever */
count = 40;
page = NULL;
while (page == NULL && count-- > 0) {
MonoTrampInfo *gen_info, *sp_info;
addr = 0;
/* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
* while the second will contain the trampolines.
*/
do {
ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
} while (ret == KERN_ABORTED);
if (ret != KERN_SUCCESS) {
g_error ("Cannot allocate memory for trampolines: %d", ret);
break;
}
/*g_warning ("allocated trampoline double page at %x", addr);*/
/* replace the second page with a remapped trampoline page */
taddr = addr + psize;
vm_deallocate (mach_task_self (), taddr, psize);
ret = vm_remap (mach_task_self (), &taddr, psize, 0, FALSE, mach_task_self(), (vm_address_t)tpage, FALSE, &prot, &max_prot, VM_INHERIT_SHARE);
if (ret != KERN_SUCCESS) {
/* someone else got the page, try again */
vm_deallocate (mach_task_self (), addr, psize);
continue;
}
/*g_warning ("remapped trampoline page at %x", taddr);*/
mono_aot_page_lock ();
page = trampoline_pages [tramp_type];
/* some other thread already allocated, so use that to avoid wasting memory */
if (page && page->trampolines < page->trampolines_end) {
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
vm_deallocate (mach_task_self (), addr, psize);
vm_deallocate (mach_task_self (), taddr, psize);
return code;
}
page = (TrampolinePage*)addr;
page->next = trampoline_pages [tramp_type];
trampoline_pages [tramp_type] = page;
page->trampolines = (guint8*)(taddr + amodule->info.tramp_page_code_offsets [tramp_type]);
page->trampolines_end = (guint8*)(taddr + psize - 64);
code = page->trampolines;
page->trampolines += specific_trampoline_size;
mono_aot_page_unlock ();
/* Register the generic part at the beggining of the trampoline page */
gen_info = mono_tramp_info_create (NULL, (guint8*)taddr, amodule->info.tramp_page_code_offsets [tramp_type], NULL, NULL);
read_page_trampoline_uwinfo (gen_info, tramp_type, TRUE);
mono_aot_tramp_info_register (gen_info, NULL);
/*
* FIXME
* Registering each specific trampoline produces a lot of
* MonoJitInfo structures. Jump trampolines are also registered
* separately.
*/
if (tramp_type != MONO_AOT_TRAMP_SPECIFIC) {
/* Register the rest of the page as a single trampoline */
sp_info = mono_tramp_info_create (NULL, code, page->trampolines_end - code, NULL, NULL);
read_page_trampoline_uwinfo (sp_info, tramp_type, FALSE);
mono_aot_tramp_info_register (sp_info, NULL);
}
return code;
}
g_error ("Cannot allocate more trampoline pages: %d", ret);
return NULL;
}
#else
static unsigned char*
get_new_trampoline_from_page (int tramp_type)
{
g_error ("Page trampolines not supported.");
return NULL;
}
#endif
static gpointer
get_new_specific_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_SPECIFIC);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_rgctx_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_STATIC_RGCTX);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_imt_trampoline_from_page (gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_IMT);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
/*g_warning ("new imt trampoline at %p for data %p, (stored at %p)", code, arg, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_gsharedvt_arg_trampoline_from_page (gpointer tramp, gpointer arg)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_GSHAREDVT_ARG);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = arg;
data [1] = tramp;
/*g_warning ("new rgctx trampoline at %p for data %p, tramp %p (stored at %p)", code, arg, tramp, data);*/
return MINI_ADDR_TO_FTNPTR (code);
}
static gpointer
get_new_unbox_arbitrary_trampoline_frome_page (gpointer addr)
{
void *code;
gpointer *data;
code = get_new_trampoline_from_page (MONO_AOT_TRAMP_UNBOX_ARBITRARY);
data = (gpointer*)((char*)code - MONO_AOT_TRAMP_PAGE_SIZE);
data [0] = addr;
return MINI_ADDR_TO_FTNPTR (code);
}
/* Return a given kind of trampoline */
/* FIXME set unwind info for these trampolines */
static gpointer
get_numerous_trampoline (MonoAotTrampoline tramp_type, int n_got_slots, MonoAotModule **out_amodule, guint32 *got_offset, guint32 *out_tramp_size)
{
#ifndef DISABLE_ASSERT_MESSAGES
MonoImage *image;
#endif
MonoAotModule *amodule = get_mscorlib_aot_module ();
int index, tramp_size;
#ifndef DISABLE_ASSERT_MESSAGES
/* Currently, we keep all trampolines in the mscorlib AOT image */
image = mono_defaults.corlib;
#endif
*out_amodule = amodule;
mono_aot_lock ();
#ifdef MONOTOUCH
#define MONOTOUCH_TRAMPOLINES_ERROR ". See http://docs.xamarin.com/ios/troubleshooting for instructions on how to fix this condition."
#else
#define MONOTOUCH_TRAMPOLINES_ERROR ""
#endif
if (amodule->trampoline_index [tramp_type] == amodule->info.num_trampolines [tramp_type]) {
g_error ("Ran out of trampolines of type %d in '%s' (limit %d)%s\n",
tramp_type, image ? image->name : MONO_ASSEMBLY_CORLIB_NAME, amodule->info.num_trampolines [tramp_type], MONOTOUCH_TRAMPOLINES_ERROR);
}
index = amodule->trampoline_index [tramp_type] ++;
mono_aot_unlock ();
*got_offset = amodule->info.trampoline_got_offset_base [tramp_type] + (index * n_got_slots);
tramp_size = amodule->info.trampoline_size [tramp_type];
if (out_tramp_size)
*out_tramp_size = tramp_size;
return amodule->trampolines [tramp_type] + (index * tramp_size);
}
static void
no_specific_trampoline (void)
{
g_assert_not_reached ();
}
/*
* Return a specific trampoline from the AOT file.
*/
gpointer
mono_aot_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, guint32 *code_len)
{
MonoAotModule *amodule;
guint32 got_offset, tramp_size;
guint8 *code, *tramp;
static gpointer generic_trampolines [MONO_TRAMPOLINE_NUM];
static gboolean inited;
static guint32 num_trampolines;
if (mono_llvm_only) {
*code_len = 1;
return (gpointer)no_specific_trampoline;
}
if (!inited) {
mono_aot_lock ();
if (!inited) {
mono_counters_register ("Specific trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &num_trampolines);
inited = TRUE;
}
mono_aot_unlock ();
}
num_trampolines ++;
if (!generic_trampolines [tramp_type]) {
const char *symbol;
symbol = mono_get_generic_trampoline_name (tramp_type);
generic_trampolines [tramp_type] = mono_aot_get_trampoline (symbol);
}
tramp = (guint8 *)generic_trampolines [tramp_type];
g_assert (tramp);
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_specific_trampoline_from_page (tramp, arg1);
tramp_size = 8;
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_SPECIFIC, 2, &amodule, &got_offset, &tramp_size);
amodule->got [got_offset] = tramp;
amodule->got [got_offset + 1] = arg1;
}
if (code_len)
*code_len = tramp_size;
return MINI_ADDR_TO_FTNPTR (code);
}
gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_rgctx_trampoline_from_page (addr, ctx);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_STATIC_RGCTX, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = ctx;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
gpointer
mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_unbox_arbitrary_trampoline_frome_page (addr);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_UNBOX_ARBITRARY, 1, &amodule, &got_offset, NULL);
amodule->got [got_offset] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
static int
i32_idx_comparer (const void *key, const void *member)
{
gint32 idx1 = GPOINTER_TO_INT (key);
gint32 idx2 = *(gint32*)member;
return idx1 - idx2;
}
static int
ui16_idx_comparer (const void *key, const void *member)
{
int idx1 = GPOINTER_TO_INT (key);
int idx2 = *(guint16*)member;
return idx1 - idx2;
}
static gboolean
aot_is_slim_amodule (MonoAotModule *amodule)
{
if (!amodule)
return FALSE;
/* "slim" only applies to mscorlib.dll */
if (strcmp (amodule->aot_name, MONO_ASSEMBLY_CORLIB_NAME))
return FALSE;
guint32 f = amodule->info.flags;
return (f & MONO_AOT_FILE_FLAG_INTERP) && !(f & MONO_AOT_FILE_FLAG_FULL_AOT);
}
gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
{
ERROR_DECL (error);
guint32 method_index = mono_metadata_token_index (method->token) - 1;
MonoAotModule *amodule;
gpointer code;
guint32 *ut, *ut_end, *entry;
int low, high, entry_index = 0;
MonoTrampInfo *tinfo;
if (method->is_inflated && !mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE)) {
method_index = find_aot_method (method, &amodule);
if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE)) {
MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
mono_error_assert_ok (error);
method_index = find_aot_method (shared, &amodule);
}
if (method_index == 0xffffff && mono_method_is_generic_sharable_full (method, FALSE, TRUE, TRUE)) {
MonoMethod *shared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
mono_error_assert_ok (error);
method_index = find_aot_method (shared, &amodule);
}
} else
amodule = m_class_get_image (method->klass)->aot_module;
if (amodule == NULL || method_index == 0xffffff || aot_is_slim_amodule (amodule)) {
/* couldn't find unbox trampoline specifically generated for that
* method. this should only happen when an unbox trampoline is needed
* for `fullAOT code -> native-to-interp -> interp` transition if
* (1) it's a virtual call
* (2) the receiver is a value type, thus needs unboxing */
g_assert (mono_use_interpreter);
return mono_aot_get_unbox_arbitrary_trampoline (addr);
}
if (!amodule->unbox_tramp_per_method) {
gpointer arr = g_new0 (gpointer, amodule->info.nmethods);
mono_memory_barrier ();
gpointer old_arr = mono_atomic_cas_ptr ((volatile gpointer*)&amodule->unbox_tramp_per_method, arr, NULL);
if (old_arr)
g_free (arr);
}
if (amodule->unbox_tramp_per_method [method_index])
return amodule->unbox_tramp_per_method [method_index];
if (amodule->info.llvm_unbox_tramp_indexes) {
int unbox_tramp_idx;
/* Search the llvm_unbox_tramp_indexes table using a binary search */
if (amodule->info.llvm_unbox_tramp_elemsize == sizeof (guint32)) {
void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, i32_idx_comparer);
g_assert (ptr);
g_assert (*(int*)ptr == method_index);
unbox_tramp_idx = (guint32*)ptr - (guint32*)amodule->info.llvm_unbox_tramp_indexes;
} else {
void *ptr = mono_binary_search (GINT_TO_POINTER (method_index), amodule->info.llvm_unbox_tramp_indexes, amodule->info.llvm_unbox_tramp_num, amodule->info.llvm_unbox_tramp_elemsize, ui16_idx_comparer);
g_assert (ptr);
g_assert (*(guint16*)ptr == method_index);
unbox_tramp_idx = (guint16*)ptr - (guint16*)amodule->info.llvm_unbox_tramp_indexes;
}
g_assert (unbox_tramp_idx < amodule->info.llvm_unbox_tramp_num);
code = ((gpointer*)(amodule->info.llvm_unbox_trampolines))[unbox_tramp_idx];
g_assert (code);
code = MINI_ADDR_TO_FTNPTR (code);
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
return code;
}
if (amodule->info.llvm_get_unbox_tramp) {
gpointer (*get_tramp) (int) = (gpointer (*)(int))amodule->info.llvm_get_unbox_tramp;
code = get_tramp (method_index);
if (code) {
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
return code;
}
}
ut = amodule->unbox_trampolines;
ut_end = amodule->unbox_trampolines_end;
/* Do a binary search in the sorted table */
code = NULL;
low = 0;
high = (ut_end - ut);
while (low < high) {
entry_index = (low + high) / 2;
entry = &ut [entry_index];
if (entry [0] < method_index) {
low = entry_index + 1;
} else if (entry [0] > method_index) {
high = entry_index;
} else {
break;
}
}
if (amodule->info.flags & MONO_AOT_FILE_FLAG_CODE_EXEC_ONLY)
code = ((gpointer*)amodule->unbox_trampoline_addresses) [entry_index];
else
code = get_call_table_entry (amodule->unbox_trampoline_addresses, entry_index, amodule->info.call_table_entry_size);
g_assert (code);
code = MINI_ADDR_TO_FTNPTR (code);
tinfo = mono_tramp_info_create (NULL, (guint8 *)code, 0, NULL, NULL);
gpointer const symbol_addr = read_unwind_info (amodule, tinfo, "unbox_trampoline_p");
if (!symbol_addr) {
mono_tramp_info_free (tinfo);
return FALSE;
}
tinfo->method = method;
tinfo->code_size = *(guint32*)symbol_addr;
tinfo->unwind_ops = mono_arch_get_cie_program ();
mono_aot_tramp_info_register (tinfo, NULL);
mono_memory_barrier ();
amodule->unbox_tramp_per_method [method_index] = code;
/* The caller expects an ftnptr */
return mono_create_ftnptr (code);
}
gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
char *symbol;
gpointer code;
MonoAotModule *amodule = mscorlib_aot_module;
guint32 index = MONO_RGCTX_SLOT_INDEX (slot);
static int count = 0;
count ++;
if (index >= amodule->info.num_rgctx_fetch_trampolines) {
static gpointer addr;
gpointer *info;
/*
* Use the general version of the rgctx fetch trampoline. It receives a pair of <slot, trampoline> in the rgctx arg reg.
*/
if (!addr)
addr = load_function (amodule, "rgctx_fetch_trampoline_general");
info = (void **)mono_mem_manager_alloc0 (get_default_mem_manager (), sizeof (gpointer) * 2);
info [0] = GUINT_TO_POINTER (slot);
info [1] = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, NULL);
code = mono_aot_get_static_rgctx_trampoline (info, addr);
return mono_create_ftnptr (code);
}
symbol = mono_get_rgctx_fetch_trampoline_name (slot);
code = load_function (amodule, symbol);
g_free (symbol);
/* The caller expects an ftnptr */
return mono_create_ftnptr (code);
}
static void
no_imt_trampoline (void)
{
g_assert_not_reached ();
}
gpointer
mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
guint32 got_offset;
gpointer code;
gpointer *buf;
int i, index, real_count;
MonoAotModule *amodule;
if (mono_llvm_only)
return (gpointer)no_imt_trampoline;
real_count = 0;
for (i = 0; i < count; ++i) {
MonoIMTCheckItem *item = imt_entries [i];
if (item->is_equals)
real_count ++;
}
/* Save the entries into an array */
buf = (void **)m_class_alloc0 (vtable->klass, (real_count + 1) * 2 * sizeof (gpointer));
index = 0;
for (i = 0; i < count; ++i) {
MonoIMTCheckItem *item = imt_entries [i];
if (!item->is_equals)
continue;
g_assert (item->key);
buf [(index * 2)] = item->key;
if (item->has_target_code) {
gpointer *p = (gpointer *)m_class_alloc0 (vtable->klass, sizeof (gpointer));
*p = item->value.target_code;
buf [(index * 2) + 1] = p;
} else {
buf [(index * 2) + 1] = &(vtable->vtable [item->value.vtable_slot]);
}
index ++;
}
buf [(index * 2)] = NULL;
buf [(index * 2) + 1] = fail_tramp;
if (USE_PAGE_TRAMPOLINES) {
code = get_new_imt_trampoline_from_page (buf);
} else {
code = get_numerous_trampoline (MONO_AOT_TRAMP_IMT, 1, &amodule, &got_offset, NULL);
amodule->got [got_offset] = buf;
}
return MINI_ADDR_TO_FTNPTR (code);
}
gpointer
mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
code = (guint8 *)get_new_gsharedvt_arg_trampoline_from_page (addr, arg);
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_GSHAREDVT_ARG, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = arg;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
gpointer
mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
{
MonoAotModule *amodule;
guint8 *code;
guint32 got_offset;
if (USE_PAGE_TRAMPOLINES) {
g_error ("FIXME: ftnptr_arg page trampolines");
} else {
code = (guint8 *)get_numerous_trampoline (MONO_AOT_TRAMP_FTNPTR_ARG, 2, &amodule, &got_offset, NULL);
amodule->got [got_offset] = arg;
amodule->got [got_offset + 1] = addr;
}
/* The caller expects an ftnptr */
return mono_create_ftnptr (MINI_ADDR_TO_FTNPTR (code));
}
#endif
/*
* mono_aot_set_make_unreadable:
*
* Set whenever to make all mmaped memory unreadable. In conjuction with a
* SIGSEGV handler, this is useful to find out which pages the runtime tries to read.
*/
void
mono_aot_set_make_unreadable (gboolean unreadable)
{
static int inited;
make_unreadable = unreadable;
if (make_unreadable && !inited) {
mono_counters_register ("AOT: pagefaults", MONO_COUNTER_JIT | MONO_COUNTER_INT, &n_pagefaults);
}
}
typedef struct {
MonoAotModule *module;
guint8 *ptr;
} FindMapUserData;
static void
find_map (gpointer key, gpointer value, gpointer user_data)
{
MonoAotModule *module = (MonoAotModule*)value;
FindMapUserData *data = (FindMapUserData*)user_data;
if (!data->module)
if ((data->ptr >= module->mem_begin) && (data->ptr < module->mem_end))
data->module = module;
}
static MonoAotModule*
find_module_for_addr (void *ptr)
{
FindMapUserData data;
if (!make_unreadable)
return NULL;
data.module = NULL;
data.ptr = (guint8*)ptr;
mono_aot_lock ();
g_hash_table_foreach (aot_modules, (GHFunc)find_map, &data);
mono_aot_unlock ();
return data.module;
}
/*
* mono_aot_is_pagefault:
*
* Should be called from a SIGSEGV signal handler to find out whenever @ptr is
* within memory allocated by this module.
*/
gboolean
mono_aot_is_pagefault (void *ptr)
{
if (!make_unreadable)
return FALSE;
/*
* Not signal safe, but SIGSEGV's are synchronous, and
* this is only turned on by a MONO_DEBUG option.
*/
return find_module_for_addr (ptr) != NULL;
}
/*
* mono_aot_handle_pagefault:
*
* Handle a pagefault caused by an unreadable page by making it readable again.
*/
void
mono_aot_handle_pagefault (void *ptr)
{
#ifndef HOST_WIN32
guint8* start = (guint8*)ROUND_DOWN (((gssize)ptr), mono_pagesize ());
int res;
mono_aot_lock ();
res = mono_mprotect (start, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
g_assert (res == 0);
n_pagefaults ++;
mono_aot_unlock ();
#endif
}
MonoAotMethodFlags
mono_aot_get_method_flags (guint8 *code)
{
guint32 flags;
if (!code_to_method_flags)
return MONO_AOT_METHOD_FLAG_NONE;
mono_aot_lock ();
/* Not found and no FLAG_NONE are the same, but its not a problem */
flags = GPOINTER_TO_UINT (g_hash_table_lookup (code_to_method_flags, code));
mono_aot_unlock ();
return (MonoAotMethodFlags)flags;
}
#else
/* AOT disabled */
void
mono_aot_init (void)
{
}
guint32
mono_aot_find_method_index (MonoMethod *method)
{
g_assert_not_reached ();
return 0;
}
gboolean
mono_aot_init_llvm_method (gpointer aot_module, gpointer method_info, MonoClass *init_class, MonoError *error)
{
g_assert_not_reached ();
return FALSE;
}
gpointer
mono_aot_get_method (MonoMethod *method, MonoError *error)
{
error_init (error);
return NULL;
}
gboolean
mono_aot_is_got_entry (guint8 *code, guint8 *addr)
{
return FALSE;
}
gboolean
mono_aot_get_cached_class_info (MonoClass *klass, MonoCachedClassInfo *res)
{
return FALSE;
}
gboolean
mono_aot_get_class_from_name (MonoImage *image, const char *name_space, const char *name, MonoClass **klass)
{
return FALSE;
}
MonoJitInfo *
mono_aot_find_jit_info (MonoImage *image, gpointer addr)
{
return NULL;
}
gpointer
mono_aot_get_method_from_token (MonoImage *image, guint32 token, MonoError *error)
{
error_init (error);
return NULL;
}
guint8*
mono_aot_get_plt_entry (host_mgreg_t *regs, guint8 *code)
{
return NULL;
}
gpointer
mono_aot_plt_resolve (gpointer aot_module, host_mgreg_t *regs, guint8 *code, MonoError *error)
{
return NULL;
}
void
mono_aot_patch_plt_entry (gpointer aot_module, guint8 *code, guint8 *plt_entry, gpointer *got, host_mgreg_t *regs, guint8 *addr)
{
}
gpointer
mono_aot_get_method_from_vt_slot (MonoVTable *vtable, int slot, MonoError *error)
{
error_init (error);
return NULL;
}
guint32
mono_aot_get_plt_info_offset (gpointer aot_module, guint8 *plt_entry, host_mgreg_t *regs, guint8 *code)
{
g_assert_not_reached ();
return 0;
}
gpointer
mono_aot_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, guint32 *code_len)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_static_rgctx_trampoline (gpointer ctx, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_trampoline_full (const char *name, MonoTrampInfo **out_tinfo)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_trampoline (const char *name)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_unbox_arbitrary_trampoline (gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_unbox_trampoline (MonoMethod *method, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_lazy_fetch_trampoline (guint32 slot)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_imt_trampoline (MonoVTable *vtable, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp)
{
g_assert_not_reached ();
return NULL;
}
gpointer
mono_aot_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
#ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
gpointer
mono_aot_get_ftnptr_arg_trampoline (gpointer arg, gpointer addr)
{
g_assert_not_reached ();
return NULL;
}
#endif
void
mono_aot_set_make_unreadable (gboolean unreadable)
{
}
gboolean
mono_aot_is_pagefault (void *ptr)
{
return FALSE;
}
void
mono_aot_handle_pagefault (void *ptr)
{
}
guint8*
mono_aot_get_unwind_info (MonoJitInfo *ji, guint32 *unwind_info_len)
{
g_assert_not_reached ();
return NULL;
}
GHashTable *
mono_aot_get_weak_field_indexes (MonoImage *image)
{
return NULL;
}
MonoAotMethodFlags
mono_aot_get_method_flags (guint8 *code)
{
return MONO_AOT_METHOD_FLAG_NONE;
}
#endif
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/mini/mini-runtime.c | /**
* \file
* Runtime code for the JIT
*
* Authors:
* Paolo Molaro ([email protected])
* Dietmar Maurer ([email protected])
*
* Copyright 2002-2003 Ximian, Inc.
* Copyright 2003-2010 Novell, Inc.
* Copyright 2011-2015 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>
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <math.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <signal.h>
#include <mono/utils/memcheck.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/runtime.h>
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/monitor.h>
#include <mono/metadata/icall-internals.h>
#include <mono/metadata/loader-internals.h>
#define MONO_MATH_DECLARE_ALL 1
#include <mono/utils/mono-math.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-path.h>
#include <mono/utils/mono-tls.h>
#include <mono/utils/mono-hwcap.h>
#include <mono/utils/dtrace.h>
#include <mono/utils/mono-signal-handler.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-proclib.h>
#include <mono/utils/mono-time.h>
#include <mono/metadata/w32handle.h>
#include <mono/metadata/components.h>
#include <mono/mini/debugger-agent-external.h>
#include "mini.h"
#include "seq-points.h"
#include <string.h>
#include <ctype.h>
#include "trace.h"
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "llvmonly-runtime.h"
#include "jit-icalls.h"
#include "mini-gc.h"
#include "mini-llvm.h"
#include "llvm-runtime.h"
#include "lldb.h"
#include "mini-runtime.h"
#include "interp/interp.h"
#ifdef MONO_ARCH_LLVM_SUPPORTED
#ifdef ENABLE_LLVM
#include "mini-llvm-cpp.h"
#include "llvm-jit.h"
#endif
#endif
#include "mono/metadata/icall-signatures.h"
#include "mono/utils/mono-tls-inline.h"
static guint32 default_opt = 0;
static gboolean default_opt_set = FALSE;
MonoMethodDesc *mono_stats_method_desc;
gboolean mono_compile_aot = FALSE;
/* If this is set, no code is generated dynamically, everything is taken from AOT files */
gboolean mono_aot_only = FALSE;
/* Same as mono_aot_only, but only LLVM compiled code is used, no trampolines */
gboolean mono_llvm_only = FALSE;
/* By default, don't require AOT but attempt to probe */
MonoAotMode mono_aot_mode = MONO_AOT_MODE_NORMAL;
MonoEEFeatures mono_ee_features;
const char *mono_build_date;
gboolean mono_do_signal_chaining;
gboolean mono_do_crash_chaining;
int mini_verbose = 0;
/*
* This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
* it can load AOT code compiled by LLVM.
*/
gboolean mono_use_llvm = FALSE;
gboolean mono_use_fast_math = FALSE;
// Lists of allowlisted and blocklisted CPU features
MonoCPUFeatures mono_cpu_features_enabled = (MonoCPUFeatures)0;
#ifdef DISABLE_SIMD
MonoCPUFeatures mono_cpu_features_disabled = MONO_CPU_X86_FULL_SSEAVX_COMBINED;
#else
MonoCPUFeatures mono_cpu_features_disabled = (MonoCPUFeatures)0;
#endif
gboolean mono_use_interpreter = FALSE;
const char *mono_interp_opts_string = NULL;
#define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
#define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
static mono_mutex_t jit_mutex;
static MonoCodeManager *global_codeman;
MonoDebugOptions mini_debug_options;
#ifdef VALGRIND_JIT_REGISTER_MAP
int valgrind_register;
#endif
GList* mono_aot_paths;
static GPtrArray *profile_options;
static GSList *tramp_infos;
GSList *mono_interp_only_classes;
static void register_icalls (void);
static void runtime_cleanup (MonoDomain *domain, gpointer user_data);
static void mini_invalidate_transformed_interp_methods (MonoAssemblyLoadContext *alc, uint32_t generation);
static void mini_interp_jit_info_foreach(InterpJitInfoFunc func, gpointer user_data);
static gboolean mini_interp_sufficient_stack (gsize size);
gboolean
mono_running_on_valgrind (void)
{
#ifndef HOST_WIN32
if (RUNNING_ON_VALGRIND){
#ifdef VALGRIND_JIT_REGISTER_MAP
valgrind_register = TRUE;
#endif
return TRUE;
} else
#endif
return FALSE;
}
void
mono_set_use_llvm (mono_bool use_llvm)
{
mono_use_llvm = (gboolean)use_llvm;
}
typedef struct {
void *ip;
MonoMethod *method;
} FindTrampUserData;
static void
find_tramp (gpointer key, gpointer value, gpointer user_data)
{
FindTrampUserData *ud = (FindTrampUserData*)user_data;
if (value == ud->ip)
ud->method = (MonoMethod*)key;
}
static char*
mono_get_method_from_ip_u (void *ip);
/* debug function */
char*
mono_get_method_from_ip (void *ip)
{
char *result;
MONO_ENTER_GC_UNSAFE;
result = mono_get_method_from_ip_u (ip);
MONO_EXIT_GC_UNSAFE;
return result;
}
/* debug function */
static char*
mono_get_method_from_ip_u (void *ip)
{
MonoJitInfo *ji;
MonoMethod *method;
char *method_name;
char *res;
MonoDomain *domain = mono_domain_get ();
MonoDebugSourceLocation *location;
FindTrampUserData user_data;
if (!domain)
domain = mono_get_root_domain ();
ji = mono_jit_info_table_find_internal (ip, TRUE, TRUE);
if (!ji) {
user_data.ip = ip;
user_data.method = NULL;
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_foreach (jit_mm->jit_trampoline_hash, find_tramp, &user_data);
jit_mm_unlock (jit_mm);
if (user_data.method) {
char *mname = mono_method_full_name (user_data.method, TRUE);
res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
g_free (mname);
return res;
}
else
return NULL;
} else if (ji->is_trampoline) {
res = g_strdup_printf ("<%p - %s trampoline>", ip, ji->d.tramp_info->name);
return res;
}
method = jinfo_get_method (ji);
method_name = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_IL);
location = mono_debug_lookup_source_location (method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
char *file_loc = NULL;
if (location)
file_loc = g_strdup_printf ("[%s :: %du]", location->source_file, location->row);
const char *in_interp = ji->is_interp ? " interp" : "";
res = g_strdup_printf (" %s [{%p} + 0x%x%s] %s (%p %p) [%p - %s]", method_name, method, (int)((char*)ip - (char*)ji->code_start), in_interp, file_loc ? file_loc : "", ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
mono_debug_free_source_location (location);
g_free (method_name);
g_free (file_loc);
return res;
}
/**
* mono_pmip:
* \param ip an instruction pointer address
*
* This method is used from a debugger to get the name of the
* method at address \p ip. This routine is typically invoked from
* a debugger like this:
*
* (gdb) print mono_pmip ($pc)
*
* \returns the name of the method at address \p ip.
*/
G_GNUC_UNUSED char *
mono_pmip (void *ip)
{
return mono_get_method_from_ip (ip);
}
G_GNUC_UNUSED char *
mono_pmip_u (void *ip)
{
return mono_get_method_from_ip_u (ip);
}
/**
* mono_print_method_from_ip:
* \param ip an instruction pointer address
*
* This method is used from a debugger to get the name of the
* method at address \p ip.
*
* This prints the name of the method at address \p ip in the standard
* output. Unlike \c mono_pmip which returns a string, this routine
* prints the value on the standard output.
*/
MONO_ATTR_USED void
mono_print_method_from_ip (void *ip)
{
MonoJitInfo *ji;
char *method;
MonoDebugSourceLocation *source;
MonoDomain *domain = mono_domain_get ();
MonoDomain *target_domain = mono_domain_get ();
FindTrampUserData user_data;
MonoGenericSharingContext*gsctx;
const char *shared_type;
if (!domain)
domain = mono_get_root_domain ();
ji = mini_jit_info_table_find_ext (ip, TRUE);
if (ji && ji->is_trampoline) {
MonoTrampInfo *tinfo = ji->d.tramp_info;
printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
return;
}
if (!ji) {
user_data.ip = ip;
user_data.method = NULL;
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_foreach (jit_mm->jit_trampoline_hash, find_tramp, &user_data);
jit_mm_unlock (jit_mm);
if (user_data.method) {
char *mname = mono_method_full_name (user_data.method, TRUE);
printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
g_free (mname);
return;
}
g_print ("No method at %p\n", ip);
fflush (stdout);
return;
}
method = mono_method_full_name (jinfo_get_method (ji), TRUE);
source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
gsctx = mono_jit_info_get_generic_sharing_context (ji);
shared_type = "";
if (gsctx) {
if (gsctx->is_gsharedvt)
shared_type = "gsharedvt ";
else
shared_type = "gshared ";
}
g_print ("IP %p at offset 0x%x of %smethod %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), shared_type, method, ji->code_start, (char*)ji->code_start + ji->code_size, target_domain, target_domain->friendly_name);
if (source)
g_print ("%s:%d\n", source->source_file, source->row);
fflush (stdout);
mono_debug_free_source_location (source);
g_free (method);
}
/*
* mono_method_same_domain:
*
* Determine whenever two compiled methods are in the same domain, thus
* the address of the callee can be embedded in the caller.
*/
gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
{
if (!caller || caller->is_trampoline || !callee || callee->is_trampoline)
return FALSE;
return TRUE;
}
/*
* mono_global_codeman_reserve:
*
* Allocate code memory from the global code manager.
*/
void *(mono_global_codeman_reserve) (int size)
{
void *ptr;
if (mono_aot_only)
g_error ("Attempting to allocate from the global code manager while running in aot-only mode.\n");
if (!global_codeman) {
/* This can happen during startup */
if (!mono_compile_aot)
global_codeman = mono_code_manager_new ();
else
global_codeman = mono_code_manager_new_aot ();
return mono_code_manager_reserve (global_codeman, size);
}
else {
mono_jit_lock ();
ptr = mono_code_manager_reserve (global_codeman, size);
mono_jit_unlock ();
return ptr;
}
}
/* The callback shouldn't take any locks */
void
mono_global_codeman_foreach (MonoCodeManagerFunc func, void *user_data)
{
mono_jit_lock ();
mono_code_manager_foreach (global_codeman, func, user_data);
mono_jit_unlock ();
}
/**
* mono_create_unwind_op:
*
* Create an unwind op with the given parameters.
*/
MonoUnwindOp*
mono_create_unwind_op (int when, int tag, int reg, int val)
{
MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
op->op = tag;
op->reg = reg;
op->val = val;
op->when = when;
return op;
}
MonoJumpInfoToken *
mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
{
MonoJumpInfoToken *res = (MonoJumpInfoToken *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
res->image = image;
res->token = token;
res->has_context = context != NULL;
if (context)
memcpy (&res->context, context, sizeof (MonoGenericContext));
return res;
}
MonoJumpInfoToken *
mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
{
return mono_jump_info_token_new2 (mp, image, token, NULL);
}
/*
* mono_tramp_info_create:
*
* Create a MonoTrampInfo structure from the arguments. This function assumes ownership
* of JI, and UNWIND_OPS.
*/
MonoTrampInfo*
mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
{
MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
info->name = g_strdup (name);
info->code = code;
info->code_size = code_size;
info->ji = ji;
info->unwind_ops = unwind_ops;
return info;
}
void
mono_tramp_info_free (MonoTrampInfo *info)
{
g_free (info->name);
// FIXME: ji
mono_free_unwind_info (info->unwind_ops);
if (info->owns_uw_info)
g_free (info->uw_info);
g_free (info);
}
static void
register_trampoline_jit_info (MonoMemoryManager *mem_manager, MonoTrampInfo *info)
{
MonoJitInfo *ji;
ji = (MonoJitInfo *)mono_mem_manager_alloc0 (mem_manager, mono_jit_info_size ((MonoJitInfoFlags)0, 0, 0));
mono_jit_info_init (ji, NULL, (guint8*)MINI_FTNPTR_TO_ADDR (info->code), info->code_size, (MonoJitInfoFlags)0, 0, 0);
ji->d.tramp_info = info;
ji->is_trampoline = TRUE;
ji->unwind_info = mono_cache_unwind_info (info->uw_info, info->uw_info_len);
mono_jit_info_table_add (ji);
}
/*
* mono_tramp_info_register:
*
* Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
* INFO can be NULL.
* Frees INFO.
*/
static void
mono_tramp_info_register_internal (MonoTrampInfo *info, MonoMemoryManager *mem_manager, gboolean aot)
{
MonoTrampInfo *copy;
MonoDomain *domain = mono_get_root_domain ();
if (!info)
return;
if (mem_manager)
copy = mono_mem_manager_alloc0 (mem_manager, sizeof (MonoTrampInfo));
else
copy = g_new0 (MonoTrampInfo, 1);
copy->code = info->code;
copy->code_size = info->code_size;
copy->name = mem_manager ? mono_mem_manager_strdup (mem_manager, info->name) : g_strdup (info->name);
copy->method = info->method;
if (info->unwind_ops) {
copy->uw_info = mono_unwind_ops_encode (info->unwind_ops, ©->uw_info_len);
copy->owns_uw_info = TRUE;
if (mem_manager) {
guint8 *temp = copy->uw_info;
copy->uw_info = mono_mem_manager_alloc (mem_manager, copy->uw_info_len);
memcpy (copy->uw_info, temp, copy->uw_info_len);
g_free (temp);
}
} else {
/* Trampolines from aot have the unwind ops already encoded */
copy->uw_info = info->uw_info;
copy->uw_info_len = info->uw_info_len;
}
mono_lldb_save_trampoline_info (info);
#ifdef MONO_ARCH_HAVE_UNWIND_TABLE
if (!aot)
mono_arch_unwindinfo_install_tramp_unwind_info (info->unwind_ops, info->code, info->code_size);
#endif
if (!domain) {
/* If no domain has been created yet, postpone the registration. */
mono_jit_lock ();
tramp_infos = g_slist_prepend (tramp_infos, copy);
mono_jit_unlock ();
} else if (copy->uw_info || info->method) {
/* Only register trampolines that have unwind info */
register_trampoline_jit_info (mem_manager ? mem_manager : get_default_mem_manager (), copy);
}
if (mono_jit_map_is_enabled ())
mono_emit_jit_tramp (info->code, info->code_size, info->name);
mono_tramp_info_free (info);
}
void
mono_tramp_info_register (MonoTrampInfo *info, MonoMemoryManager *mem_manager)
{
mono_tramp_info_register_internal (info, mem_manager, FALSE);
}
void
mono_aot_tramp_info_register (MonoTrampInfo *info, MonoMemoryManager *mem_manager)
{
mono_tramp_info_register_internal (info, mem_manager, TRUE);
}
/* Register trampolines created before the root domain was created in the jit info tables */
static void
register_trampolines (MonoDomain *domain)
{
GSList *l;
for (l = tramp_infos; l; l = l->next) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
register_trampoline_jit_info (get_default_mem_manager (), info);
}
}
G_GNUC_UNUSED static void
break_count (void)
{
}
/*
* Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
* Set a breakpoint in break_count () to break the last time <x> is done.
*/
G_GNUC_UNUSED gboolean
mono_debug_count (void)
{
static int count = 0, int_val = 0;
static gboolean inited, has_value = FALSE;
count ++;
if (!inited) {
char *value = g_getenv ("COUNT");
if (value) {
int_val = atoi (value);
g_free (value);
has_value = TRUE;
}
inited = TRUE;
}
if (!has_value)
return TRUE;
if (count == int_val)
break_count ();
if (count > int_val)
return FALSE;
return TRUE;
}
MonoMethod*
mono_icall_get_wrapper_method (MonoJitICallInfo* callinfo)
{
/* This icall is used to check for exceptions, so don't check in the wrapper */
gboolean check_exc = (callinfo != &mono_get_jit_icall_info ()->mono_thread_interruption_checkpoint);
return mono_marshal_get_icall_wrapper (callinfo, check_exc);
}
gconstpointer
mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
{
ERROR_DECL (error);
MonoMethod *wrapper;
gconstpointer addr, trampoline;
if (callinfo->wrapper)
return callinfo->wrapper;
wrapper = mono_icall_get_wrapper_method (callinfo);
if (do_compile) {
addr = mono_compile_method_checked (wrapper, error);
mono_error_assert_ok (error);
mono_memory_barrier ();
callinfo->wrapper = addr;
return addr;
} else {
if (callinfo->trampoline)
return callinfo->trampoline;
trampoline = mono_create_jit_trampoline (wrapper, error);
mono_error_assert_ok (error);
trampoline = mono_create_ftnptr ((gpointer)trampoline);
mono_loader_lock ();
if (!callinfo->trampoline) {
callinfo->trampoline = trampoline;
}
mono_loader_unlock ();
return callinfo->trampoline;
}
}
gconstpointer
mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
{
return mono_icall_get_wrapper_full (callinfo, FALSE);
}
static MonoJitDynamicMethodInfo*
mono_dynamic_code_hash_lookup (MonoMethod *method)
{
MonoJitDynamicMethodInfo *res;
MonoJitMemoryManager *jit_mm;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
if (jit_mm->dynamic_code_hash)
res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (jit_mm->dynamic_code_hash, method);
else
res = NULL;
jit_mm_unlock (jit_mm);
return res;
}
#ifdef __cplusplus
template <typename T>
static void
register_opcode_emulation (int opcode, MonoJitICallInfo *jit_icall_info, const char *name, MonoMethodSignature *sig, T func, const char *symbol, gboolean no_wrapper)
#else
static void
register_opcode_emulation (int opcode, MonoJitICallInfo *jit_icall_info, const char *name, MonoMethodSignature *sig, gpointer func, const char *symbol, gboolean no_wrapper)
#endif
{
#ifndef DISABLE_JIT
mini_register_opcode_emulation (opcode, jit_icall_info, name, sig, func, symbol, no_wrapper);
#else
// FIXME ifdef in mini_register_opcode_emulation and just call it.
g_assert (!sig->hasthis);
g_assert (sig->param_count < 3);
mono_register_jit_icall_info (jit_icall_info, func, name, sig, no_wrapper, symbol);
#endif
}
#define register_opcode_emulation(opcode, name, sig, func, no_wrapper) \
(register_opcode_emulation ((opcode), &mono_get_jit_icall_info ()->name, #name, (sig), func, #func, (no_wrapper)))
/*
* For JIT icalls implemented in C.
* NAME should be the same as the name of the C function whose address is FUNC.
* If @avoid_wrapper is TRUE, no wrapper is generated. This is for perf critical icalls which
* can't throw exceptions.
*
* func is an identifier, that names a function, and is also in jit-icall-reg.h,
* and therefore a field in mono_jit_icall_info and can be token pasted into an enum value.
*
* The name of func must be linkable for AOT, for example g_free does not work (monoeg_g_free instead),
* nor does the C++ overload fmod (mono_fmod instead). These functions therefore
* must be extern "C".
*/
#define register_icall(func, sig, avoid_wrapper) \
(mono_register_jit_icall_info (&mono_get_jit_icall_info ()->func, func, #func, (sig), (avoid_wrapper), #func))
#define register_icall_no_wrapper(func, sig) register_icall (func, sig, TRUE)
#define register_icall_with_wrapper(func, sig) register_icall (func, sig, FALSE)
/*
* Register an icall where FUNC is dynamically generated or otherwise not
* possible to link to it using NAME during AOT.
*
* func is an expression, such a local variable or a function call to get a function pointer.
* name is an identifier
*
* Providing func and name separately is what distinguishes "dyn" from regular.
*
* This also passes last parameter c_symbol=NULL since there is not a directly linkable symbol.
*/
#define register_dyn_icall(func, name, sig, save) \
(mono_register_jit_icall_info (&mono_get_jit_icall_info ()->name, (func), #name, (sig), (save), NULL))
MonoLMF *
mono_get_lmf (void)
{
MonoJitTlsData *jit_tls;
if ((jit_tls = mono_tls_get_jit_tls ()))
return jit_tls->lmf;
/*
* We do not assert here because this function can be called from
* mini-gc.c on a thread that has not executed any managed code, yet
* (the thread object allocation can trigger a collection).
*/
return NULL;
}
void
mono_set_lmf (MonoLMF *lmf)
{
(*mono_get_lmf_addr ()) = lmf;
}
static void
mono_set_jit_tls (MonoJitTlsData *jit_tls)
{
MonoThreadInfo *info;
mono_tls_set_jit_tls (jit_tls);
/* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
info = mono_thread_info_current ();
if (info)
mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
}
static void
mono_set_lmf_addr (MonoLMF **lmf_addr)
{
MonoThreadInfo *info;
mono_tls_set_lmf_addr (lmf_addr);
/* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
info = mono_thread_info_current ();
if (info)
mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
}
/*
* mono_push_lmf:
*
* Push an MonoLMFExt frame on the LMF stack.
*/
void
mono_push_lmf (MonoLMFExt *ext)
{
MonoLMF **lmf_addr;
lmf_addr = mono_get_lmf_addr ();
ext->lmf.previous_lmf = *lmf_addr;
/* Mark that this is a MonoLMFExt */
ext->lmf.previous_lmf = (gpointer)(((gssize)ext->lmf.previous_lmf) | 2);
mono_set_lmf ((MonoLMF*)ext);
}
/*
* mono_pop_lmf:
*
* Pop the last frame from the LMF stack.
*/
void
mono_pop_lmf (MonoLMF *lmf)
{
mono_set_lmf ((MonoLMF *)(((gssize)lmf->previous_lmf) & ~3));
}
/*
* mono_jit_thread_attach:
*
* Called by Xamarin.Mac and other products. Attach thread to runtime if
* needed and switch to @domain.
*
* This function is external only and @deprecated don't use it. Use mono_threads_attach_coop ().
*
* If the thread is newly-attached, put into GC Safe mode.
*
* @return the original domain which needs to be restored, or NULL.
*/
MonoDomain*
mono_jit_thread_attach (MonoDomain *domain)
{
gboolean attached;
if (!domain) {
/* Happens when called from AOTed code which is only used in the root domain. */
domain = mono_get_root_domain ();
}
g_assert (domain);
attached = mono_tls_get_jit_tls () != NULL;
if (!attached) {
// #678164
gboolean background = TRUE;
mono_thread_attach_external_native_thread (domain, background);
/* mono_jit_thread_attach is external-only and not called by
* the runtime on any of our own threads. So if we get here,
* the thread is running native code - leave it in GC Safe mode
* and leave it to the n2m invoke wrappers or MONO_API entry
* points to switch to GC Unsafe.
*/
MONO_STACKDATA (stackdata);
mono_threads_enter_gc_safe_region_unbalanced_internal (&stackdata);
}
return NULL;
}
/*
* mono_jit_set_domain:
*
* Set domain to @domain if @domain is not null
*/
void
mono_jit_set_domain (MonoDomain *domain)
{
g_assert (!mono_threads_is_blocking_transition_enabled ());
if (domain)
mono_domain_set_fast (domain);
}
/**
* mono_thread_abort:
* \param obj exception object
* Abort the thread, print exception information and stack trace
*/
static void
mono_thread_abort (MonoObject *obj)
{
/* MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); */
/* handle_remove should be eventually called for this thread, too
g_free (jit_tls);*/
if ((obj->vtable->klass == mono_defaults.threadabortexception_class) ||
((obj->vtable->klass) == mono_class_try_get_appdomain_unloaded_exception_class () &&
mono_thread_info_current ()->runtime_thread)) {
mono_thread_exit ();
} else {
mono_invoke_unhandled_exception_hook (obj);
}
}
static MonoJitTlsData*
setup_jit_tls_data (gpointer stack_start, MonoAbortFunction abort_func)
{
MonoJitTlsData *jit_tls;
MonoLMF *lmf;
jit_tls = mono_tls_get_jit_tls ();
if (jit_tls)
return jit_tls;
jit_tls = g_new0 (MonoJitTlsData, 1);
jit_tls->abort_func = abort_func;
jit_tls->end_of_stack = stack_start;
mono_set_jit_tls (jit_tls);
lmf = g_new0 (MonoLMF, 1);
MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
jit_tls->first_lmf = lmf;
mono_set_lmf_addr (&jit_tls->lmf);
jit_tls->lmf = lmf;
#ifdef MONO_ARCH_HAVE_TLS_INIT
mono_arch_tls_init ();
#endif
mono_setup_altstack (jit_tls);
return jit_tls;
}
static void
free_jit_tls_data (MonoJitTlsData *jit_tls)
{
//This happens during AOT cuz the thread is never attached
if (!jit_tls)
return;
mono_free_altstack (jit_tls);
if (jit_tls->interp_context)
mini_get_interp_callbacks ()->free_context (jit_tls->interp_context);
g_free (jit_tls->first_lmf);
g_free (jit_tls);
}
static void
mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
{
MonoThreadInfo *thread;
MonoJitTlsData *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
thread = mono_thread_info_current_unchecked ();
if (thread)
thread->jit_data = jit_tls;
mono_arch_cpu_init ();
}
void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
static void
mono_thread_abort_dummy (MonoObject *obj)
{
if (mono_thread_attach_aborted_cb)
mono_thread_attach_aborted_cb (obj);
else
mono_thread_abort (obj);
}
static void
mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
{
MonoThreadInfo *thread;
MonoJitTlsData *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
thread = mono_thread_info_current_unchecked ();
if (thread)
thread->jit_data = jit_tls;
mono_arch_cpu_init ();
}
static void
mini_thread_cleanup (MonoNativeThreadId tid)
{
MonoJitTlsData *jit_tls = NULL;
MonoThreadInfo *info;
info = mono_thread_info_current_unchecked ();
/* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
* It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
* not a trivial thing.
*
* The current offender is mono_thread_manage which cleanup threads from the outside.
*/
if (info && mono_thread_info_get_tid (info) == tid) {
jit_tls = info->jit_data;
info->jit_data = NULL;
mono_set_jit_tls (NULL);
/* If we attach a thread but never call into managed land, we might never get an lmf.*/
if (mono_get_lmf ()) {
mono_set_lmf (NULL);
mono_set_lmf_addr (NULL);
}
} else {
info = mono_thread_info_lookup (tid);
if (info) {
jit_tls = info->jit_data;
info->jit_data = NULL;
}
mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
}
if (jit_tls)
free_jit_tls_data (jit_tls);
}
MonoJumpInfo *
mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
{
MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
ji->ip.i = ip;
ji->type = type;
ji->data.target = target;
ji->next = list;
return ji;
}
#if !defined(DISABLE_LOGGING) && !defined(DISABLE_JIT)
static const char* const patch_info_str[] = {
#define PATCH_INFO(a,b) "" #a,
#include "patch-info.h"
#undef PATCH_INFO
};
const char*
mono_ji_type_to_string (MonoJumpInfoType type)
{
return patch_info_str [type];
}
void
mono_print_ji (const MonoJumpInfo *ji)
{
const char *type = patch_info_str [ji->type];
switch (ji->type) {
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = ji->data.rgctx_entry;
printf ("[%s ", type);
mono_print_ji (entry->data);
printf (" -> %s]", mono_rgctx_info_type_to_str (entry->info_type));
break;
}
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
char *s = mono_method_get_full_name (ji->data.method);
printf ("[%s %s]", type, s);
g_free (s);
break;
}
case MONO_PATCH_INFO_JIT_ICALL_ID:
printf ("[JIT_ICALL %s]", mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_VTABLE: {
char *name = mono_class_full_name (ji->data.klass);
printf ("[%s %s]", type, name);
g_free (name);
break;
}
default:
printf ("[%s]", type);
break;
}
}
#else
const char*
mono_ji_type_to_string (MonoJumpInfoType type)
{
return "";
}
void
mono_print_ji (const MonoJumpInfo *ji)
{
}
#endif
/**
* mono_patch_info_dup_mp:
*
* Make a copy of PATCH_INFO, allocating memory from the mempool MP.
*/
MonoJumpInfo*
mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
{
MonoJumpInfo *res = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
memcpy (res, patch_info, sizeof (MonoJumpInfo));
switch (patch_info->type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
res->data.token = (MonoJumpInfoToken *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
break;
case MONO_PATCH_INFO_SWITCH:
res->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
res->data.table->table = (MonoBasicBlock **)mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
res->data.rgctx_entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
res->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
res->data.gsharedvt = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
break;
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info;
MonoGSharedVtMethodInfo *oinfo;
int i;
oinfo = patch_info->data.gsharedvt_method;
info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
res->data.gsharedvt_method = info;
memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
for (i = 0; i < oinfo->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
memcpy (template_, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
}
//info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
//memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
break;
}
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info;
MonoJumpInfoVirtMethod *oinfo;
oinfo = patch_info->data.virt_method;
info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
res->data.virt_method = info;
memcpy (info, oinfo, sizeof (MonoJumpInfoVirtMethod));
break;
}
default:
break;
}
return res;
}
guint
mono_patch_info_hash (gconstpointer data)
{
const MonoJumpInfo *ji = (MonoJumpInfo*)data;
const MonoJumpInfoType type = ji->type;
guint hash = type << 8;
switch (type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
return hash | ji->data.token->token;
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
return hash | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: // Hash on the selector name
case MONO_PATCH_INFO_LDSTR_LIT:
return g_str_hash (ji->data.name);
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY:
case MONO_PATCH_INFO_IMAGE:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_AOT_JIT_INFO:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
return hash | (gssize)ji->data.target;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
return hash | (gssize)ji->data.gsharedvt->method;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
hash |= e->in_mrgctx | e->info_type | mono_patch_info_hash (e->data);
if (e->in_mrgctx)
return hash | (gssize)e->d.method;
else
return hash | (gssize)e->d.klass;
}
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_AOT_MODULE:
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
return hash;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return hash | ji->data.uindex;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
case MONO_PATCH_INFO_CASTCLASS_CACHE:
return hash | ji->data.index;
case MONO_PATCH_INFO_SWITCH:
return hash | ji->data.table->table_size;
case MONO_PATCH_INFO_GSHAREDVT_METHOD:
return hash | (gssize)ji->data.gsharedvt_method->method;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
return hash | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->is_virtual;
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info = ji->data.virt_method;
return hash | (gssize)info->klass | (gssize)info->method;
}
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
return hash | mono_signature_hash (ji->data.sig);
case MONO_PATCH_INFO_R8_GOT:
return hash | (guint32)*(double*)ji->data.target;
case MONO_PATCH_INFO_R4_GOT:
return hash | (guint32)*(float*)ji->data.target;
default:
printf ("info type: %d\n", ji->type);
mono_print_ji (ji); printf ("\n");
g_assert_not_reached ();
case MONO_PATCH_INFO_NONE:
return 0;
}
}
/*
* mono_patch_info_equal:
*
* This might fail to recognize equivalent patches, i.e. floats, so its only
* usable in those cases where this is not a problem, i.e. sharing GOT slots
* in AOT.
*/
gint
mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
{
const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
MonoJumpInfoType const ji1_type = ji1->type;
MonoJumpInfoType const ji2_type = ji2->type;
if (ji1_type != ji2_type)
return 0;
switch (ji1_type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
return ji1->data.token->image == ji2->data.token->image &&
ji1->data.token->token == ji2->data.token->token &&
ji1->data.token->has_context == ji2->data.token->has_context &&
ji1->data.token->context.class_inst == ji2->data.token->context.class_inst &&
ji1->data.token->context.method_inst == ji2->data.token->context.method_inst;
case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
case MONO_PATCH_INFO_LDSTR_LIT:
return g_str_equal (ji1->data.name, ji2->data.name);
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
return e1->d.method == e2->d.method && e1->d.klass == e2->d.klass && e1->in_mrgctx == e2->in_mrgctx && e1->info_type == e2->info_type && mono_patch_info_equal (e1->data, e2->data);
}
case MONO_PATCH_INFO_GSHAREDVT_CALL: {
MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
return c1->sig == c2->sig && c1->method == c2->method;
}
case MONO_PATCH_INFO_GSHAREDVT_METHOD:
return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
return ji1->data.del_tramp->klass == ji2->data.del_tramp->klass && ji1->data.del_tramp->method == ji2->data.del_tramp->method && ji1->data.del_tramp->is_virtual == ji2->data.del_tramp->is_virtual;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return ji1->data.uindex == ji2->data.uindex;
case MONO_PATCH_INFO_CASTCLASS_CACHE:
return ji1->data.index == ji2->data.index;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
return ji1->data.jit_icall_id == ji2->data.jit_icall_id;
case MONO_PATCH_INFO_VIRT_METHOD:
return ji1->data.virt_method->klass == ji2->data.virt_method->klass && ji1->data.virt_method->method == ji2->data.virt_method->method;
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
return mono_metadata_signature_equal (ji1->data.sig, ji2->data.sig);
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_NONE:
return 1;
default:
break;
}
return ji1->data.target == ji2->data.target;
}
gpointer
mono_resolve_patch_target_ext (MonoMemoryManager *mem_manager, MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error)
{
unsigned char *ip = patch_info->ip.i + code;
gconstpointer target = NULL;
error_init (error);
switch (patch_info->type) {
case MONO_PATCH_INFO_BB:
/*
* FIXME: This could be hit for methods without a prolog. Should use -1
* but too much code depends on a 0 initial value.
*/
//g_assert (patch_info->data.bb->native_offset);
target = patch_info->data.bb->native_offset + code;
break;
case MONO_PATCH_INFO_ABS:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_LABEL:
target = patch_info->data.inst->inst_c0 + code;
break;
case MONO_PATCH_INFO_IP:
target = ip;
break;
case MONO_PATCH_INFO_JIT_ICALL_ID: {
MonoJitICallInfo * const mi = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
target = mono_icall_get_wrapper (mi);
break;
}
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
MonoJitICallInfo * const mi = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
target = mi->func;
break;
}
case MONO_PATCH_INFO_METHOD_JUMP:
target = mono_create_jump_trampoline (patch_info->data.method, FALSE, error);
if (!is_ok (error))
return NULL;
break;
case MONO_PATCH_INFO_METHOD:
if (patch_info->data.method == method) {
target = code;
} else {
/* get the trampoline to the method from the domain */
target = mono_create_jit_trampoline (patch_info->data.method, error);
if (!is_ok (error))
return NULL;
}
break;
case MONO_PATCH_INFO_METHOD_FTNDESC: {
/*
* Return an ftndesc for either AOTed code, or for an interp entry.
*/
target = mini_llvmonly_load_method_ftndesc (patch_info->data.method, FALSE, FALSE, error);
return_val_if_nok (error, NULL);
break;
}
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
target = mini_get_interp_callbacks ()->create_method_pointer_llvmonly (patch_info->data.method, FALSE, error);
mono_error_assert_ok (error);
break;
}
case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
gpointer code_slot;
MonoJitMemoryManager *jit_mm = jit_mm_for_method (patch_info->data.method);
jit_mm_lock (jit_mm);
if (!jit_mm->method_code_hash)
jit_mm->method_code_hash = g_hash_table_new (NULL, NULL);
code_slot = g_hash_table_lookup (jit_mm->method_code_hash, patch_info->data.method);
if (!code_slot) {
code_slot = mono_mem_manager_alloc0 (jit_mm->mem_manager, sizeof (gpointer));
g_hash_table_insert (jit_mm->method_code_hash, patch_info->data.method, code_slot);
}
jit_mm_unlock (jit_mm);
target = code_slot;
break;
}
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE: {
target = mono_mem_manager_alloc0 (mem_manager, sizeof (gpointer));
break;
}
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
target = (gpointer)&mono_polling_required;
break;
case MONO_PATCH_INFO_SWITCH: {
#ifndef MONO_ARCH_NO_CODEMAN
gpointer *jump_table;
int i;
if (method && method->dynamic) {
jump_table = (void **)mono_code_manager_reserve (mono_dynamic_code_hash_lookup (method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
} else {
MonoMemoryManager *method_mem_manager = method ? m_method_get_mem_manager (method) : mem_manager;
if (mono_aot_only) {
jump_table = (void **)mono_mem_manager_alloc (method_mem_manager, sizeof (gpointer) * patch_info->data.table->table_size);
} else {
jump_table = (void **)mono_mem_manager_code_reserve (method_mem_manager, sizeof (gpointer) * patch_info->data.table->table_size);
}
}
mono_codeman_enable_write ();
for (i = 0; i < patch_info->data.table->table_size; i++) {
jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
}
mono_codeman_disable_write ();
target = jump_table;
#else
g_assert_not_reached ();
target = NULL;
#endif
break;
}
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IMAGE:
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_AOT_MODULE:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_IID:
mono_class_init_internal (patch_info->data.klass);
target = GUINT_TO_POINTER (m_class_get_interface_id (patch_info->data.klass));
break;
case MONO_PATCH_INFO_ADJUSTED_IID:
mono_class_init_internal (patch_info->data.klass);
target = GUINT_TO_POINTER ((guint32)(-((m_class_get_interface_id (patch_info->data.klass) + 1) * TARGET_SIZEOF_VOID_P)));
break;
case MONO_PATCH_INFO_VTABLE:
target = mono_class_vtable_checked (patch_info->data.klass, error);
mono_error_assert_ok (error);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
if (del_tramp->is_virtual)
target = mono_create_delegate_virtual_trampoline (del_tramp->klass, del_tramp->method);
else
target = mono_create_delegate_trampoline_info (del_tramp->klass, del_tramp->method);
break;
}
case MONO_PATCH_INFO_SFLDA: {
MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (patch_info->data.field), error);
mono_error_assert_ok (error);
if (mono_class_field_is_special_static (patch_info->data.field)) {
gpointer addr = mono_special_static_field_get_offset (patch_info->data.field, error);
mono_error_assert_ok (error);
g_assert (addr);
return addr;
}
if (!vtable->initialized && !mono_class_is_before_field_init (vtable->klass) && (!method || mono_class_needs_cctor_run (vtable->klass, method)))
/* Done by the generated code */
;
else {
if (run_cctors) {
if (!mono_runtime_class_init_full (vtable, error)) {
return NULL;
}
}
}
target = mono_static_field_get_addr (vtable, patch_info->data.field);
break;
}
case MONO_PATCH_INFO_RVA: {
guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
guint32 rva;
mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
target = mono_image_rva_map (patch_info->data.token->image, rva);
break;
}
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT:
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_EXC_NAME:
target = patch_info->data.name;
break;
case MONO_PATCH_INFO_LDSTR:
target =
mono_ldstr_checked (patch_info->data.token->image,
mono_metadata_token_index (patch_info->data.token->token), error);
break;
case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
gpointer handle;
MonoClass *handle_class;
handle = mono_ldtoken_checked (patch_info->data.token->image,
patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
if (!is_ok (error))
return NULL;
mono_class_init_internal (handle_class);
mono_class_init_internal (mono_class_from_mono_type_internal ((MonoType *)handle));
target = mono_type_get_object_checked ((MonoType *)handle, error);
if (!is_ok (error))
return NULL;
break;
}
case MONO_PATCH_INFO_LDTOKEN: {
gpointer handle;
MonoClass *handle_class;
handle = mono_ldtoken_checked (patch_info->data.token->image,
patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
mono_error_assert_msg_ok (error, "Could not patch ldtoken");
mono_class_init_internal (handle_class);
target = handle;
break;
}
case MONO_PATCH_INFO_DECLSEC:
target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
break;
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
/* run_cctors == 0 -> AOT */
if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
if (run_cctors) {
target = mono_lookup_pinvoke_call_internal (patch_info->data.method, error);
if (!target) {
if (mono_aot_only)
return NULL;
g_error ("Unable to resolve pinvoke method '%s' Re-run with MONO_LOG_LEVEL=debug for more information.\n", mono_method_full_name (patch_info->data.method, TRUE));
}
} else {
target = NULL;
}
} else {
target = mono_lookup_internal_call (patch_info->data.method);
if (mono_is_missing_icall_addr (target) && run_cctors)
g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
}
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
target = &mono_thread_interruption_request_flag;
break;
case MONO_PATCH_INFO_METHOD_RGCTX:
target = mini_method_get_rgctx (patch_info->data.method);
break;
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
target = GINT_TO_POINTER (MONO_RGCTX_SLOT_INDEX (slot));
break;
}
case MONO_PATCH_INFO_BB_OVF:
case MONO_PATCH_INFO_EXC_OVF:
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_RGCTX_FETCH: {
int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
target = mono_create_rgctx_lazy_fetch_trampoline (slot);
break;
}
#ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
case MONO_PATCH_INFO_SEQ_POINT_INFO:
if (!run_cctors)
/* AOT, not needed */
target = NULL;
else
target = mono_arch_get_seq_point_info (code);
break;
#endif
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
int card_table_shift_bits;
gpointer card_table_mask;
target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
break;
}
case MONO_PATCH_INFO_GC_NURSERY_START: {
int shift_bits;
size_t size;
target = mono_gc_get_nursery (&shift_bits, &size);
break;
}
case MONO_PATCH_INFO_GC_NURSERY_BITS: {
int shift_bits;
size_t size;
mono_gc_get_nursery (&shift_bits, &size);
target = (gpointer)(gssize)shift_bits;
break;
}
case MONO_PATCH_INFO_CASTCLASS_CACHE: {
target = mono_mem_manager_alloc0 (mem_manager, sizeof (gpointer));
break;
}
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
target = NULL;
break;
}
case MONO_PATCH_INFO_LDSTR_LIT: {
int len;
char *s;
len = strlen ((const char *)patch_info->data.target);
s = (char *)mono_mem_manager_alloc0 (mem_manager, len + 1);
memcpy (s, patch_info->data.target, len);
target = s;
break;
}
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
target = mini_get_gsharedvt_wrapper (TRUE, NULL, patch_info->data.sig, NULL, -1, FALSE);
break;
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT: {
target = (gpointer) &mono_profiler_state.gc_allocation_count;
break;
}
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT: {
target = (gpointer) &mono_profiler_state.exception_clause_count;
break;
}
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE: {
/* Resolved in aot-runtime.c */
g_assert_not_reached ();
target = NULL;
break;
}
default:
g_assert_not_reached ();
}
return (gpointer)target;
}
gpointer
mono_resolve_patch_target (MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error)
{
return mono_resolve_patch_target_ext (get_default_mem_manager (), method, code, patch_info, run_cctors, error);
}
/*
* mini_register_jump_site:
*
* Register IP as a jump/tailcall site which calls METHOD.
* This is needed because common_call_trampoline () cannot patch
* the call site because the caller ip is not available for jumps.
*/
void
mini_register_jump_site (MonoMethod *method, gpointer ip)
{
MonoJumpList *jlist;
MonoJitMemoryManager *jit_mm;
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
jlist = (MonoJumpList *)g_hash_table_lookup (jit_mm->jump_target_hash, method);
if (!jlist) {
jlist = (MonoJumpList *)mono_mem_manager_alloc0 (jit_mm->mem_manager, sizeof (MonoJumpList));
g_hash_table_insert (jit_mm->jump_target_hash, method, jlist);
}
jlist->list = g_slist_prepend (jlist->list, ip);
jit_mm_unlock (jit_mm);
}
/*
* mini_patch_jump_sites:
*
* Patch jump/tailcall sites calling METHOD so the jump to ADDR.
*/
void
mini_patch_jump_sites (MonoMethod *method, gpointer addr)
{
MonoJitMemoryManager *jit_mm;
MonoJumpInfo patch_info;
MonoJumpList *jlist;
GSList *tmp;
/* The caller/callee might use different instantiations */
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
jlist = (MonoJumpList *)g_hash_table_lookup (jit_mm->jump_target_hash, method);
if (jlist)
g_hash_table_remove (jit_mm->jump_target_hash, method);
jit_mm_unlock (jit_mm);
if (jlist) {
patch_info.next = NULL;
patch_info.ip.i = 0;
patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
patch_info.data.method = method;
mono_codeman_enable_write ();
for (tmp = jlist->list; tmp; tmp = tmp->next)
mono_arch_patch_code_new (NULL, (guint8 *)tmp->data, &patch_info, addr);
mono_codeman_disable_write ();
}
}
/*
* mini_patch_llvm_jit_callees:
*
* Patch function address slots used by llvm JITed code.
*/
void
mini_patch_llvm_jit_callees (MonoMethod *method, gpointer addr)
{
MonoJitMemoryManager *jit_mm;
// FIXME:
jit_mm = get_default_jit_mm ();
if (!jit_mm->llvm_jit_callees)
return;
jit_mm_lock (jit_mm);
GSList *callees = (GSList*)g_hash_table_lookup (jit_mm->llvm_jit_callees, method);
GSList *l;
for (l = callees; l; l = l->next) {
gpointer *slot = (gpointer*)l->data;
*slot = addr;
}
jit_mm_unlock (jit_mm);
}
void
mini_init_gsctx (MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
{
MonoGenericInst *inst;
int i;
memset (gsctx, 0, sizeof (MonoGenericSharingContext));
if (context && context->class_inst) {
inst = context->class_inst;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *type = inst->type_argv [i];
if (mini_is_gsharedvt_gparam (type))
gsctx->is_gsharedvt = TRUE;
}
}
if (context && context->method_inst) {
inst = context->method_inst;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *type = inst->type_argv [i];
if (mini_is_gsharedvt_gparam (type))
gsctx->is_gsharedvt = TRUE;
}
}
}
/*
* LOCKING: Acquires the jit code hash lock.
*/
MonoJitInfo*
mini_lookup_method (MonoMethod *method, MonoMethod *shared)
{
MonoJitInfo *ji;
MonoJitMemoryManager *jit_mm = jit_mm_for_method (method);
static gboolean inited = FALSE;
static int lookups = 0;
static int failed_lookups = 0;
jit_code_hash_lock (jit_mm);
ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&jit_mm->jit_code_hash, method);
jit_code_hash_unlock (jit_mm);
if (!ji && shared) {
jit_mm = jit_mm_for_method (shared);
jit_code_hash_lock (jit_mm);
/* Try generic sharing */
ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&jit_mm->jit_code_hash, shared);
if (ji && !ji->has_generic_jit_info)
ji = NULL;
if (!inited) {
mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
inited = TRUE;
}
++lookups;
if (!ji)
++failed_lookups;
jit_code_hash_unlock (jit_mm);
}
return ji;
}
static MonoJitInfo*
lookup_method (MonoMethod *method)
{
ERROR_DECL (error);
MonoJitInfo *ji;
MonoMethod *shared;
ji = mini_lookup_method (method, NULL);
if (!ji) {
if (!mono_method_is_generic_sharable (method, FALSE))
return NULL;
shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
mono_error_assert_ok (error);
ji = mini_lookup_method (method, shared);
}
return ji;
}
MonoClass*
mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
{
ERROR_DECL (error);
MonoClass *klass;
if (method->wrapper_type != MONO_WRAPPER_NONE) {
klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
if (context) {
klass = mono_class_inflate_generic_class_checked (klass, context, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
} else {
klass = mono_class_get_and_inflate_typespec_checked (m_class_get_image (method->klass), token, context, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
if (klass)
mono_class_init_internal (klass);
return klass;
}
#if ENABLE_JIT_MAP
static FILE* perf_map_file;
void
mono_enable_jit_map (void)
{
if (!perf_map_file) {
char name [64];
g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
unlink (name);
perf_map_file = fopen (name, "w");
}
}
void
mono_emit_jit_tramp (void *start, int size, const char *desc)
{
if (perf_map_file)
fprintf (perf_map_file, "%" PRIx64 " %x %s\n", (guint64)(gsize)start, size, desc);
}
void
mono_emit_jit_map (MonoJitInfo *jinfo)
{
if (perf_map_file) {
char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
g_free (name);
}
}
gboolean
mono_jit_map_is_enabled (void)
{
return perf_map_file != NULL;
}
#endif
#ifdef ENABLE_JIT_DUMP
#include <sys/mman.h>
#include <sys/syscall.h>
#include <elf.h>
static FILE *perf_dump_file;
static mono_mutex_t perf_dump_mutex;
static void *perf_dump_mmap_addr = MAP_FAILED;
static guint32 perf_dump_pid;
static clockid_t clock_id = CLOCK_MONOTONIC;
enum {
JIT_DUMP_MAGIC = 0x4A695444,
JIT_DUMP_VERSION = 2,
#if HOST_X86
ELF_MACHINE = EM_386,
#elif HOST_AMD64
ELF_MACHINE = EM_X86_64,
#elif HOST_ARM
ELF_MACHINE = EM_ARM,
#elif HOST_ARM64
ELF_MACHINE = EM_AARCH64,
#elif HOST_POWERPC64
ELF_MACHINE = EM_PPC64,
#elif HOST_S390X
ELF_MACHINE = EM_S390,
#elif HOST_RISCV
ELF_MACHINE = EM_RISCV,
#elif HOST_MIPS
ELF_MACHINE = EM_MIPS,
#endif
JIT_CODE_LOAD = 0
};
typedef struct
{
guint32 magic;
guint32 version;
guint32 total_size;
guint32 elf_mach;
guint32 pad1;
guint32 pid;
guint64 timestamp;
guint64 flags;
} FileHeader;
typedef struct
{
guint32 id;
guint32 total_size;
guint64 timestamp;
} RecordHeader;
typedef struct
{
RecordHeader header;
guint32 pid;
guint32 tid;
guint64 vma;
guint64 code_addr;
guint64 code_size;
guint64 code_index;
// Null terminated function name
// Native code
} JitCodeLoadRecord;
static void add_file_header_info (FileHeader *header);
static void add_basic_JitCodeLoadRecord_info (JitCodeLoadRecord *record);
void
mono_enable_jit_dump (void)
{
if (perf_dump_pid == 0)
perf_dump_pid = getpid();
if (!perf_dump_file) {
char name [64];
FileHeader header;
memset (&header, 0, sizeof (header));
mono_os_mutex_init (&perf_dump_mutex);
mono_os_mutex_lock (&perf_dump_mutex);
g_snprintf (name, sizeof (name), "/tmp/jit-%d.dump", perf_dump_pid);
unlink (name);
perf_dump_file = fopen (name, "w");
add_file_header_info (&header);
if (perf_dump_file) {
fwrite (&header, sizeof (header), 1, perf_dump_file);
//This informs perf of the presence of the jitdump file and support for the feature.
perf_dump_mmap_addr = mmap (NULL, sizeof (header), PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno (perf_dump_file), 0);
}
mono_os_mutex_unlock (&perf_dump_mutex);
}
}
static void
add_file_header_info (FileHeader *header)
{
header->magic = JIT_DUMP_MAGIC;
header->version = JIT_DUMP_VERSION;
header->total_size = sizeof (header);
header->elf_mach = ELF_MACHINE;
header->pad1 = 0;
header->pid = perf_dump_pid;
header->timestamp = mono_clock_get_time_ns (clock_id);
header->flags = 0;
}
void
mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code)
{
static uint64_t code_index;
if (perf_dump_file) {
JitCodeLoadRecord record;
size_t nameLen = strlen (jinfo->d.method->name);
memset (&record, 0, sizeof (record));
add_basic_JitCodeLoadRecord_info (&record);
record.header.total_size = sizeof (record) + nameLen + 1 + jinfo->code_size;
record.vma = (guint64)jinfo->code_start;
record.code_addr = (guint64)jinfo->code_start;
record.code_size = (guint64)jinfo->code_size;
mono_os_mutex_lock (&perf_dump_mutex);
record.code_index = ++code_index;
// TODO: write debugInfo and unwindInfo immediately before the JitCodeLoadRecord (while lock is held).
record.header.timestamp = mono_clock_get_time_ns (clock_id);
fwrite (&record, sizeof (record), 1, perf_dump_file);
fwrite (jinfo->d.method->name, nameLen + 1, 1, perf_dump_file);
fwrite (code, jinfo->code_size, 1, perf_dump_file);
mono_os_mutex_unlock (&perf_dump_mutex);
}
}
static void
add_basic_JitCodeLoadRecord_info (JitCodeLoadRecord *record)
{
record->header.id = JIT_CODE_LOAD;
record->header.timestamp = mono_clock_get_time_ns (clock_id);
record->pid = perf_dump_pid;
record->tid = syscall (SYS_gettid);
}
void
mono_jit_dump_cleanup (void)
{
if (perf_dump_mmap_addr != MAP_FAILED)
munmap (perf_dump_mmap_addr, sizeof(FileHeader));
if (perf_dump_file)
fclose (perf_dump_file);
}
#else
void
mono_enable_jit_dump (void)
{
}
void
mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code)
{
}
void
mono_jit_dump_cleanup (void)
{
}
#endif
static void
no_gsharedvt_in_wrapper (void)
{
g_assert_not_reached ();
}
/*
Overall algorithm:
When a JIT request is made, we check if there's an outstanding one for that method and, if it exits, put the thread to sleep.
If the current thread is already JITing another method, don't wait as it might cause a deadlock.
Dependency management in this case is too complex to justify implementing it.
If there are no outstanding requests, the current thread is doing nothing and there are already mono_cpu_count threads JITing, go to sleep.
TODO:
Get rid of cctor invocations from within the JIT, it increases JIT duration and complicates things A LOT.
Can we get rid of ref_count and use `done && threads_waiting == 0` as the equivalent of `ref_count == 0`?
Reduce amount of dynamically allocated - possible once the JIT is no longer reentrant
Maybe pool JitCompilationEntry, specially those with an inited cond var;
*/
typedef struct {
MonoMethod *method;
int compilation_count; /* Number of threads compiling this method - This happens due to the JIT being reentrant */
int ref_count; /* Number of threads using this JitCompilationEntry, roughtly 1 + threads_waiting */
int threads_waiting; /* Number of threads waiting on this job */
gboolean has_cond; /* True if @cond was initialized */
gboolean done; /* True if the method finished JIT'ing */
MonoCoopCond cond; /* Cond sleeping threads wait one */
} JitCompilationEntry;
typedef struct {
GPtrArray *in_flight_methods; //JitCompilationEntry*
MonoCoopMutex lock;
} JitCompilationData;
/*
Timeout, in millisecounds, that we wait other threads to finish JITing.
This value can't be too small or we won't see enough methods being reused and it can't be too big to cause massive stalls due to unforseable circunstances.
*/
#define MAX_JIT_TIMEOUT_MS 1000
static JitCompilationData compilation_data;
static int jit_methods_waited, jit_methods_multiple, jit_methods_overload, jit_spurious_wakeups_or_timeouts;
static void
mini_jit_init_job_control (void)
{
mono_coop_mutex_init (&compilation_data.lock);
compilation_data.in_flight_methods = g_ptr_array_new ();
}
static void
lock_compilation_data (void)
{
mono_coop_mutex_lock (&compilation_data.lock);
}
static void
unlock_compilation_data (void)
{
mono_coop_mutex_unlock (&compilation_data.lock);
}
static JitCompilationEntry*
find_method (MonoMethod *method)
{
int i;
for (i = 0; i < compilation_data.in_flight_methods->len; ++i){
JitCompilationEntry *e = (JitCompilationEntry*)compilation_data.in_flight_methods->pdata [i];
if (e->method == method)
return e;
}
return NULL;
}
static void
add_current_thread (MonoJitTlsData *jit_tls)
{
++jit_tls->active_jit_methods;
}
static void
unref_jit_entry (JitCompilationEntry *entry)
{
--entry->ref_count;
if (entry->ref_count)
return;
if (entry->has_cond)
mono_coop_cond_destroy (&entry->cond);
g_free (entry);
}
/*
* Returns true if this method waited successfully for another thread to JIT it
*/
static gboolean
wait_or_register_method_to_compile (MonoMethod *method)
{
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
JitCompilationEntry *entry;
static gboolean inited;
if (!inited) {
mono_counters_register ("JIT compile waited others", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_waited);
mono_counters_register ("JIT compile 1+ jobs", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_multiple);
mono_counters_register ("JIT compile overload wait", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_overload);
mono_counters_register ("JIT compile spurious wakeups or timeouts", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_spurious_wakeups_or_timeouts);
inited = TRUE;
}
lock_compilation_data ();
if (!(entry = find_method (method))) {
entry = g_new0 (JitCompilationEntry, 1);
entry->method = method;
entry->compilation_count = entry->ref_count = 1;
g_ptr_array_add (compilation_data.in_flight_methods, entry);
g_assert (find_method (method) == entry);
add_current_thread (jit_tls);
unlock_compilation_data ();
return FALSE;
} else if (jit_tls->active_jit_methods > 0 || mono_threads_is_current_thread_in_protected_block ()) {
//We can't suspend the current thread if it's already JITing a method.
//Dependency management is too compilated and we want to get rid of this anyways.
//We can't suspend the current thread if it's running a protected block (such as a cctor)
//We can't rely only on JIT nesting as cctor's can be run from outside the JIT.
//Finally, he hit a timeout or spurious wakeup. We're better off just giving up and keep recompiling
++entry->compilation_count;
++jit_methods_multiple;
++jit_tls->active_jit_methods;
unlock_compilation_data ();
return FALSE;
} else {
++jit_methods_waited;
++entry->ref_count;
if (!entry->has_cond) {
mono_coop_cond_init (&entry->cond);
entry->has_cond = TRUE;
}
while (TRUE) {
++entry->threads_waiting;
g_assert (entry->has_cond);
mono_coop_cond_timedwait (&entry->cond, &compilation_data.lock, MAX_JIT_TIMEOUT_MS);
--entry->threads_waiting;
if (entry->done) {
unref_jit_entry (entry);
unlock_compilation_data ();
return TRUE;
} else {
//We hit the timeout or a spurious wakeup, fallback to JITing
g_assert (entry->ref_count > 1);
unref_jit_entry (entry);
++jit_spurious_wakeups_or_timeouts;
++entry->compilation_count;
++jit_methods_multiple;
++jit_tls->active_jit_methods;
unlock_compilation_data ();
return FALSE;
}
}
}
}
static void
unregister_method_for_compile (MonoMethod *method)
{
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
lock_compilation_data ();
g_assert (jit_tls->active_jit_methods > 0);
--jit_tls->active_jit_methods;
JitCompilationEntry *entry = find_method (method);
g_assert (entry); // It would be weird to fail
entry->done = TRUE;
if (entry->threads_waiting) {
g_assert (entry->has_cond);
mono_coop_cond_broadcast (&entry->cond);
}
if (--entry->compilation_count == 0) {
g_ptr_array_remove (compilation_data.in_flight_methods, entry);
unref_jit_entry (entry);
}
unlock_compilation_data ();
}
static MonoJitInfo*
create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
{
MonoJitInfo *jinfo;
guint8 *uw_info;
guint32 info_len;
if (info->uw_info) {
uw_info = info->uw_info;
info_len = info->uw_info_len;
} else {
uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
}
jinfo = (MonoJitInfo *)mono_mem_manager_alloc0 (get_default_mem_manager (), MONO_SIZEOF_JIT_INFO);
jinfo->d.method = wrapper;
jinfo->code_start = MINI_FTNPTR_TO_ADDR (info->code);
jinfo->code_size = info->code_size;
jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
if (!info->uw_info)
g_free (uw_info);
return jinfo;
}
static gpointer
compile_special (MonoMethod *method, MonoError *error)
{
MonoJitInfo *jinfo;
gpointer code;
if (mono_llvm_only) {
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
/*
* These wrappers are only created for signatures which are in the program, but
* sometimes we load methods too eagerly and have to create them even if they
* will never be called.
*/
return (gpointer)no_gsharedvt_in_wrapper;
}
}
}
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
if (!piinfo->addr) {
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
guint32 flags = MONO_ICALL_FLAGS_NONE;
gpointer icall_addr;
icall_addr = (gpointer)mono_lookup_internal_call_full_with_flags (method, TRUE, (guint32 *)&flags);
if (flags & MONO_ICALL_FLAGS_NO_WRAPPER) {
piinfo->icflags = MONO_ICALL_FLAGS_NO_WRAPPER;
mono_memory_write_barrier ();
}
piinfo->addr = icall_addr;
} else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE) {
#ifdef HOST_WIN32
g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), m_class_get_image (method->klass)->name);
#else
g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), m_class_get_image (method->klass)->name);
#endif
} else {
ERROR_DECL (ignored_error);
mono_lookup_pinvoke_call_internal (method, ignored_error);
mono_error_cleanup (ignored_error);
}
}
mono_memory_read_barrier ();
gpointer compiled_method = NULL;
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && (piinfo->icflags & MONO_ICALL_FLAGS_NO_WRAPPER)) {
compiled_method = piinfo->addr;
} else {
MonoMethod *nm = mono_marshal_get_native_wrapper (method, TRUE, mono_aot_only);
compiled_method = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
}
code = mono_get_addr_from_ftnptr (compiled_method);
jinfo = mini_jit_info_table_find (code);
if (jinfo)
MONO_PROFILER_RAISE (jit_done, (method, jinfo));
return code;
} else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
const char *name = method->name;
char *full_name;
MonoMethod *nm;
if (m_class_get_parent (method->klass) == mono_defaults.multicastdelegate_class) {
if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
MonoJitICallInfo *mi = &mono_get_jit_icall_info ()->ves_icall_mono_delegate_ctor;
/*
* We need to make sure this wrapper
* is compiled because it might end up
* in an (M)RGCTX if generic sharing
* is enabled, and would be called
* indirectly. If it were a
* trampoline we'd try to patch that
* indirect call, which is not
* possible.
*/
return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
} else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
if (mono_llvm_only) {
nm = mono_marshal_get_delegate_invoke (method, NULL);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
}
/* HACK: missing gsharedvt_out wrappers to do transition to del tramp in interp-only mode */
if (mono_use_interpreter)
return NULL;
return mono_create_delegate_trampoline (method->klass);
} else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
nm = mono_marshal_get_delegate_begin_invoke (method);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
} else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
nm = mono_marshal_get_delegate_end_invoke (method);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
}
}
full_name = mono_method_full_name (method, TRUE);
mono_error_set_invalid_program (error, "Unrecognizable runtime implemented method '%s'", full_name);
g_free (full_name);
return NULL;
}
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
static MonoTrampInfo *in_tinfo, *out_tinfo;
MonoTrampInfo *tinfo;
MonoJitInfo *jinfo;
gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
if (is_in && in_tinfo)
return in_tinfo->code;
else if (!is_in && out_tinfo)
return out_tinfo->code;
/*
* This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
* works.
* FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
*/
if (mono_ee_features.use_aot_trampolines)
mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
else
mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
jinfo = create_jit_info_for_trampoline (method, tinfo);
mono_jit_info_table_add (jinfo);
if (is_in)
in_tinfo = tinfo;
else
out_tinfo = tinfo;
return tinfo->code;
}
}
return NULL;
}
static gpointer
mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, gboolean jit_only, MonoError *error)
{
MonoJitInfo *info;
gpointer code = NULL, p;
MonoJitICallInfo *callinfo = NULL;
WrapperInfo *winfo = NULL;
gboolean use_interp = FALSE;
error_init (error);
if (mono_ee_features.force_use_interpreter && !jit_only)
use_interp = TRUE;
if (!use_interp && mono_interp_only_classes) {
for (GSList *l = mono_interp_only_classes; l; l = l->next) {
if (!strcmp (m_class_get_name (method->klass), (char*)l->data))
use_interp = TRUE;
}
}
if (use_interp) {
code = mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
if (code)
return code;
return_val_if_nok (error, NULL);
}
if (mono_llvm_only)
/* Should be handled by the caller */
g_assert (!(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED));
/*
* ICALL wrappers are handled specially, since there is only one copy of them
* shared by all appdomains.
*/
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
winfo = mono_marshal_get_wrapper_info (method);
if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER)
callinfo = mono_find_jit_icall_info (winfo->d.icall.jit_icall_id);
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
g_assert (info);
if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
MonoGenericContext *ctx = NULL;
if (method->is_inflated)
ctx = mono_method_get_context (method);
method = info->d.synchronized_inner.method;
if (ctx) {
method = mono_class_inflate_generic_method_checked (method, ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
}
}
lookup_start:
info = lookup_method (method);
if (info) {
MonoVTable *vtable;
mono_atomic_inc_i32 (&mono_jit_stats.methods_lookups);
vtable = mono_class_vtable_checked (method->klass, error);
if (!is_ok (error))
return NULL;
g_assert (vtable);
if (!mono_runtime_class_init_full (vtable, error))
return NULL;
code = MINI_ADDR_TO_FTNPTR (info->code_start);
return mono_create_ftnptr (code);
}
#ifdef MONO_USE_AOT_COMPILER
if (opt & MONO_OPT_AOT) {
mono_class_init_internal (method->klass);
code = mono_aot_get_method (method, error);
if (code) {
MonoVTable *vtable;
if (mono_gc_is_critical_method (method)) {
/*
* The suspend code needs to be able to lookup these methods by ip in async context,
* so preload their jit info.
*/
MonoJitInfo *ji = mini_jit_info_table_find (code);
g_assert (ji);
}
/*
* In llvm-only mode, method might be a shared method, so we can't initialize its class.
* This is not a problem, since it will be initialized when the method is first
* called by init_method ().
*/
if (!mono_llvm_only && !mono_class_is_open_constructed_type (m_class_get_byval_arg (method->klass))) {
vtable = mono_class_vtable_checked (method->klass, error);
mono_error_assert_ok (error);
if (!mono_runtime_class_init_full (vtable, error))
return NULL;
}
}
if (!is_ok (error))
return NULL;
}
#endif
if (!code) {
code = compile_special (method, error);
if (!is_ok (error))
return NULL;
}
if (!jit_only && !code && mono_aot_only && mono_use_interpreter && method->wrapper_type != MONO_WRAPPER_OTHER) {
if (mono_llvm_only) {
/* Signal to the caller that AOTed code is not found */
return NULL;
}
code = mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
if (!is_ok (error))
return NULL;
}
if (!code) {
if (mono_class_is_open_constructed_type (m_class_get_byval_arg (method->klass))) {
char *full_name = mono_type_get_full_name (method->klass);
mono_error_set_invalid_operation (error, "Could not execute the method because the containing type '%s', is not fully instantiated.", full_name);
g_free (full_name);
return NULL;
}
if (mono_aot_only) {
char *fullname = mono_method_get_full_name (method);
mono_error_set_execution_engine (error, "Attempting to JIT compile method '%s' while running in aot-only mode. See https://docs.microsoft.com/xamarin/ios/internals/limitations for more information.\n", fullname);
g_free (fullname);
return NULL;
}
if (wait_or_register_method_to_compile (method))
goto lookup_start;
code = mono_jit_compile_method_inner (method, opt, error);
unregister_method_for_compile (method);
}
if (!is_ok (error))
return NULL;
if (!code && mono_llvm_only) {
printf ("AOT method not found in llvmonly mode: %s\n", mono_method_full_name (method, 1));
g_assert_not_reached ();
}
if (!code)
return NULL;
//FIXME mini_jit_info_table_find doesn't work yet under wasm due to code_start/code_end issues.
#ifndef HOST_WASM
if ((method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC)) {
/*
* SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
*/
MonoJitInfo *ji = mini_jit_info_table_find (code);
g_assert (ji);
}
#endif
p = mono_create_ftnptr (code);
if (callinfo) {
// FIXME Locking here is somewhat historical due to mono_register_jit_icall_wrapper taking loader lock.
// atomic_compare_exchange should suffice.
mono_loader_lock ();
mono_jit_lock ();
if (!callinfo->wrapper) {
callinfo->wrapper = p;
}
mono_jit_unlock ();
mono_loader_unlock ();
}
// FIXME p or callinfo->wrapper or does not matter?
return p;
}
typedef struct {
MonoMethod *method;
guint32 opt;
gboolean jit_only;
MonoError *error;
gpointer code;
} JitCompileMethodWithOptCallbackData;
static void
jit_compile_method_with_opt_cb (gpointer arg)
{
JitCompileMethodWithOptCallbackData *params = (JitCompileMethodWithOptCallbackData *)arg;
params->code = mono_jit_compile_method_with_opt (params->method, params->opt, params->jit_only, params->error);
}
static gpointer
jit_compile_method_with_opt (JitCompileMethodWithOptCallbackData *params)
{
MonoLMFExt ext;
memset (&ext, 0, sizeof (MonoLMFExt));
ext.kind = MONO_LMFEXT_JIT_ENTRY;
mono_push_lmf (&ext);
gboolean thrown = FALSE;
#if defined(ENABLE_LLVM_RUNTIME) || defined(ENABLE_LLVM)
mono_llvm_cpp_catch_exception (jit_compile_method_with_opt_cb, params, &thrown);
#else
jit_compile_method_with_opt_cb (params);
#endif
mono_pop_lmf (&ext.lmf);
return !thrown ? params->code : NULL;
}
gpointer
mono_jit_compile_method (MonoMethod *method, MonoError *error)
{
JitCompileMethodWithOptCallbackData params;
params.method = method;
params.opt = mono_get_optimizations_for_method (method, default_opt);
params.jit_only = FALSE;
params.error = error;
params.code = NULL;
return jit_compile_method_with_opt (¶ms);
}
/*
* mono_jit_compile_method_jit_only:
*
* Compile METHOD using the JIT/AOT, even in interpreted mode.
*/
gpointer
mono_jit_compile_method_jit_only (MonoMethod *method, MonoError *error)
{
JitCompileMethodWithOptCallbackData params;
params.method = method;
params.opt = mono_get_optimizations_for_method (method, default_opt);
params.jit_only = TRUE;
params.error = error;
params.code = NULL;
return jit_compile_method_with_opt (¶ms);
}
/*
* get_ftnptr_for_method:
*
* Return a function pointer for METHOD which is indirectly callable from managed code.
* On llvmonly, this returns a MonoFtnDesc, otherwise it returns a normal function pointer.
*/
static gpointer
get_ftnptr_for_method (MonoMethod *method, MonoError *error)
{
if (!mono_llvm_only) {
return mono_jit_compile_method (method, error);
} else {
return mini_llvmonly_load_method_ftndesc (method, FALSE, FALSE, error);
}
}
#ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
static void
invalidated_delegate_trampoline (char *desc)
{
g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
"See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
desc);
}
#endif
/*
* mono_jit_free_method:
*
* Free all memory allocated by the JIT for METHOD.
*/
static void
mono_jit_free_method (MonoMethod *method)
{
MonoJitDynamicMethodInfo *ji;
gboolean destroy = TRUE, removed;
GHashTableIter iter;
MonoJumpList *jlist;
MonoJitMemoryManager *jit_mm;
g_assert (method->dynamic);
if (mono_use_interpreter)
mini_get_interp_callbacks ()->free_method (method);
ji = mono_dynamic_code_hash_lookup (method);
if (!ji)
return;
mono_debug_remove_method (method, NULL);
mono_lldb_remove_method (method, ji);
//seq_points are always on get_default_jit_mm
jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_remove (jit_mm->seq_points, method);
jit_mm_unlock (jit_mm);
jit_mm = jit_mm_for_method (method);
jit_code_hash_lock (jit_mm);
removed = mono_internal_hash_table_remove (&jit_mm->jit_code_hash, method);
g_assert (removed);
jit_code_hash_unlock (jit_mm);
ji->ji->seq_points = NULL;
jit_mm_lock (jit_mm);
mono_conc_hashtable_remove (jit_mm->runtime_invoke_hash, method);
g_hash_table_remove (jit_mm->dynamic_code_hash, method);
g_hash_table_remove (jit_mm->jump_trampoline_hash, method);
g_hash_table_remove (jit_mm->seq_points, method);
g_hash_table_iter_init (&iter, jit_mm->jump_target_hash);
while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
GSList *tmp, *remove;
remove = NULL;
for (tmp = jlist->list; tmp; tmp = tmp->next) {
guint8 *ip = (guint8 *)tmp->data;
if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
remove = g_slist_prepend (remove, tmp);
}
for (tmp = remove; tmp; tmp = tmp->next) {
jlist->list = g_slist_delete_link ((GSList *)jlist->list, (GSList *)tmp->data);
}
g_slist_free (remove);
}
jit_mm_unlock (jit_mm);
#ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
if (mini_debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
/*
* Instead of freeing the code, change it to call an error routine
* so people can fix their code.
*/
char *type = mono_type_full_name (m_class_get_byval_arg (method->klass));
char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
g_free (type);
mono_arch_invalidate_method (ji->ji, (gpointer)invalidated_delegate_trampoline, (gpointer)type_and_method);
destroy = FALSE;
}
#endif
/*
* This needs to be done before freeing code_mp, since the code address is the
* key in the table, so if we free the code_mp first, another thread can grab the
* same code address and replace our entry in the table.
*/
mono_jit_info_table_remove (ji->ji);
if (destroy)
mono_code_manager_destroy (ji->code_mp);
g_free (ji);
}
gpointer
mono_jit_search_all_backends_for_jit_info (MonoMethod *method, MonoJitInfo **out_ji)
{
gpointer code;
MonoJitInfo *ji;
code = mono_jit_find_compiled_method_with_jit_info (method, &ji);
if (!code) {
ERROR_DECL (oerror);
/* Might be AOTed code */
mono_class_init_internal (method->klass);
code = mono_aot_get_method (method, oerror);
if (code) {
mono_error_assert_ok (oerror);
ji = mini_jit_info_table_find (code);
} else {
if (!is_ok (oerror))
mono_error_cleanup (oerror);
/* Might be interpreted */
ji = mini_get_interp_callbacks ()->find_jit_info (method);
}
}
*out_ji = ji;
return code;
}
gpointer
mono_jit_find_compiled_method_with_jit_info (MonoMethod *method, MonoJitInfo **ji)
{
MonoJitInfo *info;
info = lookup_method (method);
if (info) {
mono_atomic_inc_i32 (&mono_jit_stats.methods_lookups);
if (ji)
*ji = info;
return MINI_ADDR_TO_FTNPTR (info->code_start);
}
if (ji)
*ji = NULL;
return NULL;
}
static guint32 bisect_opt = 0;
static GHashTable *bisect_methods_hash = NULL;
void
mono_set_bisect_methods (guint32 opt, const char *method_list_filename)
{
FILE *file;
char method_name [2048];
bisect_opt = opt;
bisect_methods_hash = g_hash_table_new (g_str_hash, g_str_equal);
g_assert (bisect_methods_hash);
file = fopen (method_list_filename, "r");
g_assert (file);
while (fgets (method_name, sizeof (method_name), file)) {
size_t len = strlen (method_name);
g_assert (len > 0);
g_assert (method_name [len - 1] == '\n');
method_name [len - 1] = 0;
g_hash_table_insert (bisect_methods_hash, g_strdup (method_name), GINT_TO_POINTER (1));
}
g_assert (feof (file));
}
gboolean mono_do_single_method_regression = FALSE;
guint32 mono_single_method_regression_opt = 0;
MonoMethod *mono_current_single_method;
GSList *mono_single_method_list;
GHashTable *mono_single_method_hash;
guint32
mono_get_optimizations_for_method (MonoMethod *method, guint32 opt)
{
g_assert (method);
if (bisect_methods_hash) {
char *name = mono_method_full_name (method, TRUE);
void *res = g_hash_table_lookup (bisect_methods_hash, name);
g_free (name);
if (res)
return opt | bisect_opt;
}
if (!mono_do_single_method_regression)
return opt;
if (!mono_current_single_method) {
if (!mono_single_method_hash)
mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
if (!g_hash_table_lookup (mono_single_method_hash, method)) {
g_hash_table_insert (mono_single_method_hash, method, method);
mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
}
return opt;
}
if (method == mono_current_single_method)
return mono_single_method_regression_opt;
return opt;
}
gpointer
mono_jit_find_compiled_method (MonoMethod *method)
{
return mono_jit_find_compiled_method_with_jit_info (method, NULL);
}
typedef struct {
MonoMethod *method;
gpointer compiled_method;
gpointer runtime_invoke;
MonoVTable *vtable;
MonoDynCallInfo *dyn_call_info;
MonoClass *ret_box_class;
MonoMethodSignature *sig;
gboolean gsharedvt_invoke;
gboolean use_interp;
gpointer *wrapper_arg;
} RuntimeInvokeInfo;
#define MONO_SIZEOF_DYN_CALL_RET_BUF TARGET_SIZEOF_VOID_P
static RuntimeInvokeInfo*
create_runtime_invoke_info (MonoMethod *method, gpointer compiled_method, gboolean callee_gsharedvt, gboolean use_interp, MonoError *error)
{
MonoMethod *invoke;
RuntimeInvokeInfo *info = NULL;
RuntimeInvokeInfo *ret = NULL;
info = g_new0 (RuntimeInvokeInfo, 1);
info->compiled_method = compiled_method;
info->use_interp = use_interp;
info->sig = mono_method_signature_internal (method);
invoke = mono_marshal_get_runtime_invoke (method, FALSE);
(void)invoke;
info->vtable = mono_class_vtable_checked (method->klass, error);
if (!is_ok (error))
goto exit;
g_assert (info->vtable);
MonoMethodSignature *sig;
sig = info->sig;
MonoType *ret_type;
/*
* We want to avoid AOTing 1000s of runtime-invoke wrappers when running
* in full-aot mode, so we use a slower, but more generic wrapper if
* possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
*/
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (!mono_llvm_only && (mono_aot_only || mini_debug_options.dyn_runtime_invoke)) {
gboolean supported = TRUE;
int i;
if (method->string_ctor)
sig = mono_marshal_get_string_ctor_signature (method);
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (m_type_is_byref (t) && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t)))
supported = FALSE;
}
if (!info->compiled_method)
supported = FALSE;
if (supported) {
info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
if (mini_debug_options.dyn_runtime_invoke)
g_assert (info->dyn_call_info);
}
}
#endif
ret_type = sig->ret;
switch (ret_type->type) {
case MONO_TYPE_VOID:
break;
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_I8:
case MONO_TYPE_U8:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
case MONO_TYPE_PTR:
info->ret_box_class = mono_defaults.int_class;
break;
case MONO_TYPE_STRING:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_OBJECT:
break;
case MONO_TYPE_GENERICINST:
if (!MONO_TYPE_IS_REFERENCE (ret_type))
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
case MONO_TYPE_VALUETYPE:
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
default:
g_assert_not_reached ();
break;
}
if (info->use_interp) {
ret = info;
info = NULL;
goto exit;
}
if (!info->dyn_call_info) {
/*
* Can't use the normal llvmonly code for string ctors since the gsharedvt out wrapper passes
* an extra arg, which the string ctor methods don't have, which causes signature mismatches
* on wasm. Instead, call string ctors normally using a direct runtime invoke wrapper
* which is AOTed for each ctor.
*/
if (mono_llvm_only && !method->string_ctor) {
#ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
g_assert_not_reached ();
#endif
info->gsharedvt_invoke = TRUE;
if (!callee_gsharedvt) {
/* Invoke a gsharedvt out wrapper instead */
MonoMethod *wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
info->wrapper_arg = g_malloc0 (2 * sizeof (gpointer));
info->wrapper_arg [0] = mini_llvmonly_add_method_wrappers (method, info->compiled_method, FALSE, FALSE, &(info->wrapper_arg [1]));
/* Pass has_rgctx == TRUE since the wrapper has an extra arg */
invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
g_free (wrapper_sig);
info->compiled_method = mono_jit_compile_method (wrapper, error);
if (!is_ok (error))
goto exit;
} else {
/* Gsharedvt methods can be invoked the same way */
/* The out wrapper has the same signature as the compiled gsharedvt method */
MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
info->wrapper_arg = (gpointer*)(mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL);
invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
g_free (wrapper_sig);
}
}
info->runtime_invoke = mono_jit_compile_method (invoke, error);
if (!is_ok (error))
goto exit;
}
ret = info;
info = NULL;
exit:
g_free (info);
return ret;
}
static GENERATE_GET_CLASS_WITH_CACHE (nullbyrefreturn_ex, "Mono", "NullByRefReturnException");
static MonoObject*
mono_llvmonly_runtime_invoke (MonoMethod *method, RuntimeInvokeInfo *info, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MonoMethodSignature *sig = info->sig;
MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
int32_t retval_size = MONO_SIZEOF_DYN_CALL_RET_BUF;
gpointer retval = NULL;
int i, pindex;
error_init (error);
g_assert (info->gsharedvt_invoke);
/*
* Instead of invoking the method directly, we invoke a gsharedvt out wrapper.
* The advantage of this is the gsharedvt out wrappers have a reduced set of
* signatures, so we only have to generate runtime invoke wrappers for these
* signatures.
* This code also handles invocation of gsharedvt methods directly, no
* out wrappers are used in that case.
*/
// allocate param_refs = param_count and args = param_count + hasthis + 2.
int const param_count = sig->param_count;
gpointer* const param_refs = g_newa (gpointer, param_count * 2 + sig->hasthis + 2);
gpointer* const args = param_refs + param_count;
pindex = 0;
/*
* The runtime invoke wrappers expects pointers to primitive types, so have to
* use indirections.
*/
if (sig->hasthis)
args [pindex ++] = &obj;
if (sig->ret->type != MONO_TYPE_VOID) {
if (info->ret_box_class && !m_type_is_byref (sig->ret) &&
(sig->ret->type == MONO_TYPE_VALUETYPE ||
(sig->ret->type == MONO_TYPE_GENERICINST && !MONO_TYPE_IS_REFERENCE (sig->ret)))) {
// if the return type is a struct, allocate enough stack space to hold it
MonoClass *ret_klass = mono_class_from_mono_type_internal (sig->ret);
g_assert (!mono_class_has_failure (ret_klass));
int32_t inst_size = mono_class_instance_size (ret_klass);
if (inst_size > MONO_SIZEOF_DYN_CALL_RET_BUF) {
retval_size = inst_size;
}
}
}
retval = g_alloca (retval_size);
if (sig->ret->type != MONO_TYPE_VOID) {
args [pindex ++] = &retval;
}
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
MonoClass *klass = mono_class_from_mono_type_internal (t);
guint8 *nullable_buf;
int size;
size = mono_class_value_size (klass, NULL);
nullable_buf = g_alloca (size);
g_assert (nullable_buf);
/* The argument pointed to by params [i] is either a boxed vtype or null */
mono_nullable_init (nullable_buf, (MonoObject*)params [i], klass);
params [i] = nullable_buf;
}
if (!m_type_is_byref (t) && (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR)) {
param_refs [i] = params [i];
params [i] = &(param_refs [i]);
}
args [pindex ++] = ¶ms [i];
}
/* The gsharedvt out wrapper has an extra argument which contains the method to call */
args [pindex ++] = &info->wrapper_arg;
runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
runtime_invoke (NULL, args, exc, info->compiled_method);
if (exc && *exc)
return NULL;
if (m_type_is_byref (sig->ret)) {
if (*(gpointer*)retval == NULL) {
MonoClass *klass = mono_class_get_nullbyrefreturn_ex_class ();
MonoObject *ex = mono_object_new_checked (klass, error);
mono_error_assert_ok (error);
mono_error_set_exception_instance (error, (MonoException*)ex);
return NULL;
}
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (info->ret_box_class) {
if (m_type_is_byref (sig->ret)) {
return mono_value_box_checked (info->ret_box_class, *(gpointer*)retval, error);
} else {
MonoObject *ret = mono_value_box_checked (info->ret_box_class, retval, error);
return ret;
}
} else {
if (m_type_is_byref (sig->ret))
return **(MonoObject***)retval;
else
return *(MonoObject**)retval;
}
} else {
return NULL;
}
}
/**
* mono_jit_runtime_invoke:
* \param method: the method to invoke
* \param obj: this pointer
* \param params: array of parameter values.
* \param exc: Set to the exception raised in the managed method.
* \param error: error or caught exception object
* If \p exc is NULL, \p error is thrown instead.
* If coop is enabled, \p exc argument is ignored -
* all exceptions are caught and propagated through \p error
*/
static MonoObject*
mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MonoMethod *callee;
MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
RuntimeInvokeInfo *info, *info2;
MonoJitInfo *ji = NULL;
gboolean callee_gsharedvt = FALSE;
MonoJitMemoryManager *jit_mm;
if (mono_ee_features.force_use_interpreter) {
// FIXME: On wasm, if the callee throws an exception, this will return NULL, and the
// exception will be stored inside the interpreter, it won't show up in exc/error.
return mini_get_interp_callbacks ()->runtime_invoke (method, obj, params, exc, error);
}
error_init (error);
if (exc)
*exc = NULL;
if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
return NULL;
}
jit_mm = jit_mm_for_method (method);
info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (jit_mm->runtime_invoke_hash, method);
if (!info) {
gpointer compiled_method;
callee = method;
if (m_class_get_rank (method->klass) && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
(method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
/*
* Array Get/Set/Address methods. The JIT implements them using inline code
* inside the runtime invoke wrappers, so no need to compile them.
*/
if (mono_aot_only) {
/*
* Call a wrapper, since the runtime invoke wrapper was not generated.
*/
MonoMethod *wrapper;
wrapper = mono_marshal_get_array_accessor_wrapper (method);
mono_marshal_get_runtime_invoke (wrapper, FALSE);
callee = wrapper;
} else {
callee = NULL;
}
}
gboolean use_interp = FALSE;
if (mono_aot_mode == MONO_AOT_MODE_LLVMONLY_INTERP)
/* The runtime invoke wrappers contain clauses so they are not AOTed */
use_interp = TRUE;
if (callee) {
compiled_method = mono_jit_compile_method_jit_only (callee, error);
if (!compiled_method) {
g_assert (!is_ok (error));
if (mono_use_interpreter)
use_interp = TRUE;
else
return NULL;
} else {
if (mono_llvm_only) {
ji = mini_jit_info_table_find (mono_get_addr_from_ftnptr (compiled_method));
callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
if (callee_gsharedvt)
callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (ji)));
}
if (!callee_gsharedvt)
compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
}
} else {
compiled_method = NULL;
}
info = create_runtime_invoke_info (method, compiled_method, callee_gsharedvt, use_interp, error);
if (!is_ok (error))
return NULL;
jit_mm_lock (jit_mm);
info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (jit_mm->runtime_invoke_hash, method, info);
jit_mm_unlock (jit_mm);
if (info2) {
g_free (info);
info = info2;
}
}
/*
* We need this here because mono_marshal_get_runtime_invoke can place
* the helper method in System.Object and not the target class.
*/
if (!mono_runtime_class_init_full (info->vtable, error)) {
if (exc)
*exc = (MonoObject*) mono_error_convert_to_exception (error);
return NULL;
}
/* If coop is enabled, and the caller didn't ask for the exception to be caught separately,
we always catch the exception and propagate it through the MonoError */
gboolean catchExcInMonoError =
(exc == NULL) && mono_threads_are_safepoints_enabled ();
MonoObject *invoke_exc = NULL;
if (catchExcInMonoError)
exc = &invoke_exc;
/* The wrappers expect this to be initialized to NULL */
if (exc)
*exc = NULL;
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
static RuntimeInvokeDynamicFunction dyn_runtime_invoke = NULL;
if (info->dyn_call_info) {
if (!dyn_runtime_invoke) {
MonoMethod *dynamic_invoke = mono_marshal_get_runtime_invoke_dynamic ();
RuntimeInvokeDynamicFunction invoke_func = (RuntimeInvokeDynamicFunction)mono_jit_compile_method_jit_only (dynamic_invoke, error);
mono_memory_barrier ();
dyn_runtime_invoke = invoke_func;
if (!dyn_runtime_invoke && mono_use_interpreter) {
info->use_interp = TRUE;
info->dyn_call_info = NULL;
} else if (!is_ok (error)) {
return NULL;
}
}
}
if (info->dyn_call_info) {
MonoMethodSignature *sig = mono_method_signature_internal (method);
gpointer *args;
int i, pindex, buf_size;
guint8 *buf;
int32_t retval_size = MONO_SIZEOF_DYN_CALL_RET_BUF;
guint8 *retval = NULL;
/* if the return type is a struct and it's too big, allocate more space for it */
if (info->ret_box_class && !m_type_is_byref (sig->ret) &&
(sig->ret->type == MONO_TYPE_VALUETYPE ||
(sig->ret->type == MONO_TYPE_GENERICINST && !MONO_TYPE_IS_REFERENCE (sig->ret)))) {
MonoClass *ret_klass = mono_class_from_mono_type_internal (sig->ret);
g_assert (!mono_class_has_failure (ret_klass));
int32_t inst_size = mono_class_instance_size (ret_klass);
if (inst_size > MONO_SIZEOF_DYN_CALL_RET_BUF) {
retval_size = inst_size;
}
}
retval = g_alloca (retval_size);
/* Convert the arguments to the format expected by start_dyn_call () */
args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
pindex = 0;
if (sig->hasthis)
args [pindex ++] = &obj;
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (m_type_is_byref (t)) {
args [pindex ++] = ¶ms [i];
} else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
args [pindex ++] = ¶ms [i];
} else {
args [pindex ++] = params [i];
}
}
//printf ("M: %s\n", mono_method_full_name (method, TRUE));
buf_size = mono_arch_dyn_call_get_buf_size (info->dyn_call_info);
buf = g_alloca (buf_size);
memset (buf, 0, buf_size);
g_assert (buf);
mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf);
dyn_runtime_invoke (buf, exc, info->compiled_method);
mono_arch_finish_dyn_call (info->dyn_call_info, buf);
if (catchExcInMonoError && *exc != NULL) {
mono_error_set_exception_instance (error, (MonoException*) *exc);
return NULL;
}
if (m_type_is_byref (sig->ret)) {
if (*(gpointer*)retval == NULL) {
MonoClass *klass = mono_class_get_nullbyrefreturn_ex_class ();
MonoObject *ex = mono_object_new_checked (klass, error);
mono_error_assert_ok (error);
mono_error_set_exception_instance (error, (MonoException*)ex);
return NULL;
}
}
if (info->ret_box_class) {
if (m_type_is_byref (sig->ret)) {
return mono_value_box_checked (info->ret_box_class, *(gpointer*)retval, error);
} else {
MonoObject *boxed_ret = mono_value_box_checked (info->ret_box_class, retval, error);
return boxed_ret;
}
} else {
if (m_type_is_byref (sig->ret))
return **(MonoObject***)retval;
else
return *(MonoObject**)retval;
}
}
#endif
MonoObject *result;
if (info->use_interp) {
result = mini_get_interp_callbacks ()->runtime_invoke (method, obj, params, exc, error);
return_val_if_nok (error, NULL);
} else if (mono_llvm_only && !method->string_ctor) {
result = mono_llvmonly_runtime_invoke (method, info, obj, params, exc, error);
if (!is_ok (error))
return NULL;
} else {
runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
result = runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
}
if (catchExcInMonoError && *exc != NULL) {
((MonoException *)(*exc))->caught_in_unmanaged = TRUE;
mono_error_set_exception_instance (error, (MonoException*) *exc);
}
return result;
}
MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
{
MonoException *exc = NULL;
MonoJitInfo *ji;
MonoContext mctx;
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
MONO_SIG_HANDLER_GET_CONTEXT;
ji = mono_jit_info_table_find_internal (mono_arch_ip_from_context (ctx), TRUE, TRUE);
MONO_ENTER_GC_UNSAFE_UNBALANCED;
#if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
if (mono_arch_is_int_overflow (ctx, info))
/*
* The spec says this throws ArithmeticException, but MS throws the derived
* OverflowException.
*/
exc = mono_get_exception_overflow ();
else
exc = mono_get_exception_divide_by_zero ();
#else
exc = mono_get_exception_divide_by_zero ();
#endif
if (!ji) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
goto exit;
mono_sigctx_to_monoctx (ctx, &mctx);
mono_handle_native_crash (mono_get_signame (SIGFPE), &mctx, info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
goto exit;
}
}
mono_arch_handle_exception (ctx, exc);
exit:
MONO_EXIT_GC_UNSAFE_UNBALANCED;
}
MONO_SIG_HANDLER_FUNC (, mono_crashing_signal_handler)
{
MonoContext mctx;
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
MONO_SIG_HANDLER_GET_CONTEXT;
if (mono_runtime_get_no_exec ())
exit (1);
mono_sigctx_to_monoctx (ctx, &mctx);
#if defined(HAVE_SIG_INFO) && !defined(HOST_WIN32) // info is a siginfo_t
mono_handle_native_crash (mono_get_signame (info->si_signo), &mctx, info);
#else
mono_handle_native_crash (mono_get_signame (SIGTERM), &mctx, info);
#endif
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
#define HAVE_SIG_INFO
#define MONO_SIG_HANDLER_DEBUG 1 // "with_fault_addr" but could be extended in future, so "debug"
#ifdef MONO_SIG_HANDLER_DEBUG
// Same as MONO_SIG_HANDLER_FUNC but debug_fault_addr is added to params, and no_optimize.
// The Krait workaround is not needed here, due to this not actually being the signal handler,
// so MONO_SIGNAL_HANDLER_FUNC is combined into it.
#define MONO_SIG_HANDLER_FUNC_DEBUG(access, ftn) access MONO_NO_OPTIMIZATION void ftn \
(int _dummy, MONO_SIG_HANDLER_INFO_TYPE *_info, void *context, void * volatile debug_fault_addr G_GNUC_UNUSED)
#define MONO_SIG_HANDLER_PARAMS_DEBUG MONO_SIG_HANDLER_PARAMS, debug_fault_addr
#endif
#endif
gboolean
mono_is_addr_implicit_null_check (void *addr)
{
/* implicit null checks are only expected to work on the first page. larger
* offsets are expected to have an explicit null check */
return addr <= GUINT_TO_POINTER (mono_target_pagesize ());
}
// This function is separate from mono_sigsegv_signal_handler
// so debug_fault_addr can be seen in debugger stacks.
#ifdef MONO_SIG_HANDLER_DEBUG
MONO_NEVER_INLINE
MONO_SIG_HANDLER_FUNC_DEBUG (static, mono_sigsegv_signal_handler_debug)
#else
MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
#endif
{
MonoJitInfo *ji = NULL;
MonoDomain *domain = mono_domain_get ();
gpointer fault_addr = NULL;
MonoContext mctx;
#if defined(HAVE_SIG_INFO) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
#endif
#ifdef HAVE_SIG_INFO
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
#else
void *info = NULL;
#endif
MONO_SIG_HANDLER_GET_CONTEXT;
mono_sigctx_to_monoctx (ctx, &mctx);
#if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
if (mono_arch_is_single_step_event (info, ctx)) {
mono_component_debugger ()->single_step_event (ctx);
return;
} else if (mono_arch_is_breakpoint_event (info, ctx)) {
mono_component_debugger ()->breakpoint_hit (ctx);
return;
}
#endif
#if defined(HAVE_SIG_INFO)
#if !defined(HOST_WIN32)
fault_addr = info->si_addr;
if (mono_aot_is_pagefault (info->si_addr)) {
mono_aot_handle_pagefault (info->si_addr);
return;
}
int signo = info->si_signo;
#else
int signo = SIGSEGV;
#endif
/* The thread might no be registered with the runtime */
if (!mono_domain_get () || !jit_tls) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
mono_handle_native_crash (mono_get_signame (signo), &mctx, info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#endif
if (domain) {
gpointer ip = MINI_FTNPTR_TO_ADDR (mono_arch_ip_from_context (ctx));
ji = mono_jit_info_table_find_internal (ip, TRUE, TRUE);
}
#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
return;
/* info->si_addr seems to be NULL on some kernels when handling stack overflows */
fault_addr = info->si_addr;
if (fault_addr == NULL) {
fault_addr = MONO_CONTEXT_GET_SP (&mctx);
}
if (jit_tls && jit_tls->stack_size &&
ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
/*
* The hard-guard page has been hit: there is not much we can do anymore
* Print a hopefully clear message and abort.
*/
mono_handle_hard_stack_ovf (jit_tls, ji, &mctx, (guint8*)info->si_addr);
g_assert_not_reached ();
} else {
/* The original handler might not like that it is executed on an altstack... */
if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
#ifdef TARGET_AMD64
/* exceptions-amd64.c handles the check itself */
mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
#else
if (mono_is_addr_implicit_null_check (info->si_addr)) {
mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
} else {
// FIXME: This shouldn't run on the altstack
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, info);
}
#endif
}
#else
if (!ji) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, (MONO_SIG_HANDLER_INFO_TYPE*)info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
if (mono_is_addr_implicit_null_check (fault_addr)) {
mono_arch_handle_exception (ctx, NULL);
} else {
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, (MONO_SIG_HANDLER_INFO_TYPE*)info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#endif
}
#ifdef MONO_SIG_HANDLER_DEBUG
// This function is separate from mono_sigsegv_signal_handler_debug
// so debug_fault_addr can be seen in debugger stacks.
MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
{
#ifdef HOST_WIN32
gpointer const debug_fault_addr = (gpointer)MONO_SIG_HANDLER_GET_INFO () ->ep->ExceptionRecord->ExceptionInformation [1];
#elif defined (HAVE_SIG_INFO)
gpointer const debug_fault_addr = MONO_SIG_HANDLER_GET_INFO ()->si_addr;
#else
#error No extra parameter is passed, not even 0, to avoid any confusion.
#endif
mono_sigsegv_signal_handler_debug (MONO_SIG_HANDLER_PARAMS_DEBUG);
}
#endif // MONO_SIG_HANDLER_DEBUG
MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
{
MonoException *exc;
MONO_SIG_HANDLER_GET_CONTEXT;
MONO_ENTER_GC_UNSAFE_UNBALANCED;
exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
mono_arch_handle_exception (ctx, exc);
MONO_EXIT_GC_UNSAFE_UNBALANCED;
}
static G_GNUC_UNUSED void
no_imt_trampoline (void)
{
g_assert_not_reached ();
}
static G_GNUC_UNUSED void
no_vcall_trampoline (void)
{
g_assert_not_reached ();
}
static gpointer *vtable_trampolines;
static int vtable_trampolines_size;
gpointer
mini_get_vtable_trampoline (MonoVTable *vt, int slot_index)
{
int index = slot_index + MONO_IMT_SIZE;
if (mono_llvm_only)
return mini_llvmonly_get_vtable_trampoline (vt, slot_index, index);
g_assert (slot_index >= - MONO_IMT_SIZE);
if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
mono_jit_lock ();
if (!vtable_trampolines || index >= vtable_trampolines_size) {
int new_size;
gpointer new_table;
new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
while (new_size <= index)
new_size *= 2;
new_table = g_new0 (gpointer, new_size);
if (vtable_trampolines)
memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
g_free (vtable_trampolines);
mono_memory_barrier ();
vtable_trampolines = (void **)new_table;
vtable_trampolines_size = new_size;
}
mono_jit_unlock ();
}
if (!vtable_trampolines [index])
vtable_trampolines [index] = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, NULL);
return vtable_trampolines [index];
}
static gpointer
mini_get_imt_trampoline (MonoVTable *vt, int slot_index)
{
return mini_get_vtable_trampoline (vt, slot_index - MONO_IMT_SIZE);
}
static gboolean
mini_imt_entry_inited (MonoVTable *vt, int imt_slot_index)
{
if (mono_llvm_only)
return FALSE;
gpointer *imt = (gpointer*)vt;
imt -= MONO_IMT_SIZE;
return (imt [imt_slot_index] != mini_get_imt_trampoline (vt, imt_slot_index));
}
static gpointer
create_delegate_method_ptr (MonoMethod *method, MonoError *error)
{
gpointer func;
if (method_is_dynamic (method)) {
/* Creating a trampoline would leak memory */
func = mono_compile_method_checked (method, error);
return_val_if_nok (error, NULL);
} else {
gpointer trampoline = mono_create_jump_trampoline (method, TRUE, error);
return_val_if_nok (error, NULL);
func = mono_create_ftnptr (trampoline);
}
return func;
}
static void
mini_init_delegate (MonoDelegateHandle delegate, MonoObjectHandle target, gpointer addr, MonoMethod *method, MonoError *error)
{
MonoDelegate *del = MONO_HANDLE_RAW (delegate);
if (!method && !addr) {
// Multicast delegate init
if (!mono_llvm_only) {
MONO_HANDLE_SETVAL (delegate, invoke_impl, gpointer, mono_create_delegate_trampoline (mono_handle_class (delegate)));
} else {
mini_llvmonly_init_delegate (del, NULL);
}
return;
}
if (!method) {
MonoJitInfo *ji;
gpointer lookup_addr = MINI_FTNPTR_TO_ADDR (addr);
g_assert (addr);
ji = mono_jit_info_table_find_internal (mono_get_addr_from_ftnptr (lookup_addr), TRUE, TRUE);
if (ji) {
if (ji->is_trampoline) {
/* Could be an unbox trampoline etc. */
method = ji->d.tramp_info->method;
} else {
method = mono_jit_info_get_method (ji);
g_assert (!mono_class_is_gtd (method->klass));
}
}
}
if (method)
MONO_HANDLE_SETVAL (delegate, method, MonoMethod*, method);
if (addr)
MONO_HANDLE_SETVAL (delegate, method_ptr, gpointer, addr);
MONO_HANDLE_SET (delegate, target, target);
MONO_HANDLE_SETVAL (delegate, invoke_impl, gpointer, mono_create_delegate_trampoline (mono_handle_class (delegate)));
MonoDelegateTrampInfo *info = NULL;
if (mono_use_interpreter) {
mini_get_interp_callbacks ()->init_delegate (del, &info, error);
return_if_nok (error);
}
if (mono_llvm_only) {
g_assert (del->method);
mini_llvmonly_init_delegate (del, info);
//del->method_ptr = mini_llvmonly_load_method_delegate (del->method, FALSE, FALSE, &del->extra_arg, error);
} else if (!del->method_ptr) {
del->method_ptr = create_delegate_method_ptr (del->method, error);
return_if_nok (error);
}
}
char*
mono_get_delegate_virtual_invoke_impl_name (gboolean load_imt_reg, int offset)
{
int abs_offset;
abs_offset = offset;
if (abs_offset < 0)
abs_offset = - abs_offset;
return g_strdup_printf ("delegate_virtual_invoke%s_%s%d", load_imt_reg ? "_imt" : "", offset < 0 ? "m_" : "", abs_offset / TARGET_SIZEOF_VOID_P);
}
gpointer
mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
{
gboolean is_virtual_generic, is_interface, load_imt_reg;
int offset, idx;
static guint8 **cache = NULL;
static int cache_size = 0;
if (!method)
return NULL;
if (MONO_TYPE_ISSTRUCT (sig->ret))
return NULL;
is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
is_interface = mono_class_is_interface (method->klass);
load_imt_reg = is_virtual_generic || is_interface;
if (is_interface)
offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * TARGET_SIZEOF_VOID_P;
else
offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (TARGET_SIZEOF_VOID_P));
idx = (offset / TARGET_SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
g_assert (idx >= 0);
/* Resize the cache to idx + 1 */
if (cache_size < idx + 1) {
mono_jit_lock ();
if (cache_size < idx + 1) {
guint8 **new_cache;
int new_cache_size = idx + 1;
new_cache = g_new0 (guint8*, new_cache_size);
if (cache)
memcpy (new_cache, cache, cache_size * sizeof (guint8*));
g_free (cache);
mono_memory_barrier ();
cache = new_cache;
cache_size = new_cache_size;
}
mono_jit_unlock ();
}
if (cache [idx])
return cache [idx];
/* FIXME Support more cases */
if (mono_ee_features.use_aot_trampolines) {
cache [idx] = (guint8 *)mono_aot_get_trampoline (mono_get_delegate_virtual_invoke_impl_name (load_imt_reg, offset));
g_assert (cache [idx]);
} else {
cache [idx] = (guint8 *)mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
}
return cache [idx];
}
/**
* mini_parse_debug_option:
* @option: The option to parse.
*
* Parses debug options for the mono runtime. The options are the same as for
* the MONO_DEBUG environment variable.
*
*/
gboolean
mini_parse_debug_option (const char *option)
{
// Empty string is ok as consequence of appending ",foo"
// without first checking for empty.
if (*option == 0)
return TRUE;
if (!strcmp (option, "handle-sigint"))
mini_debug_options.handle_sigint = TRUE;
else if (!strcmp (option, "keep-delegates"))
mini_debug_options.keep_delegates = TRUE;
else if (!strcmp (option, "reverse-pinvoke-exceptions"))
mini_debug_options.reverse_pinvoke_exceptions = TRUE;
else if (!strcmp (option, "collect-pagefault-stats"))
mini_debug_options.collect_pagefault_stats = TRUE;
else if (!strcmp (option, "break-on-unverified"))
mini_debug_options.break_on_unverified = TRUE;
else if (!strcmp (option, "no-gdb-backtrace"))
mini_debug_options.no_gdb_backtrace = TRUE;
else if (!strcmp (option, "suspend-on-native-crash") || !strcmp (option, "suspend-on-sigsegv"))
mini_debug_options.suspend_on_native_crash = TRUE;
else if (!strcmp (option, "suspend-on-exception"))
mini_debug_options.suspend_on_exception = TRUE;
else if (!strcmp (option, "suspend-on-unhandled"))
mini_debug_options.suspend_on_unhandled = TRUE;
else if (!strcmp (option, "dont-free-domains"))
mono_dont_free_domains = TRUE;
else if (!strcmp (option, "dyn-runtime-invoke"))
mini_debug_options.dyn_runtime_invoke = TRUE;
else if (!strcmp (option, "gdb"))
fprintf (stderr, "MONO_DEBUG=gdb is deprecated.");
else if (!strcmp (option, "lldb"))
mini_debug_options.lldb = TRUE;
else if (!strcmp (option, "llvm-disable-inlining"))
mini_debug_options.llvm_disable_inlining = TRUE;
else if (!strcmp (option, "llvm-disable-implicit-null-checks"))
mini_debug_options.llvm_disable_implicit_null_checks = TRUE;
else if (!strcmp (option, "explicit-null-checks"))
mini_debug_options.explicit_null_checks = TRUE;
else if (!strcmp (option, "gen-seq-points"))
mini_debug_options.gen_sdb_seq_points = TRUE;
else if (!strcmp (option, "gen-compact-seq-points"))
fprintf (stderr, "Mono Warning: option gen-compact-seq-points is deprecated.\n");
else if (!strcmp (option, "no-compact-seq-points"))
mini_debug_options.no_seq_points_compact_data = TRUE;
else if (!strcmp (option, "single-imm-size"))
mini_debug_options.single_imm_size = TRUE;
else if (!strcmp (option, "init-stacks"))
mini_debug_options.init_stacks = TRUE;
else if (!strcmp (option, "casts"))
mini_debug_options.better_cast_details = TRUE;
else if (!strcmp (option, "soft-breakpoints"))
mini_debug_options.soft_breakpoints = TRUE;
else if (!strcmp (option, "check-pinvoke-callconv"))
mini_debug_options.check_pinvoke_callconv = TRUE;
else if (!strcmp (option, "use-fallback-tls"))
mini_debug_options.use_fallback_tls = TRUE;
else if (!strcmp (option, "debug-domain-unload"))
g_error ("MONO_DEBUG option debug-domain-unload is deprecated.");
else if (!strcmp (option, "partial-sharing"))
mono_set_partial_sharing_supported (TRUE);
else if (!strcmp (option, "align-small-structs"))
mono_align_small_structs = TRUE;
else if (!strcmp (option, "native-debugger-break"))
mini_debug_options.native_debugger_break = TRUE;
else if (!strcmp (option, "disable_omit_fp"))
mini_debug_options.disable_omit_fp = TRUE;
// This is an internal testing feature.
// Every tail. encountered is required to be optimized.
// It is asserted.
else if (!strcmp (option, "test-tailcall-require"))
mini_debug_options.test_tailcall_require = TRUE;
else if (!strcmp (option, "verbose-gdb"))
mini_debug_options.verbose_gdb = TRUE;
else if (!strcmp (option, "clr-memory-model"))
// FIXME Kill this debug flag
mini_debug_options.weak_memory_model = FALSE;
else if (!strcmp (option, "weak-memory-model"))
mini_debug_options.weak_memory_model = TRUE;
else if (!strcmp (option, "top-runtime-invoke-unhandled"))
mini_debug_options.top_runtime_invoke_unhandled = TRUE;
else if (!strncmp (option, "thread-dump-dir=", 16))
mono_set_thread_dump_dir(g_strdup(option + 16));
else if (!strncmp (option, "aot-skip=", 9)) {
mini_debug_options.aot_skip_set = TRUE;
mini_debug_options.aot_skip = atoi (option + 9);
} else
return FALSE;
return TRUE;
}
static void
mini_parse_debug_options (void)
{
char *options = g_getenv ("MONO_DEBUG");
gchar **args, **ptr;
if (!options)
return;
args = g_strsplit (options, ",", -1);
g_free (options);
for (ptr = args; ptr && *ptr; ptr++) {
const char *arg = *ptr;
if (!mini_parse_debug_option (arg)) {
fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
// test-tailcall-require is also accepted but not documented.
// empty string is also accepted and ignored as a consequence
// of appending ",foo" without checking for empty.
fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'suspend-on-native-crash', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dont-free-domains', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'gen-seq-points', 'no-compact-seq-points', 'single-imm-size', 'init-stacks', 'casts', 'soft-breakpoints', 'check-pinvoke-callconv', 'use-fallback-tls', 'debug-domain-unload', 'partial-sharing', 'align-small-structs', 'native-debugger-break', 'thread-dump-dir=DIR', 'no-verbose-gdb', 'llvm_disable_inlining', 'llvm-disable-self-init', 'llvm-disable-implicit-null-checks', 'weak-memory-model'.\n");
exit (1);
}
}
g_strfreev (args);
}
MonoDebugOptions *
mini_get_debug_options (void)
{
return &mini_debug_options;
}
static gpointer
mini_create_ftnptr (gpointer addr)
{
#if defined(PPC_USES_FUNCTION_DESCRIPTOR)
gpointer* desc = NULL;
static GHashTable *ftnptrs_hash;
if (!ftnptrs_hash) {
GHashTable *hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_memory_barrier ();
ftnptrs_hash = hash;
}
// FIXME:
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
mono_jit_lock ();
desc = (gpointer*)g_hash_table_lookup (ftnptrs_hash, addr);
mono_jit_unlock ();
if (desc)
return desc;
#if defined(__mono_ppc64__)
desc = mono_mem_manager_alloc0 (jit_mm->mem_manager, 3 * sizeof (gpointer));
desc [0] = addr;
desc [1] = NULL;
desc [2] = NULL;
# endif
mono_jit_lock ();
g_hash_table_insert (ftnptrs_hash, addr, desc);
mono_jit_unlock ();
return desc;
#else
return addr;
#endif
}
static gpointer
mini_get_addr_from_ftnptr (gpointer descr)
{
#if defined(PPC_USES_FUNCTION_DESCRIPTOR)
return *(gpointer*)descr;
#else
return descr;
#endif
}
static void
register_counters (void)
{
mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
mono_counters_register ("Methods from AOT+LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot_llvm);
mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
mono_counters_register ("Methods using the interpreter", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_interp);
}
static void runtime_invoke_info_free (gpointer value);
static gint
class_method_pair_equal (gconstpointer ka, gconstpointer kb)
{
const MonoClassMethodPair *apair = (const MonoClassMethodPair *)ka;
const MonoClassMethodPair *bpair = (const MonoClassMethodPair *)kb;
return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
}
static guint
class_method_pair_hash (gconstpointer data)
{
const MonoClassMethodPair *pair = (const MonoClassMethodPair *)data;
return (gsize)pair->klass ^ (gsize)pair->method;
}
static void
init_jit_mem_manager (MonoMemoryManager *mem_manager)
{
MonoJitMemoryManager *info = g_new0 (MonoJitMemoryManager, 1);
info->mem_manager = mem_manager;
info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
info->jump_target_hash = g_hash_table_new (NULL, NULL);
info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
info->runtime_invoke_hash = mono_conc_hashtable_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_jit_code_hash_init (&info->jit_code_hash);
mono_jit_code_hash_init (&info->interp_code_hash);
mono_os_mutex_init_recursive (&info->jit_code_hash_lock);
mem_manager->runtime_info = info;
}
static void
delete_jump_list (gpointer key, gpointer value, gpointer user_data)
{
MonoJumpList *jlist = (MonoJumpList *)value;
g_slist_free ((GSList*)jlist->list);
}
static void
delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
{
GSList *list = (GSList *)value;
g_slist_free (list);
}
static void
dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
{
MonoJitDynamicMethodInfo *di = (MonoJitDynamicMethodInfo *)value;
mono_code_manager_destroy (di->code_mp);
g_free (di);
}
static void
runtime_invoke_info_free (gpointer value)
{
RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (info->dyn_call_info)
mono_arch_dyn_call_free (info->dyn_call_info);
#endif
g_free (info);
}
static void
free_jit_callee_list (gpointer key, gpointer value, gpointer user_data)
{
g_slist_free ((GSList*)value);
}
static void
free_jit_mem_manager (MonoMemoryManager *mem_manager)
{
MonoJitMemoryManager *info = (MonoJitMemoryManager*)mem_manager->runtime_info;
g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
g_hash_table_destroy (info->jump_target_hash);
if (info->jump_target_got_slot_hash) {
g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
g_hash_table_destroy (info->jump_target_got_slot_hash);
}
if (info->dynamic_code_hash) {
g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
g_hash_table_destroy (info->dynamic_code_hash);
}
g_hash_table_destroy (info->method_code_hash);
g_hash_table_destroy (info->jump_trampoline_hash);
g_hash_table_destroy (info->jit_trampoline_hash);
g_hash_table_destroy (info->delegate_trampoline_hash);
g_hash_table_destroy (info->static_rgctx_trampoline_hash);
g_hash_table_destroy (info->mrgctx_hash);
g_hash_table_destroy (info->method_rgctx_hash);
g_hash_table_destroy (info->interp_method_pointer_hash);
mono_conc_hashtable_destroy (info->runtime_invoke_hash);
g_hash_table_destroy (info->seq_points);
g_hash_table_destroy (info->arch_seq_points);
if (info->agent_info)
mono_component_debugger ()->free_mem_manager (info);
g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
if (info->llvm_jit_callees) {
g_hash_table_foreach (info->llvm_jit_callees, free_jit_callee_list, NULL);
g_hash_table_destroy (info->llvm_jit_callees);
}
mono_internal_hash_table_destroy (&info->interp_code_hash);
#ifdef ENABLE_LLVM
mono_llvm_free_mem_manager (info);
#endif
g_free (info);
mem_manager->runtime_info = NULL;
}
#ifdef ENABLE_LLVM
static gboolean
llvm_init_inner (void)
{
mono_llvm_init (!mono_compile_aot);
return TRUE;
}
#endif
/*
* mini_llvm_init:
*
* Load and initialize LLVM support.
* Return TRUE on success.
*/
gboolean
mini_llvm_init (void)
{
#ifdef ENABLE_LLVM
static gboolean llvm_inited;
static gboolean init_result;
mono_loader_lock_if_inited ();
if (!llvm_inited) {
init_result = llvm_init_inner ();
llvm_inited = TRUE;
}
mono_loader_unlock_if_inited ();
return init_result;
#else
return FALSE;
#endif
}
void
mini_add_profiler_argument (const char *desc)
{
if (!profile_options)
profile_options = g_ptr_array_new ();
g_ptr_array_add (profile_options, (gpointer) g_strdup (desc));
}
const MonoEECallbacks *mono_interp_callbacks_pointer;
void
mini_install_interp_callbacks (const MonoEECallbacks *cbs)
{
mono_interp_callbacks_pointer = cbs;
}
int
mono_ee_api_version (void)
{
return MONO_EE_API_VERSION;
}
void
mono_interp_entry_from_trampoline (gpointer ccontext, gpointer imethod)
{
mini_get_interp_callbacks ()->entry_from_trampoline (ccontext, imethod);
}
void
mono_interp_to_native_trampoline (gpointer addr, gpointer ccontext)
{
mini_get_interp_callbacks ()->to_native_trampoline (addr, ccontext);
}
static gboolean
mini_is_interpreter_enabled (void)
{
return mono_use_interpreter;
}
static const char*
mono_get_runtime_build_version (void);
MonoDomain *
mini_init (const char *filename, const char *runtime_version)
{
ERROR_DECL (error);
MonoDomain *domain;
MonoRuntimeCallbacks callbacks;
static const MonoThreadInfoRuntimeCallbacks ticallbacks = {
MONO_THREAD_INFO_RUNTIME_CALLBACKS (MONO_INIT_CALLBACK, mono)
};
mono_component_event_pipe_100ns_ticks_start ();
MONO_VES_INIT_BEGIN ();
CHECKED_MONO_INIT ();
#if defined(__linux__)
if (access ("/proc/self/maps", F_OK) != 0) {
g_print ("Mono requires /proc to be mounted.\n");
exit (1);
}
#endif
mono_interp_stub_init ();
#ifndef DISABLE_INTERPRETER
if (mono_use_interpreter)
mono_ee_interp_init (mono_interp_opts_string);
#endif
mono_components_init ();
mono_component_debugger ()->parse_options (mono_debugger_agent_get_sdb_options ());
mono_os_mutex_init_recursive (&jit_mutex);
mono_cross_helpers_run ();
mono_counters_init ();
mini_jit_init ();
mini_jit_init_job_control ();
/* Happens when using the embedding interface */
if (!default_opt_set)
default_opt = mono_parse_default_optimizations (NULL);
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
if (mono_aot_only)
mono_set_generic_sharing_vt_supported (TRUE);
#else
if (mono_llvm_only)
mono_set_generic_sharing_vt_supported (TRUE);
#endif
mono_tls_init_runtime_keys ();
if (!global_codeman) {
if (!mono_compile_aot)
global_codeman = mono_code_manager_new ();
else
global_codeman = mono_code_manager_new_aot ();
}
memset (&callbacks, 0, sizeof (callbacks));
callbacks.create_ftnptr = mini_create_ftnptr;
callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
callbacks.get_runtime_build_info = mono_get_runtime_build_info;
callbacks.get_runtime_build_version = mono_get_runtime_build_version;
callbacks.set_cast_details = mono_set_cast_details;
callbacks.debug_log = mono_component_debugger ()->debug_log;
callbacks.debug_log_is_enabled = mono_component_debugger ()->debug_log_is_enabled;
callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
callbacks.get_imt_trampoline = mini_get_imt_trampoline;
callbacks.imt_entry_inited = mini_imt_entry_inited;
callbacks.init_delegate = mini_init_delegate;
#define JIT_INVOKE_WORKS
#ifdef JIT_INVOKE_WORKS
callbacks.runtime_invoke = mono_jit_runtime_invoke;
#endif
#define JIT_TRAMPOLINES_WORK
#ifdef JIT_TRAMPOLINES_WORK
callbacks.compile_method = mono_jit_compile_method;
callbacks.create_jit_trampoline = mono_create_jit_trampoline;
callbacks.create_delegate_trampoline = mono_create_delegate_trampoline;
callbacks.free_method = mono_jit_free_method;
callbacks.get_ftnptr = get_ftnptr_for_method;
#endif
callbacks.is_interpreter_enabled = mini_is_interpreter_enabled;
callbacks.get_weak_field_indexes = mono_aot_get_weak_field_indexes;
callbacks.metadata_update_published = mini_invalidate_transformed_interp_methods;
callbacks.interp_jit_info_foreach = mini_interp_jit_info_foreach;
callbacks.interp_sufficient_stack = mini_interp_sufficient_stack;
callbacks.init_mem_manager = init_jit_mem_manager;
callbacks.free_mem_manager = free_jit_mem_manager;
callbacks.get_jit_stats = get_jit_stats;
callbacks.get_exception_stats = get_exception_stats;
mono_install_callbacks (&callbacks);
#ifndef HOST_WIN32
mono_w32handle_init ();
#endif
mono_thread_info_runtime_init (&ticallbacks);
if (g_hasenv ("MONO_DEBUG")) {
mini_parse_debug_options ();
}
mono_code_manager_init (mono_compile_aot);
#ifdef MONO_ARCH_HAVE_CODE_CHUNK_TRACKING
static const MonoCodeManagerCallbacks code_manager_callbacks = {
#undef MONO_CODE_MANAGER_CALLBACK
#define MONO_CODE_MANAGER_CALLBACK(ret, name, sig) mono_arch_code_ ## name,
MONO_CODE_MANAGER_CALLBACKS
};
mono_code_manager_install_callbacks (&code_manager_callbacks);
#endif
mono_hwcap_init ();
mono_arch_cpu_init ();
mono_arch_init ();
mono_unwind_init ();
if (mini_debug_options.lldb || g_hasenv ("MONO_LLDB")) {
mono_lldb_init ("");
mono_dont_free_domains = TRUE;
}
#ifdef ENABLE_LLVM
if (mono_use_llvm)
mono_llvm_init (!mono_compile_aot);
#endif
mono_trampolines_init ();
if (default_opt & MONO_OPT_AOT)
mono_aot_init ();
mono_component_debugger ()->init ();
#ifdef MONO_ARCH_GSHARED_SUPPORTED
mono_set_generic_sharing_supported (TRUE);
#endif
mono_thread_info_signals_init ();
mono_init_native_crash_info ();
#ifndef MONO_CROSS_COMPILE
mono_runtime_install_handlers ();
#endif
mono_threads_install_cleanup (mini_thread_cleanup);
mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
mono_install_get_class_from_name (mono_aot_get_class_from_name);
mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
mono_profiler_state.context_enable = mini_profiler_context_enable;
mono_profiler_state.context_get_this = mini_profiler_context_get_this;
mono_profiler_state.context_get_argument = mini_profiler_context_get_argument;
mono_profiler_state.context_get_local = mini_profiler_context_get_local;
mono_profiler_state.context_get_result = mini_profiler_context_get_result;
mono_profiler_state.context_free_buffer = mini_profiler_context_free_buffer;
if (g_hasenv ("MONO_PROFILE")) {
gchar *profile_env = g_getenv ("MONO_PROFILE");
mini_add_profiler_argument (profile_env);
g_free (profile_env);
}
if (profile_options)
for (guint i = 0; i < profile_options->len; i++)
mono_profiler_load ((const char *) g_ptr_array_index (profile_options, i));
mono_profiler_started ();
if (mini_debug_options.collect_pagefault_stats)
mono_aot_set_make_unreadable (TRUE);
/* set no-exec before the default ALC is created */
if (mono_compile_aot) {
/*
* Avoid running managed code when AOT compiling, since the platform
* might only support aot-only execution.
*/
mono_runtime_set_no_exec (TRUE);
}
if (runtime_version)
domain = mono_init_version (filename, runtime_version);
else
domain = mono_init_from_assembly (filename, filename);
if (mono_compile_aot)
mono_component_diagnostics_server ()->disable ();
mono_component_event_pipe ()->init ();
// EventPipe up is now up and running, convert 100ns ticks since runtime init into EventPipe compatbile timestamp (using negative delta to represent timestamp in past).
// Add RuntimeInit execution checkpoint using converted timestamp.
mono_component_event_pipe ()->add_rundown_execution_checkpoint_2 ("RuntimeInit", mono_component_event_pipe ()->convert_100ns_ticks_to_timestamp_t (-mono_component_event_pipe_100ns_ticks_stop ()));
if (mono_aot_only) {
/* This helps catch code allocation requests */
mono_code_manager_set_read_only (mono_mem_manager_get_ambient ()->code_mp);
mono_marshal_use_aot_wrappers (TRUE);
}
if (mono_llvm_only) {
mono_install_imt_trampoline_builder (mini_llvmonly_get_imt_trampoline);
mono_set_always_build_imt_trampolines (TRUE);
} else if (mono_aot_only) {
mono_install_imt_trampoline_builder (mono_aot_get_imt_trampoline);
} else {
mono_install_imt_trampoline_builder (mono_arch_build_imt_trampoline);
}
/*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
mono_arch_finish_init ();
/* This must come after mono_init () in the aot-only case */
mono_exceptions_init ();
/* This should come after mono_init () too */
mini_gc_init ();
mono_create_icall_signatures ();
register_counters ();
#define JIT_CALLS_WORK
#ifdef JIT_CALLS_WORK
/* Needs to be called here since register_jit_icall depends on it */
mono_marshal_init ();
mono_arch_register_lowlevel_calls ();
register_icalls ();
mono_generic_sharing_init ();
#endif
#ifdef MONO_ARCH_SIMD_INTRINSICS
mono_simd_intrinsics_init ();
#endif
register_trampolines (domain);
mono_mem_account_register_counters ();
#define JIT_RUNTIME_WORKS
#ifdef JIT_RUNTIME_WORKS
mono_install_runtime_cleanup (runtime_cleanup);
mono_runtime_init_checked (domain, (MonoThreadStartCB)mono_thread_start_cb, mono_thread_attach_cb, error);
mono_error_assert_ok (error);
mono_thread_internal_attach (domain);
MONO_PROFILER_RAISE (thread_name, (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ()), "Main"));
#endif
mono_threads_set_runtime_startup_finished ();
mono_component_event_pipe ()->finish_init ();
#ifdef ENABLE_EXPERIMENT_TIERED
if (!mono_compile_aot) {
/* create compilation thread in background */
mini_tiered_init ();
}
#endif
if (mono_profiler_sampling_enabled ())
mono_runtime_setup_stat_profiler ();
MONO_PROFILER_RAISE (runtime_initialized, ());
MONO_VES_INIT_END ();
return domain;
}
static void
register_icalls (void)
{
mono_add_internal_call_internal ("System.Diagnostics.StackFrame::get_frame_info",
ves_icall_get_frame_info);
mono_add_internal_call_internal ("System.Diagnostics.StackTrace::get_trace",
ves_icall_get_trace);
mono_add_internal_call_internal ("Mono.Runtime::mono_runtime_install_handlers",
mono_runtime_install_handlers);
/*
* It's important that we pass `TRUE` as the last argument here, as
* it causes the JIT to omit a wrapper for these icalls. If the JIT
* *did* emit a wrapper, we'd be looking at infinite recursion since
* the wrapper would call the icall which would call the wrapper and
* so on.
*/
register_icall (mono_profiler_raise_method_enter, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_method_leave, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_method_tail_call, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_exception_clause, mono_icall_sig_void_ptr_int_int_object, TRUE);
register_icall (mono_trace_enter_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_trace_leave_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_trace_tail_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
g_assert (mono_get_lmf_addr == mono_tls_get_lmf_addr);
register_icall (mono_domain_get, mono_icall_sig_ptr, TRUE);
register_icall (mini_llvmonly_throw_exception, mono_icall_sig_void_object, TRUE);
register_icall (mini_llvmonly_rethrow_exception, mono_icall_sig_void_object, TRUE);
register_icall (mini_llvmonly_throw_corlib_exception, mono_icall_sig_void_int, TRUE);
register_icall (mini_llvmonly_resume_exception, mono_icall_sig_void, TRUE);
register_icall (mini_llvmonly_resume_exception_il_state, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mini_llvmonly_load_exception, mono_icall_sig_object, TRUE);
register_icall (mini_llvmonly_clear_exception, NULL, TRUE);
register_icall (mini_llvmonly_match_exception, mono_icall_sig_int_ptr_int_int_ptr_object, TRUE);
#if defined(ENABLE_LLVM) && defined(HAVE_UNWIND_H)
register_icall (mono_llvm_set_unhandled_exception_handler, NULL, TRUE);
// FIXME: This is broken
#ifndef TARGET_WASM
register_icall (mono_debug_personality, mono_icall_sig_int_int_int_ptr_ptr_ptr, TRUE);
#endif
#endif
if (!mono_llvm_only) {
register_dyn_icall (mono_get_throw_exception (), mono_arch_throw_exception, mono_icall_sig_void_object, TRUE);
register_dyn_icall (mono_get_rethrow_exception (), mono_arch_rethrow_exception, mono_icall_sig_void_object, TRUE);
register_dyn_icall (mono_get_throw_corlib_exception (), mono_arch_throw_corlib_exception, mono_icall_sig_void_ptr, TRUE);
}
register_icall (mono_thread_get_undeniable_exception, mono_icall_sig_object, FALSE);
register_icall (ves_icall_thread_finish_async_abort, mono_icall_sig_void, FALSE);
register_icall (mono_thread_interruption_checkpoint, mono_icall_sig_object, FALSE);
register_icall (mono_thread_force_interruption_checkpoint_noraise, mono_icall_sig_object, FALSE);
register_icall (mono_threads_state_poll, mono_icall_sig_void, FALSE);
#ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
register_opcode_emulation (OP_LMUL, __emul_lmul, mono_icall_sig_long_long_long, mono_llmult, FALSE);
register_opcode_emulation (OP_LDIV, __emul_ldiv, mono_icall_sig_long_long_long, mono_lldiv, FALSE);
register_opcode_emulation (OP_LDIV_UN, __emul_ldiv_un, mono_icall_sig_long_long_long, mono_lldiv_un, FALSE);
register_opcode_emulation (OP_LREM, __emul_lrem, mono_icall_sig_long_long_long, mono_llrem, FALSE);
register_opcode_emulation (OP_LREM_UN, __emul_lrem_un, mono_icall_sig_long_long_long, mono_llrem_un, FALSE);
#endif
#if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
register_opcode_emulation (OP_LMUL_OVF_UN, __emul_lmul_ovf_un, mono_icall_sig_long_long_long, mono_llmult_ovf_un, FALSE);
register_opcode_emulation (OP_LMUL_OVF, __emul_lmul_ovf, mono_icall_sig_long_long_long, mono_llmult_ovf, FALSE);
register_opcode_emulation (OP_LMUL_OVF_UN_OOM, __emul_lmul_ovf_un_oom, mono_icall_sig_long_long_long, mono_llmult_ovf_un_oom, FALSE);
#endif
#ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
register_opcode_emulation (OP_LSHL, __emul_lshl, mono_icall_sig_long_long_int32, mono_lshl, TRUE);
register_opcode_emulation (OP_LSHR, __emul_lshr, mono_icall_sig_long_long_int32, mono_lshr, TRUE);
register_opcode_emulation (OP_LSHR_UN, __emul_lshr_un, mono_icall_sig_long_long_int32, mono_lshr_un, TRUE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
register_opcode_emulation (OP_IDIV, __emul_op_idiv, mono_icall_sig_int32_int32_int32, mono_idiv, FALSE);
register_opcode_emulation (OP_IDIV_UN, __emul_op_idiv_un, mono_icall_sig_int32_int32_int32, mono_idiv_un, FALSE);
register_opcode_emulation (OP_IREM, __emul_op_irem, mono_icall_sig_int32_int32_int32, mono_irem, FALSE);
register_opcode_emulation (OP_IREM_UN, __emul_op_irem_un, mono_icall_sig_int32_int32_int32, mono_irem_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_MUL_DIV
register_opcode_emulation (OP_IMUL, __emul_op_imul, mono_icall_sig_int32_int32_int32, mono_imul, TRUE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
register_opcode_emulation (OP_IMUL_OVF, __emul_op_imul_ovf, mono_icall_sig_int32_int32_int32, mono_imul_ovf, FALSE);
register_opcode_emulation (OP_IMUL_OVF_UN, __emul_op_imul_ovf_un, mono_icall_sig_int32_int32_int32, mono_imul_ovf_un, FALSE);
register_opcode_emulation (OP_IMUL_OVF_UN_OOM, __emul_op_imul_ovf_un_oom, mono_icall_sig_int32_int32_int32, mono_imul_ovf_un_oom, FALSE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
register_opcode_emulation (OP_FDIV, __emul_fdiv, mono_icall_sig_double_double_double, mono_fdiv, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FCONV_TO_U8
register_opcode_emulation (OP_FCONV_TO_U8, __emul_fconv_to_u8, mono_icall_sig_ulong_double, mono_fconv_u8, FALSE);
register_opcode_emulation (OP_RCONV_TO_U8, __emul_rconv_to_u8, mono_icall_sig_ulong_float, mono_rconv_u8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FCONV_TO_U4
register_opcode_emulation (OP_FCONV_TO_U4, __emul_fconv_to_u4, mono_icall_sig_uint32_double, mono_fconv_u4, FALSE);
register_opcode_emulation (OP_RCONV_TO_U4, __emul_rconv_to_u4, mono_icall_sig_uint32_float, mono_rconv_u4, FALSE);
#endif
register_opcode_emulation (OP_FCONV_TO_OVF_I8, __emul_fconv_to_ovf_i8, mono_icall_sig_long_double, mono_fconv_ovf_i8, FALSE);
register_opcode_emulation (OP_FCONV_TO_OVF_U8, __emul_fconv_to_ovf_u8, mono_icall_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
register_opcode_emulation (OP_RCONV_TO_OVF_I8, __emul_rconv_to_ovf_i8, mono_icall_sig_long_float, mono_rconv_ovf_i8, FALSE);
register_opcode_emulation (OP_RCONV_TO_OVF_U8, __emul_rconv_to_ovf_u8, mono_icall_sig_ulong_float, mono_rconv_ovf_u8, FALSE);
#ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
register_opcode_emulation (OP_FCONV_TO_I8, __emul_fconv_to_i8, mono_icall_sig_long_double, mono_fconv_i8, FALSE);
register_opcode_emulation (OP_RCONV_TO_I8, __emul_rconv_to_i8, mono_icall_sig_long_float, mono_rconv_i8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_CONV_R8_UN
register_opcode_emulation (OP_ICONV_TO_R_UN, __emul_iconv_to_r_un, mono_icall_sig_double_int32, mono_conv_to_r8_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
register_opcode_emulation (OP_LCONV_TO_R8, __emul_lconv_to_r8, mono_icall_sig_double_long, mono_lconv_to_r8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
register_opcode_emulation (OP_LCONV_TO_R4, __emul_lconv_to_r4, mono_icall_sig_float_long, mono_lconv_to_r4, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
register_opcode_emulation (OP_LCONV_TO_R_UN, __emul_lconv_to_r8_un, mono_icall_sig_double_long, mono_lconv_to_r8_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FREM
register_opcode_emulation (OP_FREM, __emul_frem, mono_icall_sig_double_double_double, mono_fmod, FALSE);
register_opcode_emulation (OP_RREM, __emul_rrem, mono_icall_sig_float_float_float, fmodf, FALSE);
#endif
#ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
if (mono_arch_is_soft_float ()) {
register_opcode_emulation (OP_FSUB, __emul_fsub, mono_icall_sig_double_double_double, mono_fsub, FALSE);
register_opcode_emulation (OP_FADD, __emul_fadd, mono_icall_sig_double_double_double, mono_fadd, FALSE);
register_opcode_emulation (OP_FMUL, __emul_fmul, mono_icall_sig_double_double_double, mono_fmul, FALSE);
register_opcode_emulation (OP_FNEG, __emul_fneg, mono_icall_sig_double_double, mono_fneg, FALSE);
register_opcode_emulation (OP_ICONV_TO_R8, __emul_iconv_to_r8, mono_icall_sig_double_int32, mono_conv_to_r8, FALSE);
register_opcode_emulation (OP_ICONV_TO_R4, __emul_iconv_to_r4, mono_icall_sig_double_int32, mono_conv_to_r4, FALSE);
register_opcode_emulation (OP_FCONV_TO_R4, __emul_fconv_to_r4, mono_icall_sig_double_double, mono_fconv_r4, FALSE);
register_opcode_emulation (OP_FCONV_TO_I1, __emul_fconv_to_i1, mono_icall_sig_int8_double, mono_fconv_i1, FALSE);
register_opcode_emulation (OP_FCONV_TO_I2, __emul_fconv_to_i2, mono_icall_sig_int16_double, mono_fconv_i2, FALSE);
register_opcode_emulation (OP_FCONV_TO_I4, __emul_fconv_to_i4, mono_icall_sig_int32_double, mono_fconv_i4, FALSE);
register_opcode_emulation (OP_FCONV_TO_U1, __emul_fconv_to_u1, mono_icall_sig_uint8_double, mono_fconv_u1, FALSE);
register_opcode_emulation (OP_FCONV_TO_U2, __emul_fconv_to_u2, mono_icall_sig_uint16_double, mono_fconv_u2, FALSE);
#if TARGET_SIZEOF_VOID_P == 4
register_opcode_emulation (OP_FCONV_TO_I, __emul_fconv_to_i, mono_icall_sig_int32_double, mono_fconv_i4, FALSE);
#endif
register_opcode_emulation (OP_FBEQ, __emul_fcmp_eq, mono_icall_sig_uint32_double_double, mono_fcmp_eq, FALSE);
register_opcode_emulation (OP_FBLT, __emul_fcmp_lt, mono_icall_sig_uint32_double_double, mono_fcmp_lt, FALSE);
register_opcode_emulation (OP_FBGT, __emul_fcmp_gt, mono_icall_sig_uint32_double_double, mono_fcmp_gt, FALSE);
register_opcode_emulation (OP_FBLE, __emul_fcmp_le, mono_icall_sig_uint32_double_double, mono_fcmp_le, FALSE);
register_opcode_emulation (OP_FBGE, __emul_fcmp_ge, mono_icall_sig_uint32_double_double, mono_fcmp_ge, FALSE);
register_opcode_emulation (OP_FBNE_UN, __emul_fcmp_ne_un, mono_icall_sig_uint32_double_double, mono_fcmp_ne_un, FALSE);
register_opcode_emulation (OP_FBLT_UN, __emul_fcmp_lt_un, mono_icall_sig_uint32_double_double, mono_fcmp_lt_un, FALSE);
register_opcode_emulation (OP_FBGT_UN, __emul_fcmp_gt_un, mono_icall_sig_uint32_double_double, mono_fcmp_gt_un, FALSE);
register_opcode_emulation (OP_FBLE_UN, __emul_fcmp_le_un, mono_icall_sig_uint32_double_double, mono_fcmp_le_un, FALSE);
register_opcode_emulation (OP_FBGE_UN, __emul_fcmp_ge_un, mono_icall_sig_uint32_double_double, mono_fcmp_ge_un, FALSE);
register_opcode_emulation (OP_FCEQ, __emul_fcmp_ceq, mono_icall_sig_uint32_double_double, mono_fceq, FALSE);
register_opcode_emulation (OP_FCGT, __emul_fcmp_cgt, mono_icall_sig_uint32_double_double, mono_fcgt, FALSE);
register_opcode_emulation (OP_FCGT_UN, __emul_fcmp_cgt_un, mono_icall_sig_uint32_double_double, mono_fcgt_un, FALSE);
register_opcode_emulation (OP_FCLT, __emul_fcmp_clt, mono_icall_sig_uint32_double_double, mono_fclt, FALSE);
register_opcode_emulation (OP_FCLT_UN, __emul_fcmp_clt_un, mono_icall_sig_uint32_double_double, mono_fclt_un, FALSE);
register_icall (mono_fload_r4, mono_icall_sig_double_ptr, FALSE);
register_icall (mono_fstore_r4, mono_icall_sig_void_double_ptr, FALSE);
register_icall (mono_fload_r4_arg, mono_icall_sig_uint32_double, FALSE);
register_icall (mono_isfinite_double, mono_icall_sig_int32_double, FALSE);
}
#endif
register_icall (mono_ckfinite, mono_icall_sig_double_double, FALSE);
#ifdef COMPRESSED_INTERFACE_BITMAP
register_icall (mono_class_interface_match, mono_icall_sig_uint32_ptr_int32, TRUE);
#endif
/* other jit icalls */
register_icall (ves_icall_mono_delegate_ctor, mono_icall_sig_void_object_object_ptr, FALSE);
register_icall (ves_icall_mono_delegate_ctor_interp, mono_icall_sig_void_object_object_ptr, FALSE);
register_icall (mono_class_static_field_address,
mono_icall_sig_ptr_ptr, FALSE);
register_icall (mono_ldtoken_wrapper, mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_ldtoken_wrapper_generic_shared,
mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_get_special_static_data, mono_icall_sig_ptr_int, FALSE);
register_icall (mono_helper_stelem_ref_check, mono_icall_sig_void_object_object, FALSE);
register_icall (ves_icall_object_new, mono_icall_sig_object_ptr, FALSE);
register_icall (ves_icall_object_new_specific, mono_icall_sig_object_ptr, FALSE);
register_icall (ves_icall_array_new_specific, mono_icall_sig_object_ptr_int32, FALSE);
register_icall (ves_icall_runtime_class_init, mono_icall_sig_void_ptr, FALSE);
register_icall (mono_ldftn, mono_icall_sig_ptr_ptr, FALSE);
register_icall (mono_ldvirtfn, mono_icall_sig_ptr_object_ptr, FALSE);
register_icall (mono_ldvirtfn_gshared, mono_icall_sig_ptr_object_ptr, FALSE);
register_icall (mono_helper_compile_generic_method, mono_icall_sig_ptr_object_ptr_ptr, FALSE);
register_icall (mono_helper_ldstr, mono_icall_sig_object_ptr_int, FALSE);
register_icall (mono_helper_ldstr_mscorlib, mono_icall_sig_object_int, FALSE);
register_icall (mono_helper_newobj_mscorlib, mono_icall_sig_object_int, FALSE);
register_icall (mono_value_copy_internal, mono_icall_sig_void_ptr_ptr_ptr, FALSE);
register_icall (mono_object_castclass_unbox, mono_icall_sig_object_object_ptr, FALSE);
register_icall (mono_break, NULL, TRUE);
register_icall (mono_create_corlib_exception_0, mono_icall_sig_object_int, TRUE);
register_icall (mono_create_corlib_exception_1, mono_icall_sig_object_int_object, TRUE);
register_icall (mono_create_corlib_exception_2, mono_icall_sig_object_int_object_object, TRUE);
register_icall (mono_array_new_1, mono_icall_sig_object_ptr_int, FALSE);
register_icall (mono_array_new_2, mono_icall_sig_object_ptr_int_int, FALSE);
register_icall (mono_array_new_3, mono_icall_sig_object_ptr_int_int_int, FALSE);
register_icall (mono_array_new_4, mono_icall_sig_object_ptr_int_int_int_int, FALSE);
register_icall (mono_array_new_n_icall, mono_icall_sig_object_ptr_int_ptr, FALSE);
register_icall (mono_get_native_calli_wrapper, mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_resume_unwind, mono_icall_sig_void_ptr, TRUE);
register_icall (mono_gsharedvt_constrained_call, mono_icall_sig_object_ptr_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_gsharedvt_value_copy, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
//WARNING We do runtime selection here but the string *MUST* be to a fallback function that has same signature and behavior
MonoRangeCopyFunction const mono_gc_wbarrier_range_copy = mono_gc_get_range_copy_func ();
register_icall_no_wrapper (mono_gc_wbarrier_range_copy, mono_icall_sig_void_ptr_ptr_int);
register_icall (mono_object_castclass_with_cache, mono_icall_sig_object_object_ptr_ptr, FALSE);
register_icall (mono_object_isinst_with_cache, mono_icall_sig_object_object_ptr_ptr, FALSE);
register_icall (mono_generic_class_init, mono_icall_sig_void_ptr, FALSE);
register_icall (mono_fill_class_rgctx, mono_icall_sig_ptr_ptr_int, FALSE);
register_icall (mono_fill_method_rgctx, mono_icall_sig_ptr_ptr_int, FALSE);
register_dyn_icall (mono_component_debugger ()->user_break, mono_debugger_agent_user_break, mono_icall_sig_void, FALSE);
register_icall (mini_llvm_init_method, mono_icall_sig_void_ptr_ptr_ptr_ptr, TRUE);
register_icall_no_wrapper (mini_llvmonly_resolve_iface_call_gsharedvt, mono_icall_sig_ptr_object_int_ptr_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_vcall_gsharedvt, mono_icall_sig_ptr_object_int_ptr_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_vcall_gsharedvt_fast, mono_icall_sig_ptr_object_int);
register_icall_no_wrapper (mini_llvmonly_resolve_generic_virtual_call, mono_icall_sig_ptr_ptr_int_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_generic_virtual_iface_call, mono_icall_sig_ptr_ptr_int_ptr);
/* This needs a wrapper so it can have a preserveall cconv */
register_icall (mini_llvmonly_init_vtable_slot, mono_icall_sig_ptr_ptr_int, FALSE);
register_icall (mini_llvmonly_init_delegate, mono_icall_sig_void_object_ptr, TRUE);
register_icall (mini_llvmonly_init_delegate_virtual, mono_icall_sig_void_object_object_ptr, TRUE);
register_icall (mini_llvmonly_throw_nullref_exception, mono_icall_sig_void, TRUE);
register_icall (mini_llvmonly_throw_aot_failed_exception, mono_icall_sig_void_ptr, TRUE);
register_icall (mini_llvmonly_pop_lmf, mono_icall_sig_void_ptr, TRUE);
register_icall (mini_llvmonly_interp_entry_gsharedvt, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_get_assembly_object, mono_icall_sig_object_ptr, TRUE);
register_icall (mono_get_method_object, mono_icall_sig_object_ptr, TRUE);
register_icall (mono_throw_method_access, mono_icall_sig_void_ptr_ptr, FALSE);
register_icall (mono_throw_bad_image, mono_icall_sig_void, FALSE);
register_icall (mono_throw_not_supported, mono_icall_sig_void, FALSE);
register_icall (mono_throw_platform_not_supported, mono_icall_sig_void, FALSE);
register_icall (mono_throw_invalid_program, mono_icall_sig_void_ptr, FALSE);
register_icall_no_wrapper (mono_dummy_jit_icall, mono_icall_sig_void);
//register_icall_no_wrapper (mono_dummy_jit_icall_val, mono_icall_sig_void_ptr);
register_icall_with_wrapper (mono_monitor_enter_internal, mono_icall_sig_int32_obj);
register_icall_with_wrapper (mono_monitor_enter_v4_internal, mono_icall_sig_void_obj_ptr);
register_icall_no_wrapper (mono_monitor_enter_fast, mono_icall_sig_int_obj);
register_icall_no_wrapper (mono_monitor_enter_v4_fast, mono_icall_sig_int_obj_ptr);
#ifdef TARGET_IOS
register_icall (pthread_getspecific, mono_icall_sig_ptr_ptr, TRUE);
#endif
/* Register tls icalls */
register_icall_no_wrapper (mono_tls_get_thread_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_jit_tls_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_domain_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_sgen_thread_info_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_lmf_addr_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_interp_entry_from_trampoline, mono_icall_sig_void_ptr_ptr);
register_icall_no_wrapper (mono_interp_to_native_trampoline, mono_icall_sig_void_ptr_ptr);
#ifdef MONO_ARCH_HAS_REGISTER_ICALL
mono_arch_register_icall ();
#endif
}
MonoJitStats mono_jit_stats = {0};
/**
* Counters of mono_stats and mono_jit_stats can be read without locking during shutdown.
* For all other contexts, assumes that the domain lock is held.
* MONO_NO_SANITIZE_THREAD tells Clang's ThreadSanitizer to hide all reports of these (known) races.
*/
MONO_NO_SANITIZE_THREAD
void
mono_runtime_print_stats (void)
{
if (mono_jit_stats.enabled) {
g_print ("Mono Jit statistics\n");
g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio / 100.0,
mono_jit_stats.max_ratio_method);
g_print ("Biggest method: %" G_GINT32_FORMAT " (%s)\n", mono_jit_stats.biggest_method_size,
mono_jit_stats.biggest_method);
g_print ("Delegates created: %" G_GINT32_FORMAT "\n", mono_stats.delegate_creations);
g_print ("Initialized classes: %" G_GINT32_FORMAT "\n", mono_stats.initialized_class_count);
g_print ("Used classes: %" G_GINT32_FORMAT "\n", mono_stats.used_class_count);
g_print ("Generic vtables: %" G_GINT32_FORMAT "\n", mono_stats.generic_vtable_count);
g_print ("Methods: %" G_GINT32_FORMAT "\n", mono_stats.method_count);
g_print ("Static data size: %" G_GINT32_FORMAT "\n", mono_stats.class_static_data_size);
g_print ("VTable data size: %" G_GINT32_FORMAT "\n", mono_stats.class_vtable_size);
g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
g_print ("\nInitialized classes: %" G_GINT32_FORMAT "\n", mono_stats.generic_class_count);
g_print ("Inflated types: %" G_GINT32_FORMAT "\n", mono_stats.inflated_type_count);
g_print ("Generics virtual invokes: %" G_GINT32_FORMAT "\n", mono_jit_stats.generic_virtual_invocations);
g_print ("Sharable generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_sharable_methods);
g_print ("Unsharable generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_unsharable_methods);
g_print ("Shared generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_shared_methods);
g_print ("Shared vtype generic methods: %" G_GINT32_FORMAT "\n", mono_stats.gsharedvt_methods);
g_print ("IMT tables size: %" G_GINT32_FORMAT "\n", mono_stats.imt_tables_size);
g_print ("IMT number of tables: %" G_GINT32_FORMAT "\n", mono_stats.imt_number_of_tables);
g_print ("IMT number of methods: %" G_GINT32_FORMAT "\n", mono_stats.imt_number_of_methods);
g_print ("IMT used slots: %" G_GINT32_FORMAT "\n", mono_stats.imt_used_slots);
g_print ("IMT colliding slots: %" G_GINT32_FORMAT "\n", mono_stats.imt_slots_with_collisions);
g_print ("IMT max collisions: %" G_GINT32_FORMAT "\n", mono_stats.imt_max_collisions_in_slot);
g_print ("IMT methods at max col: %" G_GINT32_FORMAT "\n", mono_stats.imt_method_count_when_max_collisions);
g_print ("IMT trampolines size: %" G_GINT32_FORMAT "\n", mono_stats.imt_trampolines_size);
g_print ("JIT info table inserts: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_insert_count);
g_print ("JIT info table removes: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_remove_count);
g_print ("JIT info table lookups: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_lookup_count);
mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, NULL);
g_print ("\n");
}
}
static void
jit_stats_cleanup (void)
{
g_free (mono_jit_stats.max_ratio_method);
mono_jit_stats.max_ratio_method = NULL;
g_free (mono_jit_stats.biggest_method);
mono_jit_stats.biggest_method = NULL;
}
static void
runtime_cleanup (MonoDomain *domain, gpointer user_data)
{
mini_cleanup (domain);
}
void
mini_cleanup (MonoDomain *domain)
{
if (mono_stats.enabled)
g_printf ("Printing runtime stats at shutdown\n");
mono_runtime_print_stats ();
jit_stats_cleanup ();
mono_jit_dump_cleanup ();
mini_get_interp_callbacks ()->cleanup ();
mono_component_event_pipe ()->shutdown ();
mono_component_diagnostics_server ()->shutdown ();
}
void
mono_set_defaults (int verbose_level, guint32 opts)
{
mini_verbose = verbose_level;
mono_set_optimizations (opts);
}
void
mono_disable_optimizations (guint32 opts)
{
default_opt &= ~opts;
}
void
mono_set_optimizations (guint32 opts)
{
if (opts & MONO_OPT_AGGRESSIVE_INLINING)
opts |= MONO_OPT_INLINE;
default_opt = opts;
default_opt_set = TRUE;
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
#else
if (mono_llvm_only)
mono_set_generic_sharing_vt_supported (TRUE);
#endif
}
void
mono_set_verbose_level (guint32 level)
{
mini_verbose = level;
}
static const char*
mono_get_runtime_build_version (void)
{
return FULL_VERSION;
}
/**
* mono_get_runtime_build_info:
* The returned string is owned by the caller. The returned string
* format is <code>VERSION (FULL_VERSION BUILD_DATE)</code> and build date is optional.
* \returns the runtime version + build date in string format.
*/
char*
mono_get_runtime_build_info (void)
{
if (mono_build_date)
return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
else
return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
}
static void
mono_precompile_assembly (MonoAssembly *ass, void *user_data)
{
GHashTable *assemblies = (GHashTable*)user_data;
MonoImage *image = mono_assembly_get_image_internal (ass);
MonoMethod *method, *invoke;
int i, count = 0;
if (g_hash_table_lookup (assemblies, ass))
return;
g_hash_table_insert (assemblies, ass, ass);
if (mini_verbose > 0)
printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
ERROR_DECL (error);
method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
if (!method) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
continue;
}
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
continue;
if (method->is_generic || mono_class_is_gtd (method->klass))
continue;
count++;
if (mini_verbose > 1) {
char * desc = mono_method_full_name (method, TRUE);
g_print ("Compiling %d %s\n", count, desc);
g_free (desc);
}
mono_compile_method_checked (method, error);
if (!is_ok (error)) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
continue;
}
if (strcmp (method->name, "Finalize") == 0) {
invoke = mono_marshal_get_runtime_invoke (method, FALSE);
mono_compile_method_checked (invoke, error);
mono_error_assert_ok (error);
}
}
/* Load and precompile referenced assemblies as well */
for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
mono_assembly_load_reference (image, i);
if (image->references [i])
mono_precompile_assembly (image->references [i], assemblies);
}
}
void mono_precompile_assemblies ()
{
GHashTable *assemblies = g_hash_table_new (NULL, NULL);
mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
g_hash_table_destroy (assemblies);
}
/*
* Used by LLVM.
* Have to export this for AOT.
*/
void
mono_personality (void)
{
/* Not used */
g_assert_not_reached ();
}
static MonoBreakPolicy
always_insert_breakpoint (MonoMethod *method)
{
return MONO_BREAK_POLICY_ALWAYS;
}
static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
/**
* mono_set_break_policy:
* \param policy_callback the new callback function
*
* Allow embedders to decide whether to actually obey breakpoint instructions
* (both break IL instructions and \c Debugger.Break method calls), for example
* to not allow an app to be aborted by a perfectly valid IL opcode when executing
* untrusted or semi-trusted code.
*
* \p policy_callback will be called every time a break point instruction needs to
* be inserted with the method argument being the method that calls \c Debugger.Break
* or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
* if it wants the breakpoint to not be effective in the given method.
* \c MONO_BREAK_POLICY_ALWAYS is the default.
*/
void
mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
{
if (policy_callback)
break_policy_func = policy_callback;
else
break_policy_func = always_insert_breakpoint;
}
gboolean
mini_should_insert_breakpoint (MonoMethod *method)
{
switch (break_policy_func (method)) {
case MONO_BREAK_POLICY_ALWAYS:
return TRUE;
case MONO_BREAK_POLICY_NEVER:
return FALSE;
case MONO_BREAK_POLICY_ON_DBG:
g_warning ("mdb no longer supported");
return FALSE;
default:
g_warning ("Incorrect value returned from break policy callback");
return FALSE;
}
}
// Custom handlers currently only implemented by Windows.
#ifndef HOST_WIN32
gboolean
mono_runtime_install_custom_handlers (const char *handlers)
{
return FALSE;
}
void
mono_runtime_install_custom_handlers_usage (void)
{
fprintf (stdout,
"Custom Handlers:\n"
" --handlers=HANDLERS Enable handler support, HANDLERS is a comma\n"
" separated list of available handlers to install.\n"
"\n"
"No handlers supported on current platform.\n");
}
#endif /* HOST_WIN32 */
static void
mini_invalidate_transformed_interp_methods (MonoAssemblyLoadContext *alc G_GNUC_UNUSED, uint32_t generation G_GNUC_UNUSED)
{
mini_get_interp_callbacks ()->invalidate_transformed ();
}
static void
mini_interp_jit_info_foreach(InterpJitInfoFunc func, gpointer user_data)
{
mini_get_interp_callbacks ()->jit_info_foreach (func, user_data);
}
static gboolean
mini_interp_sufficient_stack (gsize size)
{
return mini_get_interp_callbacks ()->sufficient_stack (size);
}
/*
* mini_get_default_mem_manager:
*
* Return a memory manager which can be used for default allocation.
* FIXME: Review all callers and change them to allocate from a
* class/method/assembly specific memory manager.
*/
MonoMemoryManager*
mini_get_default_mem_manager (void)
{
return mono_mem_manager_get_ambient ();
}
gpointer
mini_alloc_generic_virtual_trampoline (MonoVTable *vtable, int size)
{
static gboolean inited = FALSE;
static int generic_virtual_trampolines_size = 0;
if (!inited) {
mono_counters_register ("Generic virtual trampoline bytes",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &generic_virtual_trampolines_size);
inited = TRUE;
}
generic_virtual_trampolines_size += size;
return mono_mem_manager_code_reserve (m_class_get_mem_manager (vtable->klass), size);
}
MonoException*
mini_get_stack_overflow_ex (void)
{
return mono_get_root_domain ()->stack_overflow_ex;
}
const MonoEECallbacks*
mini_get_interp_callbacks_api (void)
{
return mono_interp_callbacks_pointer;
}
| /**
* \file
* Runtime code for the JIT
*
* Authors:
* Paolo Molaro ([email protected])
* Dietmar Maurer ([email protected])
*
* Copyright 2002-2003 Ximian, Inc.
* Copyright 2003-2010 Novell, Inc.
* Copyright 2011-2015 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>
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <math.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <signal.h>
#include <mono/utils/memcheck.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/assembly-internals.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/class.h>
#include <mono/metadata/object.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/runtime.h>
#include <mono/metadata/reflection-internals.h>
#include <mono/metadata/monitor.h>
#include <mono/metadata/icall-internals.h>
#include <mono/metadata/loader-internals.h>
#define MONO_MATH_DECLARE_ALL 1
#include <mono/utils/mono-math.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-path.h>
#include <mono/utils/mono-tls.h>
#include <mono/utils/mono-hwcap.h>
#include <mono/utils/dtrace.h>
#include <mono/utils/mono-signal-handler.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/checked-build.h>
#include <mono/utils/mono-compiler.h>
#include <mono/utils/mono-proclib.h>
#include <mono/utils/mono-time.h>
#include <mono/metadata/w32handle.h>
#include <mono/metadata/components.h>
#include <mono/mini/debugger-agent-external.h>
#include "mini.h"
#include "seq-points.h"
#include <string.h>
#include <ctype.h>
#include "trace.h"
#include "aot-compiler.h"
#include "aot-runtime.h"
#include "llvmonly-runtime.h"
#include "jit-icalls.h"
#include "mini-gc.h"
#include "mini-llvm.h"
#include "llvm-runtime.h"
#include "lldb.h"
#include "mini-runtime.h"
#include "interp/interp.h"
#ifdef MONO_ARCH_LLVM_SUPPORTED
#ifdef ENABLE_LLVM
#include "mini-llvm-cpp.h"
#include "llvm-jit.h"
#endif
#endif
#include "mono/metadata/icall-signatures.h"
#include "mono/utils/mono-tls-inline.h"
static guint32 default_opt = 0;
static gboolean default_opt_set = FALSE;
MonoMethodDesc *mono_stats_method_desc;
gboolean mono_compile_aot = FALSE;
/* If this is set, no code is generated dynamically, everything is taken from AOT files */
gboolean mono_aot_only = FALSE;
/* Same as mono_aot_only, but only LLVM compiled code is used, no trampolines */
gboolean mono_llvm_only = FALSE;
/* By default, don't require AOT but attempt to probe */
MonoAotMode mono_aot_mode = MONO_AOT_MODE_NORMAL;
MonoEEFeatures mono_ee_features;
const char *mono_build_date;
gboolean mono_do_signal_chaining;
gboolean mono_do_crash_chaining;
int mini_verbose = 0;
/*
* This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
* it can load AOT code compiled by LLVM.
*/
gboolean mono_use_llvm = FALSE;
gboolean mono_use_fast_math = FALSE;
// Lists of allowlisted and blocklisted CPU features
MonoCPUFeatures mono_cpu_features_enabled = (MonoCPUFeatures)0;
#ifdef DISABLE_SIMD
MonoCPUFeatures mono_cpu_features_disabled = MONO_CPU_X86_FULL_SSEAVX_COMBINED;
#else
MonoCPUFeatures mono_cpu_features_disabled = (MonoCPUFeatures)0;
#endif
gboolean mono_use_interpreter = FALSE;
const char *mono_interp_opts_string = NULL;
#define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
#define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
static mono_mutex_t jit_mutex;
static MonoCodeManager *global_codeman;
MonoDebugOptions mini_debug_options;
#ifdef VALGRIND_JIT_REGISTER_MAP
int valgrind_register;
#endif
GList* mono_aot_paths;
static GPtrArray *profile_options;
static GSList *tramp_infos;
GSList *mono_interp_only_classes;
static void register_icalls (void);
static void runtime_cleanup (MonoDomain *domain, gpointer user_data);
static void mini_invalidate_transformed_interp_methods (MonoAssemblyLoadContext *alc, uint32_t generation);
static void mini_interp_jit_info_foreach(InterpJitInfoFunc func, gpointer user_data);
static gboolean mini_interp_sufficient_stack (gsize size);
gboolean
mono_running_on_valgrind (void)
{
#ifndef HOST_WIN32
if (RUNNING_ON_VALGRIND){
#ifdef VALGRIND_JIT_REGISTER_MAP
valgrind_register = TRUE;
#endif
return TRUE;
} else
#endif
return FALSE;
}
void
mono_set_use_llvm (mono_bool use_llvm)
{
mono_use_llvm = (gboolean)use_llvm;
}
typedef struct {
void *ip;
MonoMethod *method;
} FindTrampUserData;
static void
find_tramp (gpointer key, gpointer value, gpointer user_data)
{
FindTrampUserData *ud = (FindTrampUserData*)user_data;
if (value == ud->ip)
ud->method = (MonoMethod*)key;
}
static char*
mono_get_method_from_ip_u (void *ip);
/* debug function */
char*
mono_get_method_from_ip (void *ip)
{
char *result;
MONO_ENTER_GC_UNSAFE;
result = mono_get_method_from_ip_u (ip);
MONO_EXIT_GC_UNSAFE;
return result;
}
/* debug function */
static char*
mono_get_method_from_ip_u (void *ip)
{
MonoJitInfo *ji;
MonoMethod *method;
char *method_name;
char *res;
MonoDomain *domain = mono_domain_get ();
MonoDebugSourceLocation *location;
FindTrampUserData user_data;
if (!domain)
domain = mono_get_root_domain ();
ji = mono_jit_info_table_find_internal (ip, TRUE, TRUE);
if (!ji) {
user_data.ip = ip;
user_data.method = NULL;
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_foreach (jit_mm->jit_trampoline_hash, find_tramp, &user_data);
jit_mm_unlock (jit_mm);
if (user_data.method) {
char *mname = mono_method_full_name (user_data.method, TRUE);
res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
g_free (mname);
return res;
}
else
return NULL;
} else if (ji->is_trampoline) {
res = g_strdup_printf ("<%p - %s trampoline>", ip, ji->d.tramp_info->name);
return res;
}
method = jinfo_get_method (ji);
method_name = mono_method_get_name_full (method, TRUE, FALSE, MONO_TYPE_NAME_FORMAT_IL);
location = mono_debug_lookup_source_location (method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
char *file_loc = NULL;
if (location)
file_loc = g_strdup_printf ("[%s :: %du]", location->source_file, location->row);
const char *in_interp = ji->is_interp ? " interp" : "";
res = g_strdup_printf (" %s [{%p} + 0x%x%s] %s (%p %p) [%p - %s]", method_name, method, (int)((char*)ip - (char*)ji->code_start), in_interp, file_loc ? file_loc : "", ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
mono_debug_free_source_location (location);
g_free (method_name);
g_free (file_loc);
return res;
}
/**
* mono_pmip:
* \param ip an instruction pointer address
*
* This method is used from a debugger to get the name of the
* method at address \p ip. This routine is typically invoked from
* a debugger like this:
*
* (gdb) print mono_pmip ($pc)
*
* \returns the name of the method at address \p ip.
*/
G_GNUC_UNUSED char *
mono_pmip (void *ip)
{
return mono_get_method_from_ip (ip);
}
G_GNUC_UNUSED char *
mono_pmip_u (void *ip)
{
return mono_get_method_from_ip_u (ip);
}
/**
* mono_print_method_from_ip:
* \param ip an instruction pointer address
*
* This method is used from a debugger to get the name of the
* method at address \p ip.
*
* This prints the name of the method at address \p ip in the standard
* output. Unlike \c mono_pmip which returns a string, this routine
* prints the value on the standard output.
*/
MONO_ATTR_USED void
mono_print_method_from_ip (void *ip)
{
MonoJitInfo *ji;
char *method;
MonoDebugSourceLocation *source;
MonoDomain *domain = mono_domain_get ();
MonoDomain *target_domain = mono_domain_get ();
FindTrampUserData user_data;
MonoGenericSharingContext*gsctx;
const char *shared_type;
if (!domain)
domain = mono_get_root_domain ();
ji = mini_jit_info_table_find_ext (ip, TRUE);
if (ji && ji->is_trampoline) {
MonoTrampInfo *tinfo = ji->d.tramp_info;
printf ("IP %p is at offset 0x%x of trampoline '%s'.\n", ip, (int)((guint8*)ip - tinfo->code), tinfo->name);
return;
}
if (!ji) {
user_data.ip = ip;
user_data.method = NULL;
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_foreach (jit_mm->jit_trampoline_hash, find_tramp, &user_data);
jit_mm_unlock (jit_mm);
if (user_data.method) {
char *mname = mono_method_full_name (user_data.method, TRUE);
printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
g_free (mname);
return;
}
g_print ("No method at %p\n", ip);
fflush (stdout);
return;
}
method = mono_method_full_name (jinfo_get_method (ji), TRUE);
source = mono_debug_lookup_source_location (jinfo_get_method (ji), (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
gsctx = mono_jit_info_get_generic_sharing_context (ji);
shared_type = "";
if (gsctx) {
if (gsctx->is_gsharedvt)
shared_type = "gsharedvt ";
else
shared_type = "gshared ";
}
g_print ("IP %p at offset 0x%x of %smethod %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), shared_type, method, ji->code_start, (char*)ji->code_start + ji->code_size, target_domain, target_domain->friendly_name);
if (source)
g_print ("%s:%d\n", source->source_file, source->row);
fflush (stdout);
mono_debug_free_source_location (source);
g_free (method);
}
/*
* mono_method_same_domain:
*
* Determine whenever two compiled methods are in the same domain, thus
* the address of the callee can be embedded in the caller.
*/
gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
{
if (!caller || caller->is_trampoline || !callee || callee->is_trampoline)
return FALSE;
return TRUE;
}
/*
* mono_global_codeman_reserve:
*
* Allocate code memory from the global code manager.
*/
void *(mono_global_codeman_reserve) (int size)
{
void *ptr;
if (mono_aot_only)
g_error ("Attempting to allocate from the global code manager while running in aot-only mode.\n");
if (!global_codeman) {
/* This can happen during startup */
if (!mono_compile_aot)
global_codeman = mono_code_manager_new ();
else
global_codeman = mono_code_manager_new_aot ();
return mono_code_manager_reserve (global_codeman, size);
}
else {
mono_jit_lock ();
ptr = mono_code_manager_reserve (global_codeman, size);
mono_jit_unlock ();
return ptr;
}
}
/* The callback shouldn't take any locks */
void
mono_global_codeman_foreach (MonoCodeManagerFunc func, void *user_data)
{
mono_jit_lock ();
mono_code_manager_foreach (global_codeman, func, user_data);
mono_jit_unlock ();
}
/**
* mono_create_unwind_op:
*
* Create an unwind op with the given parameters.
*/
MonoUnwindOp*
mono_create_unwind_op (int when, int tag, int reg, int val)
{
MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
op->op = tag;
op->reg = reg;
op->val = val;
op->when = when;
return op;
}
MonoJumpInfoToken *
mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
{
MonoJumpInfoToken *res = (MonoJumpInfoToken *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
res->image = image;
res->token = token;
res->has_context = context != NULL;
if (context)
memcpy (&res->context, context, sizeof (MonoGenericContext));
return res;
}
MonoJumpInfoToken *
mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
{
return mono_jump_info_token_new2 (mp, image, token, NULL);
}
/*
* mono_tramp_info_create:
*
* Create a MonoTrampInfo structure from the arguments. This function assumes ownership
* of JI, and UNWIND_OPS.
*/
MonoTrampInfo*
mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
{
MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
info->name = g_strdup (name);
info->code = code;
info->code_size = code_size;
info->ji = ji;
info->unwind_ops = unwind_ops;
return info;
}
void
mono_tramp_info_free (MonoTrampInfo *info)
{
g_free (info->name);
// FIXME: ji
mono_free_unwind_info (info->unwind_ops);
if (info->owns_uw_info)
g_free (info->uw_info);
g_free (info);
}
static void
register_trampoline_jit_info (MonoMemoryManager *mem_manager, MonoTrampInfo *info)
{
MonoJitInfo *ji;
ji = (MonoJitInfo *)mono_mem_manager_alloc0 (mem_manager, mono_jit_info_size ((MonoJitInfoFlags)0, 0, 0));
mono_jit_info_init (ji, NULL, (guint8*)MINI_FTNPTR_TO_ADDR (info->code), info->code_size, (MonoJitInfoFlags)0, 0, 0);
ji->d.tramp_info = info;
ji->is_trampoline = TRUE;
ji->unwind_info = mono_cache_unwind_info (info->uw_info, info->uw_info_len);
mono_jit_info_table_add (ji);
}
/*
* mono_tramp_info_register:
*
* Remember INFO for use by xdebug, mono_print_method_from_ip (), jit maps, etc.
* INFO can be NULL.
* Frees INFO.
*/
static void
mono_tramp_info_register_internal (MonoTrampInfo *info, MonoMemoryManager *mem_manager, gboolean aot)
{
MonoTrampInfo *copy;
MonoDomain *domain = mono_get_root_domain ();
if (!info)
return;
if (mem_manager)
copy = mono_mem_manager_alloc0 (mem_manager, sizeof (MonoTrampInfo));
else
copy = g_new0 (MonoTrampInfo, 1);
copy->code = info->code;
copy->code_size = info->code_size;
copy->name = mem_manager ? mono_mem_manager_strdup (mem_manager, info->name) : g_strdup (info->name);
copy->method = info->method;
if (info->unwind_ops) {
copy->uw_info = mono_unwind_ops_encode (info->unwind_ops, ©->uw_info_len);
copy->owns_uw_info = TRUE;
if (mem_manager) {
guint8 *temp = copy->uw_info;
copy->uw_info = mono_mem_manager_alloc (mem_manager, copy->uw_info_len);
memcpy (copy->uw_info, temp, copy->uw_info_len);
g_free (temp);
}
} else {
/* Trampolines from aot have the unwind ops already encoded */
copy->uw_info = info->uw_info;
copy->uw_info_len = info->uw_info_len;
}
mono_lldb_save_trampoline_info (info);
#ifdef MONO_ARCH_HAVE_UNWIND_TABLE
if (!aot)
mono_arch_unwindinfo_install_tramp_unwind_info (info->unwind_ops, info->code, info->code_size);
#endif
if (!domain) {
/* If no domain has been created yet, postpone the registration. */
mono_jit_lock ();
tramp_infos = g_slist_prepend (tramp_infos, copy);
mono_jit_unlock ();
} else if (copy->uw_info || info->method) {
/* Only register trampolines that have unwind info */
register_trampoline_jit_info (mem_manager ? mem_manager : get_default_mem_manager (), copy);
}
if (mono_jit_map_is_enabled ())
mono_emit_jit_tramp (info->code, info->code_size, info->name);
mono_tramp_info_free (info);
}
void
mono_tramp_info_register (MonoTrampInfo *info, MonoMemoryManager *mem_manager)
{
mono_tramp_info_register_internal (info, mem_manager, FALSE);
}
void
mono_aot_tramp_info_register (MonoTrampInfo *info, MonoMemoryManager *mem_manager)
{
mono_tramp_info_register_internal (info, mem_manager, TRUE);
}
/* Register trampolines created before the root domain was created in the jit info tables */
static void
register_trampolines (MonoDomain *domain)
{
GSList *l;
for (l = tramp_infos; l; l = l->next) {
MonoTrampInfo *info = (MonoTrampInfo *)l->data;
register_trampoline_jit_info (get_default_mem_manager (), info);
}
}
G_GNUC_UNUSED static void
break_count (void)
{
}
/*
* Runtime debugging tool, use if (debug_count ()) <x> else <y> to do <x> the first COUNT times, then do <y> afterwards.
* Set a breakpoint in break_count () to break the last time <x> is done.
*/
G_GNUC_UNUSED gboolean
mono_debug_count (void)
{
static int count = 0, int_val = 0;
static gboolean inited, has_value = FALSE;
count ++;
if (!inited) {
char *value = g_getenv ("COUNT");
if (value) {
int_val = atoi (value);
g_free (value);
has_value = TRUE;
}
inited = TRUE;
}
if (!has_value)
return TRUE;
if (count == int_val)
break_count ();
if (count > int_val)
return FALSE;
return TRUE;
}
MonoMethod*
mono_icall_get_wrapper_method (MonoJitICallInfo* callinfo)
{
/* This icall is used to check for exceptions, so don't check in the wrapper */
gboolean check_exc = (callinfo != &mono_get_jit_icall_info ()->mono_thread_interruption_checkpoint);
return mono_marshal_get_icall_wrapper (callinfo, check_exc);
}
gconstpointer
mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
{
ERROR_DECL (error);
MonoMethod *wrapper;
gconstpointer addr, trampoline;
if (callinfo->wrapper)
return callinfo->wrapper;
wrapper = mono_icall_get_wrapper_method (callinfo);
if (do_compile) {
addr = mono_compile_method_checked (wrapper, error);
mono_error_assert_ok (error);
mono_memory_barrier ();
callinfo->wrapper = addr;
return addr;
} else {
if (callinfo->trampoline)
return callinfo->trampoline;
trampoline = mono_create_jit_trampoline (wrapper, error);
mono_error_assert_ok (error);
trampoline = mono_create_ftnptr ((gpointer)trampoline);
mono_loader_lock ();
if (!callinfo->trampoline) {
callinfo->trampoline = trampoline;
}
mono_loader_unlock ();
return callinfo->trampoline;
}
}
gconstpointer
mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
{
return mono_icall_get_wrapper_full (callinfo, FALSE);
}
static MonoJitDynamicMethodInfo*
mono_dynamic_code_hash_lookup (MonoMethod *method)
{
MonoJitDynamicMethodInfo *res;
MonoJitMemoryManager *jit_mm;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
if (jit_mm->dynamic_code_hash)
res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (jit_mm->dynamic_code_hash, method);
else
res = NULL;
jit_mm_unlock (jit_mm);
return res;
}
#ifdef __cplusplus
template <typename T>
static void
register_opcode_emulation (int opcode, MonoJitICallInfo *jit_icall_info, const char *name, MonoMethodSignature *sig, T func, const char *symbol, gboolean no_wrapper)
#else
static void
register_opcode_emulation (int opcode, MonoJitICallInfo *jit_icall_info, const char *name, MonoMethodSignature *sig, gpointer func, const char *symbol, gboolean no_wrapper)
#endif
{
#ifndef DISABLE_JIT
mini_register_opcode_emulation (opcode, jit_icall_info, name, sig, func, symbol, no_wrapper);
#else
// FIXME ifdef in mini_register_opcode_emulation and just call it.
g_assert (!sig->hasthis);
g_assert (sig->param_count < 3);
mono_register_jit_icall_info (jit_icall_info, func, name, sig, no_wrapper, symbol);
#endif
}
#define register_opcode_emulation(opcode, name, sig, func, no_wrapper) \
(register_opcode_emulation ((opcode), &mono_get_jit_icall_info ()->name, #name, (sig), func, #func, (no_wrapper)))
/*
* For JIT icalls implemented in C.
* NAME should be the same as the name of the C function whose address is FUNC.
* If @avoid_wrapper is TRUE, no wrapper is generated. This is for perf critical icalls which
* can't throw exceptions.
*
* func is an identifier, that names a function, and is also in jit-icall-reg.h,
* and therefore a field in mono_jit_icall_info and can be token pasted into an enum value.
*
* The name of func must be linkable for AOT, for example g_free does not work (monoeg_g_free instead),
* nor does the C++ overload fmod (mono_fmod instead). These functions therefore
* must be extern "C".
*/
#define register_icall(func, sig, avoid_wrapper) \
(mono_register_jit_icall_info (&mono_get_jit_icall_info ()->func, func, #func, (sig), (avoid_wrapper), #func))
#define register_icall_no_wrapper(func, sig) register_icall (func, sig, TRUE)
#define register_icall_with_wrapper(func, sig) register_icall (func, sig, FALSE)
/*
* Register an icall where FUNC is dynamically generated or otherwise not
* possible to link to it using NAME during AOT.
*
* func is an expression, such a local variable or a function call to get a function pointer.
* name is an identifier
*
* Providing func and name separately is what distinguishes "dyn" from regular.
*
* This also passes last parameter c_symbol=NULL since there is not a directly linkable symbol.
*/
#define register_dyn_icall(func, name, sig, save) \
(mono_register_jit_icall_info (&mono_get_jit_icall_info ()->name, (func), #name, (sig), (save), NULL))
MonoLMF *
mono_get_lmf (void)
{
MonoJitTlsData *jit_tls;
if ((jit_tls = mono_tls_get_jit_tls ()))
return jit_tls->lmf;
/*
* We do not assert here because this function can be called from
* mini-gc.c on a thread that has not executed any managed code, yet
* (the thread object allocation can trigger a collection).
*/
return NULL;
}
void
mono_set_lmf (MonoLMF *lmf)
{
(*mono_get_lmf_addr ()) = lmf;
}
static void
mono_set_jit_tls (MonoJitTlsData *jit_tls)
{
MonoThreadInfo *info;
mono_tls_set_jit_tls (jit_tls);
/* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
info = mono_thread_info_current ();
if (info)
mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
}
static void
mono_set_lmf_addr (MonoLMF **lmf_addr)
{
MonoThreadInfo *info;
mono_tls_set_lmf_addr (lmf_addr);
/* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
info = mono_thread_info_current ();
if (info)
mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
}
/*
* mono_push_lmf:
*
* Push an MonoLMFExt frame on the LMF stack.
*/
void
mono_push_lmf (MonoLMFExt *ext)
{
MonoLMF **lmf_addr;
lmf_addr = mono_get_lmf_addr ();
ext->lmf.previous_lmf = *lmf_addr;
/* Mark that this is a MonoLMFExt */
ext->lmf.previous_lmf = (gpointer)(((gssize)ext->lmf.previous_lmf) | 2);
mono_set_lmf ((MonoLMF*)ext);
}
/*
* mono_pop_lmf:
*
* Pop the last frame from the LMF stack.
*/
void
mono_pop_lmf (MonoLMF *lmf)
{
mono_set_lmf ((MonoLMF *)(((gssize)lmf->previous_lmf) & ~3));
}
/*
* mono_jit_thread_attach:
*
* Called by Xamarin.Mac and other products. Attach thread to runtime if
* needed and switch to @domain.
*
* This function is external only and @deprecated don't use it. Use mono_threads_attach_coop ().
*
* If the thread is newly-attached, put into GC Safe mode.
*
* @return the original domain which needs to be restored, or NULL.
*/
MonoDomain*
mono_jit_thread_attach (MonoDomain *domain)
{
gboolean attached;
if (!domain) {
/* Happens when called from AOTed code which is only used in the root domain. */
domain = mono_get_root_domain ();
}
g_assert (domain);
attached = mono_tls_get_jit_tls () != NULL;
if (!attached) {
// #678164
gboolean background = TRUE;
mono_thread_attach_external_native_thread (domain, background);
/* mono_jit_thread_attach is external-only and not called by
* the runtime on any of our own threads. So if we get here,
* the thread is running native code - leave it in GC Safe mode
* and leave it to the n2m invoke wrappers or MONO_API entry
* points to switch to GC Unsafe.
*/
MONO_STACKDATA (stackdata);
mono_threads_enter_gc_safe_region_unbalanced_internal (&stackdata);
}
return NULL;
}
/*
* mono_jit_set_domain:
*
* Set domain to @domain if @domain is not null
*/
void
mono_jit_set_domain (MonoDomain *domain)
{
g_assert (!mono_threads_is_blocking_transition_enabled ());
if (domain)
mono_domain_set_fast (domain);
}
/**
* mono_thread_abort:
* \param obj exception object
* Abort the thread, print exception information and stack trace
*/
static void
mono_thread_abort (MonoObject *obj)
{
/* MonoJitTlsData *jit_tls = mono_tls_get_jit_tls (); */
/* handle_remove should be eventually called for this thread, too
g_free (jit_tls);*/
if ((obj->vtable->klass == mono_defaults.threadabortexception_class) ||
((obj->vtable->klass) == mono_class_try_get_appdomain_unloaded_exception_class () &&
mono_thread_info_current ()->runtime_thread)) {
mono_thread_exit ();
} else {
mono_invoke_unhandled_exception_hook (obj);
}
}
static MonoJitTlsData*
setup_jit_tls_data (gpointer stack_start, MonoAbortFunction abort_func)
{
MonoJitTlsData *jit_tls;
MonoLMF *lmf;
jit_tls = mono_tls_get_jit_tls ();
if (jit_tls)
return jit_tls;
jit_tls = g_new0 (MonoJitTlsData, 1);
jit_tls->abort_func = abort_func;
jit_tls->end_of_stack = stack_start;
mono_set_jit_tls (jit_tls);
lmf = g_new0 (MonoLMF, 1);
MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
jit_tls->first_lmf = lmf;
mono_set_lmf_addr (&jit_tls->lmf);
jit_tls->lmf = lmf;
#ifdef MONO_ARCH_HAVE_TLS_INIT
mono_arch_tls_init ();
#endif
mono_setup_altstack (jit_tls);
return jit_tls;
}
static void
free_jit_tls_data (MonoJitTlsData *jit_tls)
{
//This happens during AOT cuz the thread is never attached
if (!jit_tls)
return;
mono_free_altstack (jit_tls);
if (jit_tls->interp_context)
mini_get_interp_callbacks ()->free_context (jit_tls->interp_context);
g_free (jit_tls->first_lmf);
g_free (jit_tls);
}
static void
mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
{
MonoThreadInfo *thread;
MonoJitTlsData *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
thread = mono_thread_info_current_unchecked ();
if (thread)
thread->jit_data = jit_tls;
mono_arch_cpu_init ();
}
void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
static void
mono_thread_abort_dummy (MonoObject *obj)
{
if (mono_thread_attach_aborted_cb)
mono_thread_attach_aborted_cb (obj);
else
mono_thread_abort (obj);
}
static void
mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
{
MonoThreadInfo *thread;
MonoJitTlsData *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
thread = mono_thread_info_current_unchecked ();
if (thread)
thread->jit_data = jit_tls;
mono_arch_cpu_init ();
}
static void
mini_thread_cleanup (MonoNativeThreadId tid)
{
MonoJitTlsData *jit_tls = NULL;
MonoThreadInfo *info;
info = mono_thread_info_current_unchecked ();
/* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
* It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
* not a trivial thing.
*
* The current offender is mono_thread_manage which cleanup threads from the outside.
*/
if (info && mono_thread_info_get_tid (info) == tid) {
jit_tls = info->jit_data;
info->jit_data = NULL;
mono_set_jit_tls (NULL);
/* If we attach a thread but never call into managed land, we might never get an lmf.*/
if (mono_get_lmf ()) {
mono_set_lmf (NULL);
mono_set_lmf_addr (NULL);
}
} else {
info = mono_thread_info_lookup (tid);
if (info) {
jit_tls = info->jit_data;
info->jit_data = NULL;
}
mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
}
if (jit_tls)
free_jit_tls_data (jit_tls);
}
MonoJumpInfo *
mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
{
MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
ji->ip.i = ip;
ji->type = type;
ji->data.target = target;
ji->next = list;
return ji;
}
#if !defined(DISABLE_LOGGING) && !defined(DISABLE_JIT)
static const char* const patch_info_str[] = {
#define PATCH_INFO(a,b) "" #a,
#include "patch-info.h"
#undef PATCH_INFO
};
const char*
mono_ji_type_to_string (MonoJumpInfoType type)
{
return patch_info_str [type];
}
void
mono_print_ji (const MonoJumpInfo *ji)
{
const char *type = patch_info_str [ji->type];
switch (ji->type) {
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *entry = ji->data.rgctx_entry;
printf ("[%s ", type);
mono_print_ji (entry->data);
printf (" -> %s]", mono_rgctx_info_type_to_str (entry->info_type));
break;
}
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
char *s = mono_method_get_full_name (ji->data.method);
printf ("[%s %s]", type, s);
g_free (s);
break;
}
case MONO_PATCH_INFO_JIT_ICALL_ID:
printf ("[JIT_ICALL %s]", mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
break;
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_VTABLE: {
char *name = mono_class_full_name (ji->data.klass);
printf ("[%s %s]", type, name);
g_free (name);
break;
}
default:
printf ("[%s]", type);
break;
}
}
#else
const char*
mono_ji_type_to_string (MonoJumpInfoType type)
{
return "";
}
void
mono_print_ji (const MonoJumpInfo *ji)
{
}
#endif
/**
* mono_patch_info_dup_mp:
*
* Make a copy of PATCH_INFO, allocating memory from the mempool MP.
*/
MonoJumpInfo*
mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
{
MonoJumpInfo *res = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
memcpy (res, patch_info, sizeof (MonoJumpInfo));
switch (patch_info->type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
res->data.token = (MonoJumpInfoToken *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
break;
case MONO_PATCH_INFO_SWITCH:
res->data.table = (MonoJumpInfoBBTable *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
res->data.table->table = (MonoBasicBlock **)mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
break;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
res->data.rgctx_entry = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
res->data.del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (mp, sizeof (MonoDelegateClassMethodPair));
memcpy (res->data.del_tramp, patch_info->data.del_tramp, sizeof (MonoDelegateClassMethodPair));
break;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
res->data.gsharedvt = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc (mp, sizeof (MonoJumpInfoGSharedVtCall));
memcpy (res->data.gsharedvt, patch_info->data.gsharedvt, sizeof (MonoJumpInfoGSharedVtCall));
break;
case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
MonoGSharedVtMethodInfo *info;
MonoGSharedVtMethodInfo *oinfo;
int i;
oinfo = patch_info->data.gsharedvt_method;
info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
res->data.gsharedvt_method = info;
memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
for (i = 0; i < oinfo->num_entries; ++i) {
MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
memcpy (template_, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
}
//info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
//memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
break;
}
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info;
MonoJumpInfoVirtMethod *oinfo;
oinfo = patch_info->data.virt_method;
info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoVirtMethod));
res->data.virt_method = info;
memcpy (info, oinfo, sizeof (MonoJumpInfoVirtMethod));
break;
}
default:
break;
}
return res;
}
guint
mono_patch_info_hash (gconstpointer data)
{
const MonoJumpInfo *ji = (MonoJumpInfo*)data;
const MonoJumpInfoType type = ji->type;
guint hash = type << 8;
switch (type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
return hash | ji->data.token->token;
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
return hash | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: // Hash on the selector name
case MONO_PATCH_INFO_LDSTR_LIT:
return g_str_hash (ji->data.name);
case MONO_PATCH_INFO_VTABLE:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IID:
case MONO_PATCH_INFO_ADJUSTED_IID:
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_METHOD:
case MONO_PATCH_INFO_METHOD_JUMP:
case MONO_PATCH_INFO_METHOD_FTNDESC:
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY:
case MONO_PATCH_INFO_IMAGE:
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SFLDA:
case MONO_PATCH_INFO_SEQ_POINT_INFO:
case MONO_PATCH_INFO_METHOD_RGCTX:
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_METHOD_CODE_SLOT:
case MONO_PATCH_INFO_AOT_JIT_INFO:
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE:
return hash | (gssize)ji->data.target;
case MONO_PATCH_INFO_GSHAREDVT_CALL:
return hash | (gssize)ji->data.gsharedvt->method;
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *e = ji->data.rgctx_entry;
hash |= e->in_mrgctx | e->info_type | mono_patch_info_hash (e->data);
if (e->in_mrgctx)
return hash | (gssize)e->d.method;
else
return hash | (gssize)e->d.klass;
}
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
case MONO_PATCH_INFO_GC_NURSERY_START:
case MONO_PATCH_INFO_GC_NURSERY_BITS:
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_AOT_MODULE:
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE:
return hash;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return hash | ji->data.uindex;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
case MONO_PATCH_INFO_CASTCLASS_CACHE:
return hash | ji->data.index;
case MONO_PATCH_INFO_SWITCH:
return hash | ji->data.table->table_size;
case MONO_PATCH_INFO_GSHAREDVT_METHOD:
return hash | (gssize)ji->data.gsharedvt_method->method;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
return hash | (gsize)ji->data.del_tramp->klass | (gsize)ji->data.del_tramp->method | (gsize)ji->data.del_tramp->is_virtual;
case MONO_PATCH_INFO_VIRT_METHOD: {
MonoJumpInfoVirtMethod *info = ji->data.virt_method;
return hash | (gssize)info->klass | (gssize)info->method;
}
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
return hash | mono_signature_hash (ji->data.sig);
case MONO_PATCH_INFO_R8_GOT:
return hash | (guint32)*(double*)ji->data.target;
case MONO_PATCH_INFO_R4_GOT:
return hash | (guint32)*(float*)ji->data.target;
default:
printf ("info type: %d\n", ji->type);
mono_print_ji (ji); printf ("\n");
g_assert_not_reached ();
case MONO_PATCH_INFO_NONE:
return 0;
}
}
/*
* mono_patch_info_equal:
*
* This might fail to recognize equivalent patches, i.e. floats, so its only
* usable in those cases where this is not a problem, i.e. sharing GOT slots
* in AOT.
*/
gint
mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
{
const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
MonoJumpInfoType const ji1_type = ji1->type;
MonoJumpInfoType const ji2_type = ji2->type;
if (ji1_type != ji2_type)
return 0;
switch (ji1_type) {
case MONO_PATCH_INFO_RVA:
case MONO_PATCH_INFO_LDSTR:
case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
case MONO_PATCH_INFO_LDTOKEN:
case MONO_PATCH_INFO_DECLSEC:
return ji1->data.token->image == ji2->data.token->image &&
ji1->data.token->token == ji2->data.token->token &&
ji1->data.token->has_context == ji2->data.token->has_context &&
ji1->data.token->context.class_inst == ji2->data.token->context.class_inst &&
ji1->data.token->context.method_inst == ji2->data.token->context.method_inst;
case MONO_PATCH_INFO_OBJC_SELECTOR_REF:
case MONO_PATCH_INFO_LDSTR_LIT:
return g_str_equal (ji1->data.name, ji2->data.name);
case MONO_PATCH_INFO_RGCTX_FETCH:
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
return e1->d.method == e2->d.method && e1->d.klass == e2->d.klass && e1->in_mrgctx == e2->in_mrgctx && e1->info_type == e2->info_type && mono_patch_info_equal (e1->data, e2->data);
}
case MONO_PATCH_INFO_GSHAREDVT_CALL: {
MonoJumpInfoGSharedVtCall *c1 = ji1->data.gsharedvt;
MonoJumpInfoGSharedVtCall *c2 = ji2->data.gsharedvt;
return c1->sig == c2->sig && c1->method == c2->method;
}
case MONO_PATCH_INFO_GSHAREDVT_METHOD:
return ji1->data.gsharedvt_method->method == ji2->data.gsharedvt_method->method;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
return ji1->data.del_tramp->klass == ji2->data.del_tramp->klass && ji1->data.del_tramp->method == ji2->data.del_tramp->method && ji1->data.del_tramp->is_virtual == ji2->data.del_tramp->is_virtual;
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
return ji1->data.uindex == ji2->data.uindex;
case MONO_PATCH_INFO_CASTCLASS_CACHE:
return ji1->data.index == ji2->data.index;
case MONO_PATCH_INFO_JIT_ICALL_ID:
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
return ji1->data.jit_icall_id == ji2->data.jit_icall_id;
case MONO_PATCH_INFO_VIRT_METHOD:
return ji1->data.virt_method->klass == ji2->data.virt_method->klass && ji1->data.virt_method->method == ji2->data.virt_method->method;
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
return mono_metadata_signature_equal (ji1->data.sig, ji2->data.sig);
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
case MONO_PATCH_INFO_NONE:
return 1;
default:
break;
}
return ji1->data.target == ji2->data.target;
}
gpointer
mono_resolve_patch_target_ext (MonoMemoryManager *mem_manager, MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error)
{
unsigned char *ip = patch_info->ip.i + code;
gconstpointer target = NULL;
error_init (error);
switch (patch_info->type) {
case MONO_PATCH_INFO_BB:
/*
* FIXME: This could be hit for methods without a prolog. Should use -1
* but too much code depends on a 0 initial value.
*/
//g_assert (patch_info->data.bb->native_offset);
target = patch_info->data.bb->native_offset + code;
break;
case MONO_PATCH_INFO_ABS:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_LABEL:
target = patch_info->data.inst->inst_c0 + code;
break;
case MONO_PATCH_INFO_IP:
target = ip;
break;
case MONO_PATCH_INFO_JIT_ICALL_ID: {
MonoJitICallInfo * const mi = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
target = mono_icall_get_wrapper (mi);
break;
}
case MONO_PATCH_INFO_JIT_ICALL_ADDR:
case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
MonoJitICallInfo * const mi = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
target = mi->func;
break;
}
case MONO_PATCH_INFO_METHOD_JUMP:
target = mono_create_jump_trampoline (patch_info->data.method, FALSE, error);
if (!is_ok (error))
return NULL;
break;
case MONO_PATCH_INFO_METHOD:
if (patch_info->data.method == method) {
target = code;
} else {
/* get the trampoline to the method from the domain */
target = mono_create_jit_trampoline (patch_info->data.method, error);
if (!is_ok (error))
return NULL;
}
break;
case MONO_PATCH_INFO_METHOD_FTNDESC: {
/*
* Return an ftndesc for either AOTed code, or for an interp entry.
*/
target = mini_llvmonly_load_method_ftndesc (patch_info->data.method, FALSE, FALSE, error);
return_val_if_nok (error, NULL);
break;
}
case MONO_PATCH_INFO_LLVMONLY_INTERP_ENTRY: {
target = mini_get_interp_callbacks ()->create_method_pointer_llvmonly (patch_info->data.method, FALSE, error);
mono_error_assert_ok (error);
break;
}
case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
gpointer code_slot;
MonoJitMemoryManager *jit_mm = jit_mm_for_method (patch_info->data.method);
jit_mm_lock (jit_mm);
if (!jit_mm->method_code_hash)
jit_mm->method_code_hash = g_hash_table_new (NULL, NULL);
code_slot = g_hash_table_lookup (jit_mm->method_code_hash, patch_info->data.method);
if (!code_slot) {
code_slot = mono_mem_manager_alloc0 (jit_mm->mem_manager, sizeof (gpointer));
g_hash_table_insert (jit_mm->method_code_hash, patch_info->data.method, code_slot);
}
jit_mm_unlock (jit_mm);
target = code_slot;
break;
}
case MONO_PATCH_INFO_METHOD_PINVOKE_ADDR_CACHE: {
target = mono_mem_manager_alloc0 (mem_manager, sizeof (gpointer));
break;
}
case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
target = (gpointer)&mono_polling_required;
break;
case MONO_PATCH_INFO_SWITCH: {
#ifndef MONO_ARCH_NO_CODEMAN
gpointer *jump_table;
int i;
if (method && method->dynamic) {
jump_table = (void **)mono_code_manager_reserve (mono_dynamic_code_hash_lookup (method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
} else {
MonoMemoryManager *method_mem_manager = method ? m_method_get_mem_manager (method) : mem_manager;
if (mono_aot_only) {
jump_table = (void **)mono_mem_manager_alloc (method_mem_manager, sizeof (gpointer) * patch_info->data.table->table_size);
} else {
jump_table = (void **)mono_mem_manager_code_reserve (method_mem_manager, sizeof (gpointer) * patch_info->data.table->table_size);
}
}
mono_codeman_enable_write ();
for (i = 0; i < patch_info->data.table->table_size; i++) {
jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
}
mono_codeman_disable_write ();
target = jump_table;
#else
g_assert_not_reached ();
target = NULL;
#endif
break;
}
case MONO_PATCH_INFO_METHODCONST:
case MONO_PATCH_INFO_CLASS:
case MONO_PATCH_INFO_IMAGE:
case MONO_PATCH_INFO_FIELD:
case MONO_PATCH_INFO_SIGNATURE:
case MONO_PATCH_INFO_AOT_MODULE:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_IID:
mono_class_init_internal (patch_info->data.klass);
target = GUINT_TO_POINTER (m_class_get_interface_id (patch_info->data.klass));
break;
case MONO_PATCH_INFO_ADJUSTED_IID:
mono_class_init_internal (patch_info->data.klass);
target = GUINT_TO_POINTER ((guint32)(-((m_class_get_interface_id (patch_info->data.klass) + 1) * TARGET_SIZEOF_VOID_P)));
break;
case MONO_PATCH_INFO_VTABLE:
target = mono_class_vtable_checked (patch_info->data.klass, error);
mono_error_assert_ok (error);
break;
case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
MonoDelegateClassMethodPair *del_tramp = patch_info->data.del_tramp;
if (del_tramp->is_virtual)
target = mono_create_delegate_virtual_trampoline (del_tramp->klass, del_tramp->method);
else
target = mono_create_delegate_trampoline_info (del_tramp->klass, del_tramp->method);
break;
}
case MONO_PATCH_INFO_SFLDA: {
MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (patch_info->data.field), error);
mono_error_assert_ok (error);
if (mono_class_field_is_special_static (patch_info->data.field)) {
gpointer addr = mono_special_static_field_get_offset (patch_info->data.field, error);
mono_error_assert_ok (error);
g_assert (addr);
return addr;
}
if (!vtable->initialized && !mono_class_is_before_field_init (vtable->klass) && (!method || mono_class_needs_cctor_run (vtable->klass, method)))
/* Done by the generated code */
;
else {
if (run_cctors) {
if (!mono_runtime_class_init_full (vtable, error)) {
return NULL;
}
}
}
target = mono_static_field_get_addr (vtable, patch_info->data.field);
break;
}
case MONO_PATCH_INFO_RVA: {
guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
guint32 rva;
mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
target = mono_image_rva_map (patch_info->data.token->image, rva);
break;
}
case MONO_PATCH_INFO_R4:
case MONO_PATCH_INFO_R4_GOT:
case MONO_PATCH_INFO_R8:
case MONO_PATCH_INFO_R8_GOT:
target = patch_info->data.target;
break;
case MONO_PATCH_INFO_EXC_NAME:
target = patch_info->data.name;
break;
case MONO_PATCH_INFO_LDSTR:
target =
mono_ldstr_checked (patch_info->data.token->image,
mono_metadata_token_index (patch_info->data.token->token), error);
break;
case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
gpointer handle;
MonoClass *handle_class;
handle = mono_ldtoken_checked (patch_info->data.token->image,
patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
if (!is_ok (error))
return NULL;
mono_class_init_internal (handle_class);
mono_class_init_internal (mono_class_from_mono_type_internal ((MonoType *)handle));
target = mono_type_get_object_checked ((MonoType *)handle, error);
if (!is_ok (error))
return NULL;
break;
}
case MONO_PATCH_INFO_LDTOKEN: {
gpointer handle;
MonoClass *handle_class;
handle = mono_ldtoken_checked (patch_info->data.token->image,
patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL, error);
mono_error_assert_msg_ok (error, "Could not patch ldtoken");
mono_class_init_internal (handle_class);
target = handle;
break;
}
case MONO_PATCH_INFO_DECLSEC:
target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
break;
case MONO_PATCH_INFO_ICALL_ADDR:
case MONO_PATCH_INFO_ICALL_ADDR_CALL:
/* run_cctors == 0 -> AOT */
if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
if (run_cctors) {
target = mono_lookup_pinvoke_call_internal (patch_info->data.method, error);
if (!target) {
if (mono_aot_only)
return NULL;
g_error ("Unable to resolve pinvoke method '%s' Re-run with MONO_LOG_LEVEL=debug for more information.\n", mono_method_full_name (patch_info->data.method, TRUE));
}
} else {
target = NULL;
}
} else {
target = mono_lookup_internal_call (patch_info->data.method);
if (mono_is_missing_icall_addr (target) && run_cctors)
g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
}
break;
case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
target = &mono_thread_interruption_request_flag;
break;
case MONO_PATCH_INFO_METHOD_RGCTX:
target = mini_method_get_rgctx (patch_info->data.method);
break;
case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
target = GINT_TO_POINTER (MONO_RGCTX_SLOT_INDEX (slot));
break;
}
case MONO_PATCH_INFO_BB_OVF:
case MONO_PATCH_INFO_EXC_OVF:
case MONO_PATCH_INFO_GOT_OFFSET:
case MONO_PATCH_INFO_NONE:
break;
case MONO_PATCH_INFO_RGCTX_FETCH: {
int slot = mini_get_rgctx_entry_slot (patch_info->data.rgctx_entry);
target = mono_create_rgctx_lazy_fetch_trampoline (slot);
break;
}
#ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
case MONO_PATCH_INFO_SEQ_POINT_INFO:
if (!run_cctors)
/* AOT, not needed */
target = NULL;
else
target = mono_arch_get_seq_point_info (code);
break;
#endif
case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
int card_table_shift_bits;
gpointer card_table_mask;
target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
break;
}
case MONO_PATCH_INFO_GC_NURSERY_START: {
int shift_bits;
size_t size;
target = mono_gc_get_nursery (&shift_bits, &size);
break;
}
case MONO_PATCH_INFO_GC_NURSERY_BITS: {
int shift_bits;
size_t size;
mono_gc_get_nursery (&shift_bits, &size);
target = (gpointer)(gssize)shift_bits;
break;
}
case MONO_PATCH_INFO_CASTCLASS_CACHE: {
target = mono_mem_manager_alloc0 (mem_manager, sizeof (gpointer));
break;
}
case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
target = NULL;
break;
}
case MONO_PATCH_INFO_LDSTR_LIT: {
int len;
char *s;
len = strlen ((const char *)patch_info->data.target);
s = (char *)mono_mem_manager_alloc0 (mem_manager, len + 1);
memcpy (s, patch_info->data.target, len);
target = s;
break;
}
case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
target = mini_get_gsharedvt_wrapper (TRUE, NULL, patch_info->data.sig, NULL, -1, FALSE);
break;
case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT: {
target = (gpointer) &mono_profiler_state.gc_allocation_count;
break;
}
case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT: {
target = (gpointer) &mono_profiler_state.exception_clause_count;
break;
}
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES:
case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINES_GOT_SLOTS_BASE: {
/* Resolved in aot-runtime.c */
g_assert_not_reached ();
target = NULL;
break;
}
default:
g_assert_not_reached ();
}
return (gpointer)target;
}
gpointer
mono_resolve_patch_target (MonoMethod *method, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors, MonoError *error)
{
return mono_resolve_patch_target_ext (get_default_mem_manager (), method, code, patch_info, run_cctors, error);
}
/*
* mini_register_jump_site:
*
* Register IP as a jump/tailcall site which calls METHOD.
* This is needed because common_call_trampoline () cannot patch
* the call site because the caller ip is not available for jumps.
*/
void
mini_register_jump_site (MonoMethod *method, gpointer ip)
{
MonoJumpList *jlist;
MonoJitMemoryManager *jit_mm;
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
jlist = (MonoJumpList *)g_hash_table_lookup (jit_mm->jump_target_hash, method);
if (!jlist) {
jlist = (MonoJumpList *)mono_mem_manager_alloc0 (jit_mm->mem_manager, sizeof (MonoJumpList));
g_hash_table_insert (jit_mm->jump_target_hash, method, jlist);
}
jlist->list = g_slist_prepend (jlist->list, ip);
jit_mm_unlock (jit_mm);
}
/*
* mini_patch_jump_sites:
*
* Patch jump/tailcall sites calling METHOD so the jump to ADDR.
*/
void
mini_patch_jump_sites (MonoMethod *method, gpointer addr)
{
MonoJitMemoryManager *jit_mm;
MonoJumpInfo patch_info;
MonoJumpList *jlist;
GSList *tmp;
/* The caller/callee might use different instantiations */
MonoMethod *shared_method = mini_method_to_shared (method);
method = shared_method ? shared_method : method;
jit_mm = jit_mm_for_method (method);
jit_mm_lock (jit_mm);
jlist = (MonoJumpList *)g_hash_table_lookup (jit_mm->jump_target_hash, method);
if (jlist)
g_hash_table_remove (jit_mm->jump_target_hash, method);
jit_mm_unlock (jit_mm);
if (jlist) {
patch_info.next = NULL;
patch_info.ip.i = 0;
patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
patch_info.data.method = method;
mono_codeman_enable_write ();
for (tmp = jlist->list; tmp; tmp = tmp->next)
mono_arch_patch_code_new (NULL, (guint8 *)tmp->data, &patch_info, addr);
mono_codeman_disable_write ();
}
}
/*
* mini_patch_llvm_jit_callees:
*
* Patch function address slots used by llvm JITed code.
*/
void
mini_patch_llvm_jit_callees (MonoMethod *method, gpointer addr)
{
MonoJitMemoryManager *jit_mm;
// FIXME:
jit_mm = get_default_jit_mm ();
if (!jit_mm->llvm_jit_callees)
return;
jit_mm_lock (jit_mm);
GSList *callees = (GSList*)g_hash_table_lookup (jit_mm->llvm_jit_callees, method);
GSList *l;
for (l = callees; l; l = l->next) {
gpointer *slot = (gpointer*)l->data;
*slot = addr;
}
jit_mm_unlock (jit_mm);
}
void
mini_init_gsctx (MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
{
MonoGenericInst *inst;
int i;
memset (gsctx, 0, sizeof (MonoGenericSharingContext));
if (context && context->class_inst) {
inst = context->class_inst;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *type = inst->type_argv [i];
if (mini_is_gsharedvt_gparam (type))
gsctx->is_gsharedvt = TRUE;
}
}
if (context && context->method_inst) {
inst = context->method_inst;
for (i = 0; i < inst->type_argc; ++i) {
MonoType *type = inst->type_argv [i];
if (mini_is_gsharedvt_gparam (type))
gsctx->is_gsharedvt = TRUE;
}
}
}
/*
* LOCKING: Acquires the jit code hash lock.
*/
MonoJitInfo*
mini_lookup_method (MonoMethod *method, MonoMethod *shared)
{
MonoJitInfo *ji;
MonoJitMemoryManager *jit_mm = jit_mm_for_method (method);
static gboolean inited = FALSE;
static int lookups = 0;
static int failed_lookups = 0;
jit_code_hash_lock (jit_mm);
ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&jit_mm->jit_code_hash, method);
jit_code_hash_unlock (jit_mm);
if (!ji && shared) {
jit_mm = jit_mm_for_method (shared);
jit_code_hash_lock (jit_mm);
/* Try generic sharing */
ji = (MonoJitInfo *)mono_internal_hash_table_lookup (&jit_mm->jit_code_hash, shared);
if (ji && !ji->has_generic_jit_info)
ji = NULL;
if (!inited) {
mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
inited = TRUE;
}
++lookups;
if (!ji)
++failed_lookups;
jit_code_hash_unlock (jit_mm);
}
return ji;
}
static MonoJitInfo*
lookup_method (MonoMethod *method)
{
ERROR_DECL (error);
MonoJitInfo *ji;
MonoMethod *shared;
ji = mini_lookup_method (method, NULL);
if (!ji) {
if (!mono_method_is_generic_sharable (method, FALSE))
return NULL;
shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
mono_error_assert_ok (error);
ji = mini_lookup_method (method, shared);
}
return ji;
}
MonoClass*
mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
{
ERROR_DECL (error);
MonoClass *klass;
if (method->wrapper_type != MONO_WRAPPER_NONE) {
klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
if (context) {
klass = mono_class_inflate_generic_class_checked (klass, context, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
} else {
klass = mono_class_get_and_inflate_typespec_checked (m_class_get_image (method->klass), token, context, error);
mono_error_cleanup (error); /* FIXME don't swallow the error */
}
if (klass)
mono_class_init_internal (klass);
return klass;
}
#if ENABLE_JIT_MAP
static FILE* perf_map_file;
void
mono_enable_jit_map (void)
{
if (!perf_map_file) {
char name [64];
g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
unlink (name);
perf_map_file = fopen (name, "w");
}
}
void
mono_emit_jit_tramp (void *start, int size, const char *desc)
{
if (perf_map_file)
fprintf (perf_map_file, "%" PRIx64 " %x %s\n", (guint64)(gsize)start, size, desc);
}
void
mono_emit_jit_map (MonoJitInfo *jinfo)
{
if (perf_map_file) {
char *name = mono_method_full_name (jinfo_get_method (jinfo), TRUE);
mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
g_free (name);
}
}
gboolean
mono_jit_map_is_enabled (void)
{
return perf_map_file != NULL;
}
#endif
#ifdef ENABLE_JIT_DUMP
#include <sys/mman.h>
#include <sys/syscall.h>
#include <elf.h>
static FILE *perf_dump_file;
static mono_mutex_t perf_dump_mutex;
static void *perf_dump_mmap_addr = MAP_FAILED;
static guint32 perf_dump_pid;
static clockid_t clock_id = CLOCK_MONOTONIC;
enum {
JIT_DUMP_MAGIC = 0x4A695444,
JIT_DUMP_VERSION = 2,
#if HOST_X86
ELF_MACHINE = EM_386,
#elif HOST_AMD64
ELF_MACHINE = EM_X86_64,
#elif HOST_ARM
ELF_MACHINE = EM_ARM,
#elif HOST_ARM64
ELF_MACHINE = EM_AARCH64,
#elif HOST_POWERPC64
ELF_MACHINE = EM_PPC64,
#elif HOST_S390X
ELF_MACHINE = EM_S390,
#elif HOST_RISCV
ELF_MACHINE = EM_RISCV,
#elif HOST_MIPS
ELF_MACHINE = EM_MIPS,
#endif
JIT_CODE_LOAD = 0
};
typedef struct
{
guint32 magic;
guint32 version;
guint32 total_size;
guint32 elf_mach;
guint32 pad1;
guint32 pid;
guint64 timestamp;
guint64 flags;
} FileHeader;
typedef struct
{
guint32 id;
guint32 total_size;
guint64 timestamp;
} RecordHeader;
typedef struct
{
RecordHeader header;
guint32 pid;
guint32 tid;
guint64 vma;
guint64 code_addr;
guint64 code_size;
guint64 code_index;
// Null terminated function name
// Native code
} JitCodeLoadRecord;
static void add_file_header_info (FileHeader *header);
static void add_basic_JitCodeLoadRecord_info (JitCodeLoadRecord *record);
void
mono_enable_jit_dump (void)
{
if (perf_dump_pid == 0)
perf_dump_pid = getpid();
if (!perf_dump_file) {
char name [64];
FileHeader header;
memset (&header, 0, sizeof (header));
mono_os_mutex_init (&perf_dump_mutex);
mono_os_mutex_lock (&perf_dump_mutex);
g_snprintf (name, sizeof (name), "/tmp/jit-%d.dump", perf_dump_pid);
unlink (name);
perf_dump_file = fopen (name, "w");
add_file_header_info (&header);
if (perf_dump_file) {
fwrite (&header, sizeof (header), 1, perf_dump_file);
//This informs perf of the presence of the jitdump file and support for the feature.
perf_dump_mmap_addr = mmap (NULL, sizeof (header), PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno (perf_dump_file), 0);
}
mono_os_mutex_unlock (&perf_dump_mutex);
}
}
static void
add_file_header_info (FileHeader *header)
{
header->magic = JIT_DUMP_MAGIC;
header->version = JIT_DUMP_VERSION;
header->total_size = sizeof (header);
header->elf_mach = ELF_MACHINE;
header->pad1 = 0;
header->pid = perf_dump_pid;
header->timestamp = mono_clock_get_time_ns (clock_id);
header->flags = 0;
}
void
mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code)
{
static uint64_t code_index;
if (perf_dump_file) {
JitCodeLoadRecord record;
size_t nameLen = strlen (jinfo->d.method->name);
memset (&record, 0, sizeof (record));
add_basic_JitCodeLoadRecord_info (&record);
record.header.total_size = sizeof (record) + nameLen + 1 + jinfo->code_size;
record.vma = (guint64)jinfo->code_start;
record.code_addr = (guint64)jinfo->code_start;
record.code_size = (guint64)jinfo->code_size;
mono_os_mutex_lock (&perf_dump_mutex);
record.code_index = ++code_index;
// TODO: write debugInfo and unwindInfo immediately before the JitCodeLoadRecord (while lock is held).
record.header.timestamp = mono_clock_get_time_ns (clock_id);
fwrite (&record, sizeof (record), 1, perf_dump_file);
fwrite (jinfo->d.method->name, nameLen + 1, 1, perf_dump_file);
fwrite (code, jinfo->code_size, 1, perf_dump_file);
mono_os_mutex_unlock (&perf_dump_mutex);
}
}
static void
add_basic_JitCodeLoadRecord_info (JitCodeLoadRecord *record)
{
record->header.id = JIT_CODE_LOAD;
record->header.timestamp = mono_clock_get_time_ns (clock_id);
record->pid = perf_dump_pid;
record->tid = syscall (SYS_gettid);
}
void
mono_jit_dump_cleanup (void)
{
if (perf_dump_mmap_addr != MAP_FAILED)
munmap (perf_dump_mmap_addr, sizeof(FileHeader));
if (perf_dump_file)
fclose (perf_dump_file);
}
#else
void
mono_enable_jit_dump (void)
{
}
void
mono_emit_jit_dump (MonoJitInfo *jinfo, gpointer code)
{
}
void
mono_jit_dump_cleanup (void)
{
}
#endif
static void
no_gsharedvt_in_wrapper (void)
{
g_assert_not_reached ();
}
/*
Overall algorithm:
When a JIT request is made, we check if there's an outstanding one for that method and, if it exits, put the thread to sleep.
If the current thread is already JITing another method, don't wait as it might cause a deadlock.
Dependency management in this case is too complex to justify implementing it.
If there are no outstanding requests, the current thread is doing nothing and there are already mono_cpu_count threads JITing, go to sleep.
TODO:
Get rid of cctor invocations from within the JIT, it increases JIT duration and complicates things A LOT.
Can we get rid of ref_count and use `done && threads_waiting == 0` as the equivalent of `ref_count == 0`?
Reduce amount of dynamically allocated - possible once the JIT is no longer reentrant
Maybe pool JitCompilationEntry, specially those with an inited cond var;
*/
typedef struct {
MonoMethod *method;
int compilation_count; /* Number of threads compiling this method - This happens due to the JIT being reentrant */
int ref_count; /* Number of threads using this JitCompilationEntry, roughtly 1 + threads_waiting */
int threads_waiting; /* Number of threads waiting on this job */
gboolean has_cond; /* True if @cond was initialized */
gboolean done; /* True if the method finished JIT'ing */
MonoCoopCond cond; /* Cond sleeping threads wait one */
} JitCompilationEntry;
typedef struct {
GPtrArray *in_flight_methods; //JitCompilationEntry*
MonoCoopMutex lock;
} JitCompilationData;
/*
Timeout, in millisecounds, that we wait other threads to finish JITing.
This value can't be too small or we won't see enough methods being reused and it can't be too big to cause massive stalls due to unforseable circunstances.
*/
#define MAX_JIT_TIMEOUT_MS 1000
static JitCompilationData compilation_data;
static int jit_methods_waited, jit_methods_multiple, jit_methods_overload, jit_spurious_wakeups_or_timeouts;
static void
mini_jit_init_job_control (void)
{
mono_coop_mutex_init (&compilation_data.lock);
compilation_data.in_flight_methods = g_ptr_array_new ();
}
static void
lock_compilation_data (void)
{
mono_coop_mutex_lock (&compilation_data.lock);
}
static void
unlock_compilation_data (void)
{
mono_coop_mutex_unlock (&compilation_data.lock);
}
static JitCompilationEntry*
find_method (MonoMethod *method)
{
int i;
for (i = 0; i < compilation_data.in_flight_methods->len; ++i){
JitCompilationEntry *e = (JitCompilationEntry*)compilation_data.in_flight_methods->pdata [i];
if (e->method == method)
return e;
}
return NULL;
}
static void
add_current_thread (MonoJitTlsData *jit_tls)
{
++jit_tls->active_jit_methods;
}
static void
unref_jit_entry (JitCompilationEntry *entry)
{
--entry->ref_count;
if (entry->ref_count)
return;
if (entry->has_cond)
mono_coop_cond_destroy (&entry->cond);
g_free (entry);
}
/*
* Returns true if this method waited successfully for another thread to JIT it
*/
static gboolean
wait_or_register_method_to_compile (MonoMethod *method)
{
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
JitCompilationEntry *entry;
static gboolean inited;
if (!inited) {
mono_counters_register ("JIT compile waited others", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_waited);
mono_counters_register ("JIT compile 1+ jobs", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_multiple);
mono_counters_register ("JIT compile overload wait", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_methods_overload);
mono_counters_register ("JIT compile spurious wakeups or timeouts", MONO_COUNTER_INT|MONO_COUNTER_JIT, &jit_spurious_wakeups_or_timeouts);
inited = TRUE;
}
lock_compilation_data ();
if (!(entry = find_method (method))) {
entry = g_new0 (JitCompilationEntry, 1);
entry->method = method;
entry->compilation_count = entry->ref_count = 1;
g_ptr_array_add (compilation_data.in_flight_methods, entry);
g_assert (find_method (method) == entry);
add_current_thread (jit_tls);
unlock_compilation_data ();
return FALSE;
} else if (jit_tls->active_jit_methods > 0 || mono_threads_is_current_thread_in_protected_block ()) {
//We can't suspend the current thread if it's already JITing a method.
//Dependency management is too compilated and we want to get rid of this anyways.
//We can't suspend the current thread if it's running a protected block (such as a cctor)
//We can't rely only on JIT nesting as cctor's can be run from outside the JIT.
//Finally, he hit a timeout or spurious wakeup. We're better off just giving up and keep recompiling
++entry->compilation_count;
++jit_methods_multiple;
++jit_tls->active_jit_methods;
unlock_compilation_data ();
return FALSE;
} else {
++jit_methods_waited;
++entry->ref_count;
if (!entry->has_cond) {
mono_coop_cond_init (&entry->cond);
entry->has_cond = TRUE;
}
while (TRUE) {
++entry->threads_waiting;
g_assert (entry->has_cond);
mono_coop_cond_timedwait (&entry->cond, &compilation_data.lock, MAX_JIT_TIMEOUT_MS);
--entry->threads_waiting;
if (entry->done) {
unref_jit_entry (entry);
unlock_compilation_data ();
return TRUE;
} else {
//We hit the timeout or a spurious wakeup, fallback to JITing
g_assert (entry->ref_count > 1);
unref_jit_entry (entry);
++jit_spurious_wakeups_or_timeouts;
++entry->compilation_count;
++jit_methods_multiple;
++jit_tls->active_jit_methods;
unlock_compilation_data ();
return FALSE;
}
}
}
}
static void
unregister_method_for_compile (MonoMethod *method)
{
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
lock_compilation_data ();
g_assert (jit_tls->active_jit_methods > 0);
--jit_tls->active_jit_methods;
JitCompilationEntry *entry = find_method (method);
g_assert (entry); // It would be weird to fail
entry->done = TRUE;
if (entry->threads_waiting) {
g_assert (entry->has_cond);
mono_coop_cond_broadcast (&entry->cond);
}
if (--entry->compilation_count == 0) {
g_ptr_array_remove (compilation_data.in_flight_methods, entry);
unref_jit_entry (entry);
}
unlock_compilation_data ();
}
static MonoJitInfo*
create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
{
MonoJitInfo *jinfo;
guint8 *uw_info;
guint32 info_len;
if (info->uw_info) {
uw_info = info->uw_info;
info_len = info->uw_info_len;
} else {
uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
}
jinfo = (MonoJitInfo *)mono_mem_manager_alloc0 (get_default_mem_manager (), MONO_SIZEOF_JIT_INFO);
jinfo->d.method = wrapper;
jinfo->code_start = MINI_FTNPTR_TO_ADDR (info->code);
jinfo->code_size = info->code_size;
jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
if (!info->uw_info)
g_free (uw_info);
return jinfo;
}
static gpointer
compile_special (MonoMethod *method, MonoError *error)
{
MonoJitInfo *jinfo;
gpointer code;
if (mono_llvm_only) {
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
/*
* These wrappers are only created for signatures which are in the program, but
* sometimes we load methods too eagerly and have to create them even if they
* will never be called.
*/
return (gpointer)no_gsharedvt_in_wrapper;
}
}
}
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
if (!piinfo->addr) {
if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
guint32 flags = MONO_ICALL_FLAGS_NONE;
gpointer icall_addr;
icall_addr = (gpointer)mono_lookup_internal_call_full_with_flags (method, TRUE, (guint32 *)&flags);
if (flags & MONO_ICALL_FLAGS_NO_WRAPPER) {
piinfo->icflags = MONO_ICALL_FLAGS_NO_WRAPPER;
mono_memory_write_barrier ();
}
piinfo->addr = icall_addr;
} else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE) {
#ifdef HOST_WIN32
g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), m_class_get_image (method->klass)->name);
#else
g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), m_class_get_image (method->klass)->name);
#endif
} else {
ERROR_DECL (ignored_error);
mono_lookup_pinvoke_call_internal (method, ignored_error);
mono_error_cleanup (ignored_error);
}
}
mono_memory_read_barrier ();
gpointer compiled_method = NULL;
if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && (piinfo->icflags & MONO_ICALL_FLAGS_NO_WRAPPER)) {
compiled_method = piinfo->addr;
} else {
MonoMethod *nm = mono_marshal_get_native_wrapper (method, TRUE, mono_aot_only);
compiled_method = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
}
code = mono_get_addr_from_ftnptr (compiled_method);
jinfo = mini_jit_info_table_find (code);
if (jinfo)
MONO_PROFILER_RAISE (jit_done, (method, jinfo));
return code;
} else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
const char *name = method->name;
char *full_name;
MonoMethod *nm;
if (m_class_get_parent (method->klass) == mono_defaults.multicastdelegate_class) {
if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
MonoJitICallInfo *mi = &mono_get_jit_icall_info ()->ves_icall_mono_delegate_ctor;
/*
* We need to make sure this wrapper
* is compiled because it might end up
* in an (M)RGCTX if generic sharing
* is enabled, and would be called
* indirectly. If it were a
* trampoline we'd try to patch that
* indirect call, which is not
* possible.
*/
return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
} else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
if (mono_llvm_only) {
nm = mono_marshal_get_delegate_invoke (method, NULL);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
}
/* HACK: missing gsharedvt_out wrappers to do transition to del tramp in interp-only mode */
if (mono_use_interpreter)
return NULL;
return mono_create_delegate_trampoline (method->klass);
} else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
nm = mono_marshal_get_delegate_begin_invoke (method);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
} else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
nm = mono_marshal_get_delegate_end_invoke (method);
gpointer compiled_ptr = mono_jit_compile_method_jit_only (nm, error);
return_val_if_nok (error, NULL);
return mono_get_addr_from_ftnptr (compiled_ptr);
}
}
full_name = mono_method_full_name (method, TRUE);
mono_error_set_invalid_program (error, "Unrecognizable runtime implemented method '%s'", full_name);
g_free (full_name);
return NULL;
}
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
static MonoTrampInfo *in_tinfo, *out_tinfo;
MonoTrampInfo *tinfo;
MonoJitInfo *jinfo;
gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
if (is_in && in_tinfo)
return in_tinfo->code;
else if (!is_in && out_tinfo)
return out_tinfo->code;
/*
* This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
* works.
* FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
*/
if (mono_ee_features.use_aot_trampolines)
mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
else
mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
jinfo = create_jit_info_for_trampoline (method, tinfo);
mono_jit_info_table_add (jinfo);
if (is_in)
in_tinfo = tinfo;
else
out_tinfo = tinfo;
return tinfo->code;
}
}
return NULL;
}
static gpointer
mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, gboolean jit_only, MonoError *error)
{
MonoJitInfo *info;
gpointer code = NULL, p;
MonoJitICallInfo *callinfo = NULL;
WrapperInfo *winfo = NULL;
gboolean use_interp = FALSE;
error_init (error);
if (mono_ee_features.force_use_interpreter && !jit_only)
use_interp = TRUE;
if (!use_interp && mono_interp_only_classes) {
for (GSList *l = mono_interp_only_classes; l; l = l->next) {
if (!strcmp (m_class_get_name (method->klass), (char*)l->data))
use_interp = TRUE;
}
}
if (use_interp) {
code = mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
if (code)
return code;
return_val_if_nok (error, NULL);
}
if (mono_llvm_only)
/* Should be handled by the caller */
g_assert (!(method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED));
/*
* ICALL wrappers are handled specially, since there is only one copy of them
* shared by all appdomains.
*/
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
winfo = mono_marshal_get_wrapper_info (method);
if (winfo && winfo->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER)
callinfo = mono_find_jit_icall_info (winfo->d.icall.jit_icall_id);
if (method->wrapper_type == MONO_WRAPPER_OTHER) {
WrapperInfo *info = mono_marshal_get_wrapper_info (method);
g_assert (info);
if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER) {
MonoGenericContext *ctx = NULL;
if (method->is_inflated)
ctx = mono_method_get_context (method);
method = info->d.synchronized_inner.method;
if (ctx) {
method = mono_class_inflate_generic_method_checked (method, ctx, error);
g_assert (is_ok (error)); /* FIXME don't swallow the error */
}
}
}
lookup_start:
info = lookup_method (method);
if (info) {
MonoVTable *vtable;
mono_atomic_inc_i32 (&mono_jit_stats.methods_lookups);
vtable = mono_class_vtable_checked (method->klass, error);
if (!is_ok (error))
return NULL;
g_assert (vtable);
if (!mono_runtime_class_init_full (vtable, error))
return NULL;
code = MINI_ADDR_TO_FTNPTR (info->code_start);
return mono_create_ftnptr (code);
}
#ifdef MONO_USE_AOT_COMPILER
if (opt & MONO_OPT_AOT) {
mono_class_init_internal (method->klass);
code = mono_aot_get_method (method, error);
if (code) {
MonoVTable *vtable;
if (mono_gc_is_critical_method (method)) {
/*
* The suspend code needs to be able to lookup these methods by ip in async context,
* so preload their jit info.
*/
MonoJitInfo *ji = mini_jit_info_table_find (code);
g_assert (ji);
}
/*
* In llvm-only mode, method might be a shared method, so we can't initialize its class.
* This is not a problem, since it will be initialized when the method is first
* called by init_method ().
*/
if (!mono_llvm_only && !mono_class_is_open_constructed_type (m_class_get_byval_arg (method->klass))) {
vtable = mono_class_vtable_checked (method->klass, error);
mono_error_assert_ok (error);
if (!mono_runtime_class_init_full (vtable, error))
return NULL;
}
}
if (!is_ok (error))
return NULL;
}
#endif
if (!code) {
code = compile_special (method, error);
if (!is_ok (error))
return NULL;
}
if (!jit_only && !code && mono_aot_only && mono_use_interpreter && method->wrapper_type != MONO_WRAPPER_OTHER) {
if (mono_llvm_only) {
/* Signal to the caller that AOTed code is not found */
return NULL;
}
code = mini_get_interp_callbacks ()->create_method_pointer (method, TRUE, error);
if (!is_ok (error))
return NULL;
}
if (!code) {
if (mono_class_is_open_constructed_type (m_class_get_byval_arg (method->klass))) {
char *full_name = mono_type_get_full_name (method->klass);
mono_error_set_invalid_operation (error, "Could not execute the method because the containing type '%s', is not fully instantiated.", full_name);
g_free (full_name);
return NULL;
}
if (mono_aot_only) {
char *fullname = mono_method_get_full_name (method);
mono_error_set_execution_engine (error, "Attempting to JIT compile method '%s' while running in aot-only mode. See https://docs.microsoft.com/xamarin/ios/internals/limitations for more information.\n", fullname);
g_free (fullname);
return NULL;
}
if (wait_or_register_method_to_compile (method))
goto lookup_start;
code = mono_jit_compile_method_inner (method, opt, error);
unregister_method_for_compile (method);
}
if (!is_ok (error))
return NULL;
if (!code && mono_llvm_only) {
printf ("AOT method not found in llvmonly mode: %s\n", mono_method_full_name (method, 1));
g_assert_not_reached ();
}
if (!code)
return NULL;
//FIXME mini_jit_info_table_find doesn't work yet under wasm due to code_start/code_end issues.
#ifndef HOST_WASM
if ((method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER || method->wrapper_type == MONO_WRAPPER_ALLOC)) {
/*
* SGEN requires the JIT info for these methods to be registered, see is_ip_in_managed_allocator ().
*/
MonoJitInfo *ji = mini_jit_info_table_find (code);
g_assert (ji);
}
#endif
p = mono_create_ftnptr (code);
if (callinfo) {
// FIXME Locking here is somewhat historical due to mono_register_jit_icall_wrapper taking loader lock.
// atomic_compare_exchange should suffice.
mono_loader_lock ();
mono_jit_lock ();
if (!callinfo->wrapper) {
callinfo->wrapper = p;
}
mono_jit_unlock ();
mono_loader_unlock ();
}
// FIXME p or callinfo->wrapper or does not matter?
return p;
}
typedef struct {
MonoMethod *method;
guint32 opt;
gboolean jit_only;
MonoError *error;
gpointer code;
} JitCompileMethodWithOptCallbackData;
static void
jit_compile_method_with_opt_cb (gpointer arg)
{
JitCompileMethodWithOptCallbackData *params = (JitCompileMethodWithOptCallbackData *)arg;
params->code = mono_jit_compile_method_with_opt (params->method, params->opt, params->jit_only, params->error);
}
static gpointer
jit_compile_method_with_opt (JitCompileMethodWithOptCallbackData *params)
{
MonoLMFExt ext;
memset (&ext, 0, sizeof (MonoLMFExt));
ext.kind = MONO_LMFEXT_JIT_ENTRY;
mono_push_lmf (&ext);
gboolean thrown = FALSE;
#if defined(ENABLE_LLVM_RUNTIME) || defined(ENABLE_LLVM)
mono_llvm_cpp_catch_exception (jit_compile_method_with_opt_cb, params, &thrown);
#else
jit_compile_method_with_opt_cb (params);
#endif
mono_pop_lmf (&ext.lmf);
return !thrown ? params->code : NULL;
}
gpointer
mono_jit_compile_method (MonoMethod *method, MonoError *error)
{
JitCompileMethodWithOptCallbackData params;
params.method = method;
params.opt = mono_get_optimizations_for_method (method, default_opt);
params.jit_only = FALSE;
params.error = error;
params.code = NULL;
return jit_compile_method_with_opt (¶ms);
}
/*
* mono_jit_compile_method_jit_only:
*
* Compile METHOD using the JIT/AOT, even in interpreted mode.
*/
gpointer
mono_jit_compile_method_jit_only (MonoMethod *method, MonoError *error)
{
JitCompileMethodWithOptCallbackData params;
params.method = method;
params.opt = mono_get_optimizations_for_method (method, default_opt);
params.jit_only = TRUE;
params.error = error;
params.code = NULL;
return jit_compile_method_with_opt (¶ms);
}
/*
* get_ftnptr_for_method:
*
* Return a function pointer for METHOD which is indirectly callable from managed code.
* On llvmonly, this returns a MonoFtnDesc, otherwise it returns a normal function pointer.
*/
static gpointer
get_ftnptr_for_method (MonoMethod *method, MonoError *error)
{
if (!mono_llvm_only) {
return mono_jit_compile_method (method, error);
} else {
return mini_llvmonly_load_method_ftndesc (method, FALSE, FALSE, error);
}
}
#ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
static void
invalidated_delegate_trampoline (char *desc)
{
g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
"See http://www.mono-project.com/Diagnostic:Delegate for an explanation and ways to fix this.",
desc);
}
#endif
/*
* mono_jit_free_method:
*
* Free all memory allocated by the JIT for METHOD.
*/
static void
mono_jit_free_method (MonoMethod *method)
{
MonoJitDynamicMethodInfo *ji;
gboolean destroy = TRUE, removed;
GHashTableIter iter;
MonoJumpList *jlist;
MonoJitMemoryManager *jit_mm;
g_assert (method->dynamic);
if (mono_use_interpreter)
mini_get_interp_callbacks ()->free_method (method);
ji = mono_dynamic_code_hash_lookup (method);
if (!ji)
return;
mono_debug_remove_method (method, NULL);
mono_lldb_remove_method (method, ji);
//seq_points are always on get_default_jit_mm
jit_mm = get_default_jit_mm ();
jit_mm_lock (jit_mm);
g_hash_table_remove (jit_mm->seq_points, method);
jit_mm_unlock (jit_mm);
jit_mm = jit_mm_for_method (method);
jit_code_hash_lock (jit_mm);
removed = mono_internal_hash_table_remove (&jit_mm->jit_code_hash, method);
g_assert (removed);
jit_code_hash_unlock (jit_mm);
ji->ji->seq_points = NULL;
jit_mm_lock (jit_mm);
mono_conc_hashtable_remove (jit_mm->runtime_invoke_hash, method);
g_hash_table_remove (jit_mm->dynamic_code_hash, method);
g_hash_table_remove (jit_mm->jump_trampoline_hash, method);
g_hash_table_remove (jit_mm->seq_points, method);
g_hash_table_iter_init (&iter, jit_mm->jump_target_hash);
while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
GSList *tmp, *remove;
remove = NULL;
for (tmp = jlist->list; tmp; tmp = tmp->next) {
guint8 *ip = (guint8 *)tmp->data;
if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
remove = g_slist_prepend (remove, tmp);
}
for (tmp = remove; tmp; tmp = tmp->next) {
jlist->list = g_slist_delete_link ((GSList *)jlist->list, (GSList *)tmp->data);
}
g_slist_free (remove);
}
jit_mm_unlock (jit_mm);
#ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
if (mini_debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
/*
* Instead of freeing the code, change it to call an error routine
* so people can fix their code.
*/
char *type = mono_type_full_name (m_class_get_byval_arg (method->klass));
char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
g_free (type);
mono_arch_invalidate_method (ji->ji, (gpointer)invalidated_delegate_trampoline, (gpointer)type_and_method);
destroy = FALSE;
}
#endif
/*
* This needs to be done before freeing code_mp, since the code address is the
* key in the table, so if we free the code_mp first, another thread can grab the
* same code address and replace our entry in the table.
*/
mono_jit_info_table_remove (ji->ji);
if (destroy)
mono_code_manager_destroy (ji->code_mp);
g_free (ji);
}
gpointer
mono_jit_search_all_backends_for_jit_info (MonoMethod *method, MonoJitInfo **out_ji)
{
gpointer code;
MonoJitInfo *ji;
code = mono_jit_find_compiled_method_with_jit_info (method, &ji);
if (!code) {
ERROR_DECL (oerror);
/* Might be AOTed code */
mono_class_init_internal (method->klass);
code = mono_aot_get_method (method, oerror);
if (code) {
mono_error_assert_ok (oerror);
ji = mini_jit_info_table_find (code);
} else {
if (!is_ok (oerror))
mono_error_cleanup (oerror);
/* Might be interpreted */
ji = mini_get_interp_callbacks ()->find_jit_info (method);
}
}
*out_ji = ji;
return code;
}
gpointer
mono_jit_find_compiled_method_with_jit_info (MonoMethod *method, MonoJitInfo **ji)
{
MonoJitInfo *info;
info = lookup_method (method);
if (info) {
mono_atomic_inc_i32 (&mono_jit_stats.methods_lookups);
if (ji)
*ji = info;
return MINI_ADDR_TO_FTNPTR (info->code_start);
}
if (ji)
*ji = NULL;
return NULL;
}
static guint32 bisect_opt = 0;
static GHashTable *bisect_methods_hash = NULL;
void
mono_set_bisect_methods (guint32 opt, const char *method_list_filename)
{
FILE *file;
char method_name [2048];
bisect_opt = opt;
bisect_methods_hash = g_hash_table_new (g_str_hash, g_str_equal);
g_assert (bisect_methods_hash);
file = fopen (method_list_filename, "r");
g_assert (file);
while (fgets (method_name, sizeof (method_name), file)) {
size_t len = strlen (method_name);
g_assert (len > 0);
g_assert (method_name [len - 1] == '\n');
method_name [len - 1] = 0;
g_hash_table_insert (bisect_methods_hash, g_strdup (method_name), GINT_TO_POINTER (1));
}
g_assert (feof (file));
}
gboolean mono_do_single_method_regression = FALSE;
guint32 mono_single_method_regression_opt = 0;
MonoMethod *mono_current_single_method;
GSList *mono_single_method_list;
GHashTable *mono_single_method_hash;
guint32
mono_get_optimizations_for_method (MonoMethod *method, guint32 opt)
{
g_assert (method);
if (bisect_methods_hash) {
char *name = mono_method_full_name (method, TRUE);
void *res = g_hash_table_lookup (bisect_methods_hash, name);
g_free (name);
if (res)
return opt | bisect_opt;
}
if (!mono_do_single_method_regression)
return opt;
if (!mono_current_single_method) {
if (!mono_single_method_hash)
mono_single_method_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
if (!g_hash_table_lookup (mono_single_method_hash, method)) {
g_hash_table_insert (mono_single_method_hash, method, method);
mono_single_method_list = g_slist_prepend (mono_single_method_list, method);
}
return opt;
}
if (method == mono_current_single_method)
return mono_single_method_regression_opt;
return opt;
}
gpointer
mono_jit_find_compiled_method (MonoMethod *method)
{
return mono_jit_find_compiled_method_with_jit_info (method, NULL);
}
typedef struct {
MonoMethod *method;
gpointer compiled_method;
gpointer runtime_invoke;
MonoVTable *vtable;
MonoDynCallInfo *dyn_call_info;
MonoClass *ret_box_class;
MonoMethodSignature *sig;
gboolean gsharedvt_invoke;
gboolean use_interp;
gpointer *wrapper_arg;
} RuntimeInvokeInfo;
#define MONO_SIZEOF_DYN_CALL_RET_BUF TARGET_SIZEOF_VOID_P
static RuntimeInvokeInfo*
create_runtime_invoke_info (MonoMethod *method, gpointer compiled_method, gboolean callee_gsharedvt, gboolean use_interp, MonoError *error)
{
MonoMethod *invoke;
RuntimeInvokeInfo *info = NULL;
RuntimeInvokeInfo *ret = NULL;
info = g_new0 (RuntimeInvokeInfo, 1);
info->compiled_method = compiled_method;
info->use_interp = use_interp;
info->sig = mono_method_signature_internal (method);
invoke = mono_marshal_get_runtime_invoke (method, FALSE);
(void)invoke;
info->vtable = mono_class_vtable_checked (method->klass, error);
if (!is_ok (error))
goto exit;
g_assert (info->vtable);
MonoMethodSignature *sig;
sig = info->sig;
MonoType *ret_type;
/*
* We want to avoid AOTing 1000s of runtime-invoke wrappers when running
* in full-aot mode, so we use a slower, but more generic wrapper if
* possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
*/
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (!mono_llvm_only && (mono_aot_only || mini_debug_options.dyn_runtime_invoke)) {
gboolean supported = TRUE;
int i;
if (method->string_ctor)
sig = mono_marshal_get_string_ctor_signature (method);
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (m_type_is_byref (t) && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t)))
supported = FALSE;
}
if (!info->compiled_method)
supported = FALSE;
if (supported) {
info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
if (mini_debug_options.dyn_runtime_invoke)
g_assert (info->dyn_call_info);
}
}
#endif
ret_type = sig->ret;
switch (ret_type->type) {
case MONO_TYPE_VOID:
break;
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_I8:
case MONO_TYPE_U8:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
case MONO_TYPE_PTR:
info->ret_box_class = mono_defaults.int_class;
break;
case MONO_TYPE_STRING:
case MONO_TYPE_CLASS:
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_OBJECT:
break;
case MONO_TYPE_GENERICINST:
if (!MONO_TYPE_IS_REFERENCE (ret_type))
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
case MONO_TYPE_VALUETYPE:
info->ret_box_class = mono_class_from_mono_type_internal (ret_type);
break;
default:
g_assert_not_reached ();
break;
}
if (info->use_interp) {
ret = info;
info = NULL;
goto exit;
}
if (!info->dyn_call_info) {
/*
* Can't use the normal llvmonly code for string ctors since the gsharedvt out wrapper passes
* an extra arg, which the string ctor methods don't have, which causes signature mismatches
* on wasm. Instead, call string ctors normally using a direct runtime invoke wrapper
* which is AOTed for each ctor.
*/
if (mono_llvm_only && !method->string_ctor) {
#ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
g_assert_not_reached ();
#endif
info->gsharedvt_invoke = TRUE;
if (!callee_gsharedvt) {
/* Invoke a gsharedvt out wrapper instead */
MonoMethod *wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
info->wrapper_arg = g_malloc0 (2 * sizeof (gpointer));
info->wrapper_arg [0] = mini_llvmonly_add_method_wrappers (method, info->compiled_method, FALSE, FALSE, &(info->wrapper_arg [1]));
/* Pass has_rgctx == TRUE since the wrapper has an extra arg */
invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
g_free (wrapper_sig);
info->compiled_method = mono_jit_compile_method (wrapper, error);
if (!is_ok (error))
goto exit;
} else {
/* Gsharedvt methods can be invoked the same way */
/* The out wrapper has the same signature as the compiled gsharedvt method */
MonoMethodSignature *wrapper_sig = mini_get_gsharedvt_out_sig_wrapper_signature (sig->hasthis, sig->ret->type != MONO_TYPE_VOID, sig->param_count);
info->wrapper_arg = (gpointer*)(mono_method_needs_static_rgctx_invoke (method, TRUE) ? mini_method_get_rgctx (method) : NULL);
invoke = mono_marshal_get_runtime_invoke_for_sig (wrapper_sig);
g_free (wrapper_sig);
}
}
info->runtime_invoke = mono_jit_compile_method (invoke, error);
if (!is_ok (error))
goto exit;
}
ret = info;
info = NULL;
exit:
g_free (info);
return ret;
}
static GENERATE_GET_CLASS_WITH_CACHE (nullbyrefreturn_ex, "Mono", "NullByRefReturnException");
static MonoObject*
mono_llvmonly_runtime_invoke (MonoMethod *method, RuntimeInvokeInfo *info, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MonoMethodSignature *sig = info->sig;
MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
int32_t retval_size = MONO_SIZEOF_DYN_CALL_RET_BUF;
gpointer retval = NULL;
int i, pindex;
error_init (error);
g_assert (info->gsharedvt_invoke);
/*
* Instead of invoking the method directly, we invoke a gsharedvt out wrapper.
* The advantage of this is the gsharedvt out wrappers have a reduced set of
* signatures, so we only have to generate runtime invoke wrappers for these
* signatures.
* This code also handles invocation of gsharedvt methods directly, no
* out wrappers are used in that case.
*/
// allocate param_refs = param_count and args = param_count + hasthis + 2.
int const param_count = sig->param_count;
gpointer* const param_refs = g_newa (gpointer, param_count * 2 + sig->hasthis + 2);
gpointer* const args = param_refs + param_count;
pindex = 0;
/*
* The runtime invoke wrappers expects pointers to primitive types, so have to
* use indirections.
*/
if (sig->hasthis)
args [pindex ++] = &obj;
if (sig->ret->type != MONO_TYPE_VOID) {
if (info->ret_box_class && !m_type_is_byref (sig->ret) &&
(sig->ret->type == MONO_TYPE_VALUETYPE ||
(sig->ret->type == MONO_TYPE_GENERICINST && !MONO_TYPE_IS_REFERENCE (sig->ret)))) {
// if the return type is a struct, allocate enough stack space to hold it
MonoClass *ret_klass = mono_class_from_mono_type_internal (sig->ret);
g_assert (!mono_class_has_failure (ret_klass));
int32_t inst_size = mono_class_instance_size (ret_klass);
if (inst_size > MONO_SIZEOF_DYN_CALL_RET_BUF) {
retval_size = inst_size;
}
}
}
retval = g_alloca (retval_size);
if (sig->ret->type != MONO_TYPE_VOID) {
args [pindex ++] = &retval;
}
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
MonoClass *klass = mono_class_from_mono_type_internal (t);
guint8 *nullable_buf;
int size;
size = mono_class_value_size (klass, NULL);
nullable_buf = g_alloca (size);
g_assert (nullable_buf);
/* The argument pointed to by params [i] is either a boxed vtype or null */
mono_nullable_init (nullable_buf, (MonoObject*)params [i], klass);
params [i] = nullable_buf;
}
if (!m_type_is_byref (t) && (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR)) {
param_refs [i] = params [i];
params [i] = &(param_refs [i]);
}
args [pindex ++] = ¶ms [i];
}
/* The gsharedvt out wrapper has an extra argument which contains the method to call */
args [pindex ++] = &info->wrapper_arg;
runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
runtime_invoke (NULL, args, exc, info->compiled_method);
if (exc && *exc)
return NULL;
if (m_type_is_byref (sig->ret)) {
if (*(gpointer*)retval == NULL) {
MonoClass *klass = mono_class_get_nullbyrefreturn_ex_class ();
MonoObject *ex = mono_object_new_checked (klass, error);
mono_error_assert_ok (error);
mono_error_set_exception_instance (error, (MonoException*)ex);
return NULL;
}
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (info->ret_box_class) {
if (m_type_is_byref (sig->ret)) {
return mono_value_box_checked (info->ret_box_class, *(gpointer*)retval, error);
} else {
MonoObject *ret = mono_value_box_checked (info->ret_box_class, retval, error);
return ret;
}
} else {
if (m_type_is_byref (sig->ret))
return **(MonoObject***)retval;
else
return *(MonoObject**)retval;
}
} else {
return NULL;
}
}
/**
* mono_jit_runtime_invoke:
* \param method: the method to invoke
* \param obj: this pointer
* \param params: array of parameter values.
* \param exc: Set to the exception raised in the managed method.
* \param error: error or caught exception object
* If \p exc is NULL, \p error is thrown instead.
* If coop is enabled, \p exc argument is ignored -
* all exceptions are caught and propagated through \p error
*/
static MonoObject*
mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
{
MonoMethod *callee;
MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
RuntimeInvokeInfo *info, *info2;
MonoJitInfo *ji = NULL;
gboolean callee_gsharedvt = FALSE;
MonoJitMemoryManager *jit_mm;
if (mono_ee_features.force_use_interpreter) {
// FIXME: On wasm, if the callee throws an exception, this will return NULL, and the
// exception will be stored inside the interpreter, it won't show up in exc/error.
return mini_get_interp_callbacks ()->runtime_invoke (method, obj, params, exc, error);
}
error_init (error);
if (exc)
*exc = NULL;
if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
return NULL;
}
jit_mm = jit_mm_for_method (method);
info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (jit_mm->runtime_invoke_hash, method);
if (!info) {
gpointer compiled_method;
callee = method;
if (m_class_get_rank (method->klass) && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
(method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
/*
* Array Get/Set/Address methods. The JIT implements them using inline code
* inside the runtime invoke wrappers, so no need to compile them.
*/
if (mono_aot_only) {
/*
* Call a wrapper, since the runtime invoke wrapper was not generated.
*/
MonoMethod *wrapper;
wrapper = mono_marshal_get_array_accessor_wrapper (method);
mono_marshal_get_runtime_invoke (wrapper, FALSE);
callee = wrapper;
} else {
callee = NULL;
}
}
gboolean use_interp = FALSE;
if (mono_aot_mode == MONO_AOT_MODE_LLVMONLY_INTERP)
/* The runtime invoke wrappers contain clauses so they are not AOTed */
use_interp = TRUE;
if (callee) {
compiled_method = mono_jit_compile_method_jit_only (callee, error);
if (!compiled_method) {
g_assert (!is_ok (error));
if (mono_use_interpreter)
use_interp = TRUE;
else
return NULL;
} else {
if (mono_llvm_only) {
ji = mini_jit_info_table_find (mono_get_addr_from_ftnptr (compiled_method));
callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
if (callee_gsharedvt)
callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (ji)));
}
if (!callee_gsharedvt)
compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
}
} else {
compiled_method = NULL;
}
info = create_runtime_invoke_info (method, compiled_method, callee_gsharedvt, use_interp, error);
if (!is_ok (error))
return NULL;
jit_mm_lock (jit_mm);
info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (jit_mm->runtime_invoke_hash, method, info);
jit_mm_unlock (jit_mm);
if (info2) {
g_free (info);
info = info2;
}
}
/*
* We need this here because mono_marshal_get_runtime_invoke can place
* the helper method in System.Object and not the target class.
*/
if (!mono_runtime_class_init_full (info->vtable, error)) {
if (exc)
*exc = (MonoObject*) mono_error_convert_to_exception (error);
return NULL;
}
/* If coop is enabled, and the caller didn't ask for the exception to be caught separately,
we always catch the exception and propagate it through the MonoError */
gboolean catchExcInMonoError =
(exc == NULL) && mono_threads_are_safepoints_enabled ();
MonoObject *invoke_exc = NULL;
if (catchExcInMonoError)
exc = &invoke_exc;
/* The wrappers expect this to be initialized to NULL */
if (exc)
*exc = NULL;
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
static RuntimeInvokeDynamicFunction dyn_runtime_invoke = NULL;
if (info->dyn_call_info) {
if (!dyn_runtime_invoke) {
MonoMethod *dynamic_invoke = mono_marshal_get_runtime_invoke_dynamic ();
RuntimeInvokeDynamicFunction invoke_func = (RuntimeInvokeDynamicFunction)mono_jit_compile_method_jit_only (dynamic_invoke, error);
mono_memory_barrier ();
dyn_runtime_invoke = invoke_func;
if (!dyn_runtime_invoke && mono_use_interpreter) {
info->use_interp = TRUE;
info->dyn_call_info = NULL;
} else if (!is_ok (error)) {
return NULL;
}
}
}
if (info->dyn_call_info) {
MonoMethodSignature *sig = mono_method_signature_internal (method);
gpointer *args;
int i, pindex, buf_size;
guint8 *buf;
int32_t retval_size = MONO_SIZEOF_DYN_CALL_RET_BUF;
guint8 *retval = NULL;
/* if the return type is a struct and it's too big, allocate more space for it */
if (info->ret_box_class && !m_type_is_byref (sig->ret) &&
(sig->ret->type == MONO_TYPE_VALUETYPE ||
(sig->ret->type == MONO_TYPE_GENERICINST && !MONO_TYPE_IS_REFERENCE (sig->ret)))) {
MonoClass *ret_klass = mono_class_from_mono_type_internal (sig->ret);
g_assert (!mono_class_has_failure (ret_klass));
int32_t inst_size = mono_class_instance_size (ret_klass);
if (inst_size > MONO_SIZEOF_DYN_CALL_RET_BUF) {
retval_size = inst_size;
}
}
retval = g_alloca (retval_size);
/* Convert the arguments to the format expected by start_dyn_call () */
args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
pindex = 0;
if (sig->hasthis)
args [pindex ++] = &obj;
for (i = 0; i < sig->param_count; ++i) {
MonoType *t = sig->params [i];
if (m_type_is_byref (t)) {
args [pindex ++] = ¶ms [i];
} else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
args [pindex ++] = ¶ms [i];
} else {
args [pindex ++] = params [i];
}
}
//printf ("M: %s\n", mono_method_full_name (method, TRUE));
buf_size = mono_arch_dyn_call_get_buf_size (info->dyn_call_info);
buf = g_alloca (buf_size);
memset (buf, 0, buf_size);
g_assert (buf);
mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf);
dyn_runtime_invoke (buf, exc, info->compiled_method);
mono_arch_finish_dyn_call (info->dyn_call_info, buf);
if (catchExcInMonoError && *exc != NULL) {
mono_error_set_exception_instance (error, (MonoException*) *exc);
return NULL;
}
if (m_type_is_byref (sig->ret)) {
if (*(gpointer*)retval == NULL) {
MonoClass *klass = mono_class_get_nullbyrefreturn_ex_class ();
MonoObject *ex = mono_object_new_checked (klass, error);
mono_error_assert_ok (error);
mono_error_set_exception_instance (error, (MonoException*)ex);
return NULL;
}
}
if (info->ret_box_class) {
if (m_type_is_byref (sig->ret)) {
return mono_value_box_checked (info->ret_box_class, *(gpointer*)retval, error);
} else {
MonoObject *boxed_ret = mono_value_box_checked (info->ret_box_class, retval, error);
return boxed_ret;
}
} else {
if (m_type_is_byref (sig->ret))
return **(MonoObject***)retval;
else
return *(MonoObject**)retval;
}
}
#endif
MonoObject *result;
if (info->use_interp) {
result = mini_get_interp_callbacks ()->runtime_invoke (method, obj, params, exc, error);
return_val_if_nok (error, NULL);
} else if (mono_llvm_only && !method->string_ctor) {
result = mono_llvmonly_runtime_invoke (method, info, obj, params, exc, error);
if (!is_ok (error))
return NULL;
} else {
runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;
result = runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
}
if (catchExcInMonoError && *exc != NULL) {
((MonoException *)(*exc))->caught_in_unmanaged = TRUE;
mono_error_set_exception_instance (error, (MonoException*) *exc);
}
return result;
}
MONO_SIG_HANDLER_FUNC (, mono_sigfpe_signal_handler)
{
MonoException *exc = NULL;
MonoJitInfo *ji;
MonoContext mctx;
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
MONO_SIG_HANDLER_GET_CONTEXT;
ji = mono_jit_info_table_find_internal (mono_arch_ip_from_context (ctx), TRUE, TRUE);
MONO_ENTER_GC_UNSAFE_UNBALANCED;
#if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
if (mono_arch_is_int_overflow (ctx, info))
/*
* The spec says this throws ArithmeticException, but MS throws the derived
* OverflowException.
*/
exc = mono_get_exception_overflow ();
else
exc = mono_get_exception_divide_by_zero ();
#else
exc = mono_get_exception_divide_by_zero ();
#endif
if (!ji) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
goto exit;
mono_sigctx_to_monoctx (ctx, &mctx);
mono_handle_native_crash (mono_get_signame (SIGFPE), &mctx, info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
goto exit;
}
}
mono_arch_handle_exception (ctx, exc);
exit:
MONO_EXIT_GC_UNSAFE_UNBALANCED;
}
MONO_SIG_HANDLER_FUNC (, mono_crashing_signal_handler)
{
MonoContext mctx;
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
MONO_SIG_HANDLER_GET_CONTEXT;
if (mono_runtime_get_no_exec ())
exit (1);
mono_sigctx_to_monoctx (ctx, &mctx);
#if defined(HAVE_SIG_INFO) && !defined(HOST_WIN32) // info is a siginfo_t
mono_handle_native_crash (mono_get_signame (info->si_signo), &mctx, info);
#else
mono_handle_native_crash (mono_get_signame (SIGTERM), &mctx, info);
#endif
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
#define HAVE_SIG_INFO
#define MONO_SIG_HANDLER_DEBUG 1 // "with_fault_addr" but could be extended in future, so "debug"
#ifdef MONO_SIG_HANDLER_DEBUG
// Same as MONO_SIG_HANDLER_FUNC but debug_fault_addr is added to params, and no_optimize.
// The Krait workaround is not needed here, due to this not actually being the signal handler,
// so MONO_SIGNAL_HANDLER_FUNC is combined into it.
#define MONO_SIG_HANDLER_FUNC_DEBUG(access, ftn) access MONO_NO_OPTIMIZATION void ftn \
(int _dummy, MONO_SIG_HANDLER_INFO_TYPE *_info, void *context, void * volatile debug_fault_addr G_GNUC_UNUSED)
#define MONO_SIG_HANDLER_PARAMS_DEBUG MONO_SIG_HANDLER_PARAMS, debug_fault_addr
#endif
#endif
gboolean
mono_is_addr_implicit_null_check (void *addr)
{
/* implicit null checks are only expected to work on the first page. larger
* offsets are expected to have an explicit null check */
return addr <= GUINT_TO_POINTER (mono_target_pagesize ());
}
// This function is separate from mono_sigsegv_signal_handler
// so debug_fault_addr can be seen in debugger stacks.
#ifdef MONO_SIG_HANDLER_DEBUG
MONO_NEVER_INLINE
MONO_SIG_HANDLER_FUNC_DEBUG (static, mono_sigsegv_signal_handler_debug)
#else
MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
#endif
{
MonoJitInfo *ji = NULL;
MonoDomain *domain = mono_domain_get ();
gpointer fault_addr = NULL;
MonoContext mctx;
#if defined(HAVE_SIG_INFO) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
#endif
#ifdef HAVE_SIG_INFO
MONO_SIG_HANDLER_INFO_TYPE *info = MONO_SIG_HANDLER_GET_INFO ();
#else
void *info = NULL;
#endif
MONO_SIG_HANDLER_GET_CONTEXT;
mono_sigctx_to_monoctx (ctx, &mctx);
#if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
if (mono_arch_is_single_step_event (info, ctx)) {
mono_component_debugger ()->single_step_event (ctx);
return;
} else if (mono_arch_is_breakpoint_event (info, ctx)) {
mono_component_debugger ()->breakpoint_hit (ctx);
return;
}
#endif
#if defined(HAVE_SIG_INFO)
#if !defined(HOST_WIN32)
fault_addr = info->si_addr;
if (mono_aot_is_pagefault (info->si_addr)) {
mono_aot_handle_pagefault (info->si_addr);
return;
}
int signo = info->si_signo;
#else
int signo = SIGSEGV;
#endif
/* The thread might no be registered with the runtime */
if (!mono_domain_get () || !jit_tls) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
mono_handle_native_crash (mono_get_signame (signo), &mctx, info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#endif
if (domain) {
gpointer ip = MINI_FTNPTR_TO_ADDR (mono_arch_ip_from_context (ctx));
ji = mono_jit_info_table_find_internal (ip, TRUE, TRUE);
}
#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, info, (guint8*)info->si_addr))
return;
/* info->si_addr seems to be NULL on some kernels when handling stack overflows */
fault_addr = info->si_addr;
if (fault_addr == NULL) {
fault_addr = MONO_CONTEXT_GET_SP (&mctx);
}
if (jit_tls && jit_tls->stack_size &&
ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
/*
* The hard-guard page has been hit: there is not much we can do anymore
* Print a hopefully clear message and abort.
*/
mono_handle_hard_stack_ovf (jit_tls, ji, &mctx, (guint8*)info->si_addr);
g_assert_not_reached ();
} else {
/* The original handler might not like that it is executed on an altstack... */
if (!ji && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
#ifdef TARGET_AMD64
/* exceptions-amd64.c handles the check itself */
mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
#else
if (mono_is_addr_implicit_null_check (info->si_addr)) {
mono_arch_handle_altstack_exception (ctx, info, info->si_addr, FALSE);
} else {
// FIXME: This shouldn't run on the altstack
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, info);
}
#endif
}
#else
if (!ji) {
if (!mono_do_crash_chaining && mono_chain_signal (MONO_SIG_HANDLER_PARAMS))
return;
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, (MONO_SIG_HANDLER_INFO_TYPE*)info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
if (mono_is_addr_implicit_null_check (fault_addr)) {
mono_arch_handle_exception (ctx, NULL);
} else {
mono_handle_native_crash (mono_get_signame (SIGSEGV), &mctx, (MONO_SIG_HANDLER_INFO_TYPE*)info);
if (mono_do_crash_chaining) {
mono_chain_signal (MONO_SIG_HANDLER_PARAMS);
return;
}
}
#endif
}
#ifdef MONO_SIG_HANDLER_DEBUG
// This function is separate from mono_sigsegv_signal_handler_debug
// so debug_fault_addr can be seen in debugger stacks.
MONO_SIG_HANDLER_FUNC (, mono_sigsegv_signal_handler)
{
#ifdef HOST_WIN32
gpointer const debug_fault_addr = (gpointer)MONO_SIG_HANDLER_GET_INFO () ->ep->ExceptionRecord->ExceptionInformation [1];
#elif defined (HAVE_SIG_INFO)
gpointer const debug_fault_addr = MONO_SIG_HANDLER_GET_INFO ()->si_addr;
#else
#error No extra parameter is passed, not even 0, to avoid any confusion.
#endif
mono_sigsegv_signal_handler_debug (MONO_SIG_HANDLER_PARAMS_DEBUG);
}
#endif // MONO_SIG_HANDLER_DEBUG
MONO_SIG_HANDLER_FUNC (, mono_sigint_signal_handler)
{
MonoException *exc;
MONO_SIG_HANDLER_GET_CONTEXT;
MONO_ENTER_GC_UNSAFE_UNBALANCED;
exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
mono_arch_handle_exception (ctx, exc);
MONO_EXIT_GC_UNSAFE_UNBALANCED;
}
static G_GNUC_UNUSED void
no_imt_trampoline (void)
{
g_assert_not_reached ();
}
static G_GNUC_UNUSED void
no_vcall_trampoline (void)
{
g_assert_not_reached ();
}
static gpointer *vtable_trampolines;
static int vtable_trampolines_size;
gpointer
mini_get_vtable_trampoline (MonoVTable *vt, int slot_index)
{
int index = slot_index + MONO_IMT_SIZE;
if (mono_llvm_only)
return mini_llvmonly_get_vtable_trampoline (vt, slot_index, index);
g_assert (slot_index >= - MONO_IMT_SIZE);
if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
mono_jit_lock ();
if (!vtable_trampolines || index >= vtable_trampolines_size) {
int new_size;
gpointer new_table;
new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
while (new_size <= index)
new_size *= 2;
new_table = g_new0 (gpointer, new_size);
if (vtable_trampolines)
memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
g_free (vtable_trampolines);
mono_memory_barrier ();
vtable_trampolines = (void **)new_table;
vtable_trampolines_size = new_size;
}
mono_jit_unlock ();
}
if (!vtable_trampolines [index])
vtable_trampolines [index] = mono_create_specific_trampoline (get_default_mem_manager (), GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, NULL);
return vtable_trampolines [index];
}
static gpointer
mini_get_imt_trampoline (MonoVTable *vt, int slot_index)
{
return mini_get_vtable_trampoline (vt, slot_index - MONO_IMT_SIZE);
}
static gboolean
mini_imt_entry_inited (MonoVTable *vt, int imt_slot_index)
{
if (mono_llvm_only)
return FALSE;
gpointer *imt = (gpointer*)vt;
imt -= MONO_IMT_SIZE;
return (imt [imt_slot_index] != mini_get_imt_trampoline (vt, imt_slot_index));
}
static gpointer
create_delegate_method_ptr (MonoMethod *method, MonoError *error)
{
gpointer func;
if (method_is_dynamic (method)) {
/* Creating a trampoline would leak memory */
func = mono_compile_method_checked (method, error);
return_val_if_nok (error, NULL);
} else {
gpointer trampoline = mono_create_jump_trampoline (method, TRUE, error);
return_val_if_nok (error, NULL);
func = mono_create_ftnptr (trampoline);
}
return func;
}
static void
mini_init_delegate (MonoDelegateHandle delegate, MonoObjectHandle target, gpointer addr, MonoMethod *method, MonoError *error)
{
MonoDelegate *del = MONO_HANDLE_RAW (delegate);
if (!method && !addr) {
// Multicast delegate init
if (!mono_llvm_only) {
MONO_HANDLE_SETVAL (delegate, invoke_impl, gpointer, mono_create_delegate_trampoline (mono_handle_class (delegate)));
} else {
mini_llvmonly_init_delegate (del, NULL);
}
return;
}
if (!method) {
MonoJitInfo *ji;
gpointer lookup_addr = MINI_FTNPTR_TO_ADDR (addr);
g_assert (addr);
ji = mono_jit_info_table_find_internal (mono_get_addr_from_ftnptr (lookup_addr), TRUE, TRUE);
if (ji) {
if (ji->is_trampoline) {
/* Could be an unbox trampoline etc. */
method = ji->d.tramp_info->method;
} else {
method = mono_jit_info_get_method (ji);
g_assert (!mono_class_is_gtd (method->klass));
}
}
}
if (method)
MONO_HANDLE_SETVAL (delegate, method, MonoMethod*, method);
if (addr)
MONO_HANDLE_SETVAL (delegate, method_ptr, gpointer, addr);
MONO_HANDLE_SET (delegate, target, target);
MONO_HANDLE_SETVAL (delegate, invoke_impl, gpointer, mono_create_delegate_trampoline (mono_handle_class (delegate)));
MonoDelegateTrampInfo *info = NULL;
if (mono_use_interpreter) {
mini_get_interp_callbacks ()->init_delegate (del, &info, error);
return_if_nok (error);
}
if (mono_llvm_only) {
g_assert (del->method);
mini_llvmonly_init_delegate (del, info);
//del->method_ptr = mini_llvmonly_load_method_delegate (del->method, FALSE, FALSE, &del->extra_arg, error);
} else if (!del->method_ptr) {
del->method_ptr = create_delegate_method_ptr (del->method, error);
return_if_nok (error);
}
}
char*
mono_get_delegate_virtual_invoke_impl_name (gboolean load_imt_reg, int offset)
{
int abs_offset;
abs_offset = offset;
if (abs_offset < 0)
abs_offset = - abs_offset;
return g_strdup_printf ("delegate_virtual_invoke%s_%s%d", load_imt_reg ? "_imt" : "", offset < 0 ? "m_" : "", abs_offset / TARGET_SIZEOF_VOID_P);
}
gpointer
mono_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method)
{
gboolean is_virtual_generic, is_interface, load_imt_reg;
int offset, idx;
static guint8 **cache = NULL;
static int cache_size = 0;
if (!method)
return NULL;
if (MONO_TYPE_ISSTRUCT (sig->ret))
return NULL;
is_virtual_generic = method->is_inflated && mono_method_get_declaring_generic_method (method)->is_generic;
is_interface = mono_class_is_interface (method->klass);
load_imt_reg = is_virtual_generic || is_interface;
if (is_interface)
offset = ((gint32)mono_method_get_imt_slot (method) - MONO_IMT_SIZE) * TARGET_SIZEOF_VOID_P;
else
offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + ((mono_method_get_vtable_index (method)) * (TARGET_SIZEOF_VOID_P));
idx = (offset / TARGET_SIZEOF_VOID_P + MONO_IMT_SIZE) * 2 + (load_imt_reg ? 1 : 0);
g_assert (idx >= 0);
/* Resize the cache to idx + 1 */
if (cache_size < idx + 1) {
mono_jit_lock ();
if (cache_size < idx + 1) {
guint8 **new_cache;
int new_cache_size = idx + 1;
new_cache = g_new0 (guint8*, new_cache_size);
if (cache)
memcpy (new_cache, cache, cache_size * sizeof (guint8*));
g_free (cache);
mono_memory_barrier ();
cache = new_cache;
cache_size = new_cache_size;
}
mono_jit_unlock ();
}
if (cache [idx])
return cache [idx];
/* FIXME Support more cases */
if (mono_ee_features.use_aot_trampolines) {
cache [idx] = (guint8 *)mono_aot_get_trampoline (mono_get_delegate_virtual_invoke_impl_name (load_imt_reg, offset));
g_assert (cache [idx]);
} else {
cache [idx] = (guint8 *)mono_arch_get_delegate_virtual_invoke_impl (sig, method, offset, load_imt_reg);
}
return cache [idx];
}
/**
* mini_parse_debug_option:
* @option: The option to parse.
*
* Parses debug options for the mono runtime. The options are the same as for
* the MONO_DEBUG environment variable.
*
*/
gboolean
mini_parse_debug_option (const char *option)
{
// Empty string is ok as consequence of appending ",foo"
// without first checking for empty.
if (*option == 0)
return TRUE;
if (!strcmp (option, "handle-sigint"))
mini_debug_options.handle_sigint = TRUE;
else if (!strcmp (option, "keep-delegates"))
mini_debug_options.keep_delegates = TRUE;
else if (!strcmp (option, "reverse-pinvoke-exceptions"))
mini_debug_options.reverse_pinvoke_exceptions = TRUE;
else if (!strcmp (option, "collect-pagefault-stats"))
mini_debug_options.collect_pagefault_stats = TRUE;
else if (!strcmp (option, "break-on-unverified"))
mini_debug_options.break_on_unverified = TRUE;
else if (!strcmp (option, "no-gdb-backtrace"))
mini_debug_options.no_gdb_backtrace = TRUE;
else if (!strcmp (option, "suspend-on-native-crash") || !strcmp (option, "suspend-on-sigsegv"))
mini_debug_options.suspend_on_native_crash = TRUE;
else if (!strcmp (option, "suspend-on-exception"))
mini_debug_options.suspend_on_exception = TRUE;
else if (!strcmp (option, "suspend-on-unhandled"))
mini_debug_options.suspend_on_unhandled = TRUE;
else if (!strcmp (option, "dont-free-domains"))
mono_dont_free_domains = TRUE;
else if (!strcmp (option, "dyn-runtime-invoke"))
mini_debug_options.dyn_runtime_invoke = TRUE;
else if (!strcmp (option, "gdb"))
fprintf (stderr, "MONO_DEBUG=gdb is deprecated.");
else if (!strcmp (option, "lldb"))
mini_debug_options.lldb = TRUE;
else if (!strcmp (option, "llvm-disable-inlining"))
mini_debug_options.llvm_disable_inlining = TRUE;
else if (!strcmp (option, "llvm-disable-implicit-null-checks"))
mini_debug_options.llvm_disable_implicit_null_checks = TRUE;
else if (!strcmp (option, "explicit-null-checks"))
mini_debug_options.explicit_null_checks = TRUE;
else if (!strcmp (option, "gen-seq-points"))
mini_debug_options.gen_sdb_seq_points = TRUE;
else if (!strcmp (option, "gen-compact-seq-points"))
fprintf (stderr, "Mono Warning: option gen-compact-seq-points is deprecated.\n");
else if (!strcmp (option, "no-compact-seq-points"))
mini_debug_options.no_seq_points_compact_data = TRUE;
else if (!strcmp (option, "single-imm-size"))
mini_debug_options.single_imm_size = TRUE;
else if (!strcmp (option, "init-stacks"))
mini_debug_options.init_stacks = TRUE;
else if (!strcmp (option, "casts"))
mini_debug_options.better_cast_details = TRUE;
else if (!strcmp (option, "soft-breakpoints"))
mini_debug_options.soft_breakpoints = TRUE;
else if (!strcmp (option, "check-pinvoke-callconv"))
mini_debug_options.check_pinvoke_callconv = TRUE;
else if (!strcmp (option, "use-fallback-tls"))
mini_debug_options.use_fallback_tls = TRUE;
else if (!strcmp (option, "debug-domain-unload"))
g_error ("MONO_DEBUG option debug-domain-unload is deprecated.");
else if (!strcmp (option, "partial-sharing"))
mono_set_partial_sharing_supported (TRUE);
else if (!strcmp (option, "align-small-structs"))
mono_align_small_structs = TRUE;
else if (!strcmp (option, "native-debugger-break"))
mini_debug_options.native_debugger_break = TRUE;
else if (!strcmp (option, "disable_omit_fp"))
mini_debug_options.disable_omit_fp = TRUE;
// This is an internal testing feature.
// Every tail. encountered is required to be optimized.
// It is asserted.
else if (!strcmp (option, "test-tailcall-require"))
mini_debug_options.test_tailcall_require = TRUE;
else if (!strcmp (option, "verbose-gdb"))
mini_debug_options.verbose_gdb = TRUE;
else if (!strcmp (option, "clr-memory-model"))
// FIXME Kill this debug flag
mini_debug_options.weak_memory_model = FALSE;
else if (!strcmp (option, "weak-memory-model"))
mini_debug_options.weak_memory_model = TRUE;
else if (!strcmp (option, "top-runtime-invoke-unhandled"))
mini_debug_options.top_runtime_invoke_unhandled = TRUE;
else if (!strncmp (option, "thread-dump-dir=", 16))
mono_set_thread_dump_dir(g_strdup(option + 16));
else if (!strncmp (option, "aot-skip=", 9)) {
mini_debug_options.aot_skip_set = TRUE;
mini_debug_options.aot_skip = atoi (option + 9);
} else
return FALSE;
return TRUE;
}
static void
mini_parse_debug_options (void)
{
char *options = g_getenv ("MONO_DEBUG");
gchar **args, **ptr;
if (!options)
return;
args = g_strsplit (options, ",", -1);
g_free (options);
for (ptr = args; ptr && *ptr; ptr++) {
const char *arg = *ptr;
if (!mini_parse_debug_option (arg)) {
fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
// test-tailcall-require is also accepted but not documented.
// empty string is also accepted and ignored as a consequence
// of appending ",foo" without checking for empty.
fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'suspend-on-native-crash', 'suspend-on-sigsegv', 'suspend-on-exception', 'suspend-on-unhandled', 'dont-free-domains', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'gen-seq-points', 'no-compact-seq-points', 'single-imm-size', 'init-stacks', 'casts', 'soft-breakpoints', 'check-pinvoke-callconv', 'use-fallback-tls', 'debug-domain-unload', 'partial-sharing', 'align-small-structs', 'native-debugger-break', 'thread-dump-dir=DIR', 'no-verbose-gdb', 'llvm_disable_inlining', 'llvm-disable-self-init', 'llvm-disable-implicit-null-checks', 'weak-memory-model'.\n");
exit (1);
}
}
g_strfreev (args);
}
MonoDebugOptions *
mini_get_debug_options (void)
{
return &mini_debug_options;
}
static gpointer
mini_create_ftnptr (gpointer addr)
{
#if defined(PPC_USES_FUNCTION_DESCRIPTOR)
gpointer* desc = NULL;
static GHashTable *ftnptrs_hash;
if (!ftnptrs_hash) {
GHashTable *hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_memory_barrier ();
ftnptrs_hash = hash;
}
// FIXME:
MonoJitMemoryManager *jit_mm = get_default_jit_mm ();
mono_jit_lock ();
desc = (gpointer*)g_hash_table_lookup (ftnptrs_hash, addr);
mono_jit_unlock ();
if (desc)
return desc;
#if defined(__mono_ppc64__)
desc = mono_mem_manager_alloc0 (jit_mm->mem_manager, 3 * sizeof (gpointer));
desc [0] = addr;
desc [1] = NULL;
desc [2] = NULL;
# endif
mono_jit_lock ();
g_hash_table_insert (ftnptrs_hash, addr, desc);
mono_jit_unlock ();
return desc;
#else
return addr;
#endif
}
static gpointer
mini_get_addr_from_ftnptr (gpointer descr)
{
#if defined(PPC_USES_FUNCTION_DESCRIPTOR)
return *(gpointer*)descr;
#else
return descr;
#endif
}
static void
register_counters (void)
{
mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_compiled);
mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
mono_counters_register ("Methods from AOT+LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot_llvm);
mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
mono_counters_register ("Methods using the interpreter", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_interp);
}
static void runtime_invoke_info_free (gpointer value);
static gint
class_method_pair_equal (gconstpointer ka, gconstpointer kb)
{
const MonoClassMethodPair *apair = (const MonoClassMethodPair *)ka;
const MonoClassMethodPair *bpair = (const MonoClassMethodPair *)kb;
return apair->klass == bpair->klass && apair->method == bpair->method ? 1 : 0;
}
static guint
class_method_pair_hash (gconstpointer data)
{
const MonoClassMethodPair *pair = (const MonoClassMethodPair *)data;
return (gsize)pair->klass ^ (gsize)pair->method;
}
static void
init_jit_mem_manager (MonoMemoryManager *mem_manager)
{
MonoJitMemoryManager *info = g_new0 (MonoJitMemoryManager, 1);
info->mem_manager = mem_manager;
info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
info->jump_target_hash = g_hash_table_new (NULL, NULL);
info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
info->delegate_trampoline_hash = g_hash_table_new (class_method_pair_hash, class_method_pair_equal);
info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, mono_seq_point_info_free);
info->runtime_invoke_hash = mono_conc_hashtable_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_jit_code_hash_init (&info->jit_code_hash);
mono_jit_code_hash_init (&info->interp_code_hash);
mono_os_mutex_init_recursive (&info->jit_code_hash_lock);
mem_manager->runtime_info = info;
}
static void
delete_jump_list (gpointer key, gpointer value, gpointer user_data)
{
MonoJumpList *jlist = (MonoJumpList *)value;
g_slist_free ((GSList*)jlist->list);
}
static void
delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
{
GSList *list = (GSList *)value;
g_slist_free (list);
}
static void
dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
{
MonoJitDynamicMethodInfo *di = (MonoJitDynamicMethodInfo *)value;
mono_code_manager_destroy (di->code_mp);
g_free (di);
}
static void
runtime_invoke_info_free (gpointer value)
{
RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
if (info->dyn_call_info)
mono_arch_dyn_call_free (info->dyn_call_info);
#endif
g_free (info);
}
static void
free_jit_callee_list (gpointer key, gpointer value, gpointer user_data)
{
g_slist_free ((GSList*)value);
}
static void
free_jit_mem_manager (MonoMemoryManager *mem_manager)
{
MonoJitMemoryManager *info = (MonoJitMemoryManager*)mem_manager->runtime_info;
g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
g_hash_table_destroy (info->jump_target_hash);
if (info->jump_target_got_slot_hash) {
g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
g_hash_table_destroy (info->jump_target_got_slot_hash);
}
if (info->dynamic_code_hash) {
g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
g_hash_table_destroy (info->dynamic_code_hash);
}
g_hash_table_destroy (info->method_code_hash);
g_hash_table_destroy (info->jump_trampoline_hash);
g_hash_table_destroy (info->jit_trampoline_hash);
g_hash_table_destroy (info->delegate_trampoline_hash);
g_hash_table_destroy (info->static_rgctx_trampoline_hash);
g_hash_table_destroy (info->mrgctx_hash);
g_hash_table_destroy (info->method_rgctx_hash);
g_hash_table_destroy (info->interp_method_pointer_hash);
mono_conc_hashtable_destroy (info->runtime_invoke_hash);
g_hash_table_destroy (info->seq_points);
g_hash_table_destroy (info->arch_seq_points);
if (info->agent_info)
mono_component_debugger ()->free_mem_manager (info);
g_hash_table_destroy (info->gsharedvt_arg_tramp_hash);
if (info->llvm_jit_callees) {
g_hash_table_foreach (info->llvm_jit_callees, free_jit_callee_list, NULL);
g_hash_table_destroy (info->llvm_jit_callees);
}
mono_internal_hash_table_destroy (&info->interp_code_hash);
#ifdef ENABLE_LLVM
mono_llvm_free_mem_manager (info);
#endif
g_free (info);
mem_manager->runtime_info = NULL;
}
#ifdef ENABLE_LLVM
static gboolean
llvm_init_inner (void)
{
mono_llvm_init (!mono_compile_aot);
return TRUE;
}
#endif
/*
* mini_llvm_init:
*
* Load and initialize LLVM support.
* Return TRUE on success.
*/
gboolean
mini_llvm_init (void)
{
#ifdef ENABLE_LLVM
static gboolean llvm_inited;
static gboolean init_result;
mono_loader_lock_if_inited ();
if (!llvm_inited) {
init_result = llvm_init_inner ();
llvm_inited = TRUE;
}
mono_loader_unlock_if_inited ();
return init_result;
#else
return FALSE;
#endif
}
void
mini_add_profiler_argument (const char *desc)
{
if (!profile_options)
profile_options = g_ptr_array_new ();
g_ptr_array_add (profile_options, (gpointer) g_strdup (desc));
}
const MonoEECallbacks *mono_interp_callbacks_pointer;
void
mini_install_interp_callbacks (const MonoEECallbacks *cbs)
{
mono_interp_callbacks_pointer = cbs;
}
int
mono_ee_api_version (void)
{
return MONO_EE_API_VERSION;
}
void
mono_interp_entry_from_trampoline (gpointer ccontext, gpointer imethod)
{
mini_get_interp_callbacks ()->entry_from_trampoline (ccontext, imethod);
}
void
mono_interp_to_native_trampoline (gpointer addr, gpointer ccontext)
{
mini_get_interp_callbacks ()->to_native_trampoline (addr, ccontext);
}
static gboolean
mini_is_interpreter_enabled (void)
{
return mono_use_interpreter;
}
static const char*
mono_get_runtime_build_version (void);
MonoDomain *
mini_init (const char *filename, const char *runtime_version)
{
ERROR_DECL (error);
MonoDomain *domain;
MonoRuntimeCallbacks callbacks;
static const MonoThreadInfoRuntimeCallbacks ticallbacks = {
MONO_THREAD_INFO_RUNTIME_CALLBACKS (MONO_INIT_CALLBACK, mono)
};
mono_component_event_pipe_100ns_ticks_start ();
MONO_VES_INIT_BEGIN ();
CHECKED_MONO_INIT ();
#if defined(__linux__)
if (access ("/proc/self/maps", F_OK) != 0) {
g_print ("Mono requires /proc to be mounted.\n");
exit (1);
}
#endif
mono_interp_stub_init ();
#ifndef DISABLE_INTERPRETER
if (mono_use_interpreter)
mono_ee_interp_init (mono_interp_opts_string);
#endif
mono_components_init ();
mono_component_debugger ()->parse_options (mono_debugger_agent_get_sdb_options ());
mono_os_mutex_init_recursive (&jit_mutex);
mono_cross_helpers_run ();
mono_counters_init ();
mini_jit_init ();
mini_jit_init_job_control ();
/* Happens when using the embedding interface */
if (!default_opt_set)
default_opt = mono_parse_default_optimizations (NULL);
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
if (mono_aot_only)
mono_set_generic_sharing_vt_supported (TRUE);
#else
if (mono_llvm_only)
mono_set_generic_sharing_vt_supported (TRUE);
#endif
mono_tls_init_runtime_keys ();
if (!global_codeman) {
if (!mono_compile_aot)
global_codeman = mono_code_manager_new ();
else
global_codeman = mono_code_manager_new_aot ();
}
memset (&callbacks, 0, sizeof (callbacks));
callbacks.create_ftnptr = mini_create_ftnptr;
callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
callbacks.get_runtime_build_info = mono_get_runtime_build_info;
callbacks.get_runtime_build_version = mono_get_runtime_build_version;
callbacks.set_cast_details = mono_set_cast_details;
callbacks.debug_log = mono_component_debugger ()->debug_log;
callbacks.debug_log_is_enabled = mono_component_debugger ()->debug_log_is_enabled;
callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
callbacks.get_imt_trampoline = mini_get_imt_trampoline;
callbacks.imt_entry_inited = mini_imt_entry_inited;
callbacks.init_delegate = mini_init_delegate;
#define JIT_INVOKE_WORKS
#ifdef JIT_INVOKE_WORKS
callbacks.runtime_invoke = mono_jit_runtime_invoke;
#endif
#define JIT_TRAMPOLINES_WORK
#ifdef JIT_TRAMPOLINES_WORK
callbacks.compile_method = mono_jit_compile_method;
callbacks.create_jit_trampoline = mono_create_jit_trampoline;
callbacks.create_delegate_trampoline = mono_create_delegate_trampoline;
callbacks.free_method = mono_jit_free_method;
callbacks.get_ftnptr = get_ftnptr_for_method;
#endif
callbacks.is_interpreter_enabled = mini_is_interpreter_enabled;
#if ENABLE_WEAK_ATTR
callbacks.get_weak_field_indexes = mono_aot_get_weak_field_indexes;
#endif
callbacks.metadata_update_published = mini_invalidate_transformed_interp_methods;
callbacks.interp_jit_info_foreach = mini_interp_jit_info_foreach;
callbacks.interp_sufficient_stack = mini_interp_sufficient_stack;
callbacks.init_mem_manager = init_jit_mem_manager;
callbacks.free_mem_manager = free_jit_mem_manager;
callbacks.get_jit_stats = get_jit_stats;
callbacks.get_exception_stats = get_exception_stats;
mono_install_callbacks (&callbacks);
#ifndef HOST_WIN32
mono_w32handle_init ();
#endif
mono_thread_info_runtime_init (&ticallbacks);
if (g_hasenv ("MONO_DEBUG")) {
mini_parse_debug_options ();
}
mono_code_manager_init (mono_compile_aot);
#ifdef MONO_ARCH_HAVE_CODE_CHUNK_TRACKING
static const MonoCodeManagerCallbacks code_manager_callbacks = {
#undef MONO_CODE_MANAGER_CALLBACK
#define MONO_CODE_MANAGER_CALLBACK(ret, name, sig) mono_arch_code_ ## name,
MONO_CODE_MANAGER_CALLBACKS
};
mono_code_manager_install_callbacks (&code_manager_callbacks);
#endif
mono_hwcap_init ();
mono_arch_cpu_init ();
mono_arch_init ();
mono_unwind_init ();
if (mini_debug_options.lldb || g_hasenv ("MONO_LLDB")) {
mono_lldb_init ("");
mono_dont_free_domains = TRUE;
}
#ifdef ENABLE_LLVM
if (mono_use_llvm)
mono_llvm_init (!mono_compile_aot);
#endif
mono_trampolines_init ();
if (default_opt & MONO_OPT_AOT)
mono_aot_init ();
mono_component_debugger ()->init ();
#ifdef MONO_ARCH_GSHARED_SUPPORTED
mono_set_generic_sharing_supported (TRUE);
#endif
mono_thread_info_signals_init ();
mono_init_native_crash_info ();
#ifndef MONO_CROSS_COMPILE
mono_runtime_install_handlers ();
#endif
mono_threads_install_cleanup (mini_thread_cleanup);
mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
mono_install_get_class_from_name (mono_aot_get_class_from_name);
mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
mono_profiler_state.context_enable = mini_profiler_context_enable;
mono_profiler_state.context_get_this = mini_profiler_context_get_this;
mono_profiler_state.context_get_argument = mini_profiler_context_get_argument;
mono_profiler_state.context_get_local = mini_profiler_context_get_local;
mono_profiler_state.context_get_result = mini_profiler_context_get_result;
mono_profiler_state.context_free_buffer = mini_profiler_context_free_buffer;
if (g_hasenv ("MONO_PROFILE")) {
gchar *profile_env = g_getenv ("MONO_PROFILE");
mini_add_profiler_argument (profile_env);
g_free (profile_env);
}
if (profile_options)
for (guint i = 0; i < profile_options->len; i++)
mono_profiler_load ((const char *) g_ptr_array_index (profile_options, i));
mono_profiler_started ();
if (mini_debug_options.collect_pagefault_stats)
mono_aot_set_make_unreadable (TRUE);
/* set no-exec before the default ALC is created */
if (mono_compile_aot) {
/*
* Avoid running managed code when AOT compiling, since the platform
* might only support aot-only execution.
*/
mono_runtime_set_no_exec (TRUE);
}
if (runtime_version)
domain = mono_init_version (filename, runtime_version);
else
domain = mono_init_from_assembly (filename, filename);
if (mono_compile_aot)
mono_component_diagnostics_server ()->disable ();
mono_component_event_pipe ()->init ();
// EventPipe up is now up and running, convert 100ns ticks since runtime init into EventPipe compatbile timestamp (using negative delta to represent timestamp in past).
// Add RuntimeInit execution checkpoint using converted timestamp.
mono_component_event_pipe ()->add_rundown_execution_checkpoint_2 ("RuntimeInit", mono_component_event_pipe ()->convert_100ns_ticks_to_timestamp_t (-mono_component_event_pipe_100ns_ticks_stop ()));
if (mono_aot_only) {
/* This helps catch code allocation requests */
mono_code_manager_set_read_only (mono_mem_manager_get_ambient ()->code_mp);
mono_marshal_use_aot_wrappers (TRUE);
}
if (mono_llvm_only) {
mono_install_imt_trampoline_builder (mini_llvmonly_get_imt_trampoline);
mono_set_always_build_imt_trampolines (TRUE);
} else if (mono_aot_only) {
mono_install_imt_trampoline_builder (mono_aot_get_imt_trampoline);
} else {
mono_install_imt_trampoline_builder (mono_arch_build_imt_trampoline);
}
/*Init arch tls information only after the metadata side is inited to make sure we see dynamic appdomain tls keys*/
mono_arch_finish_init ();
/* This must come after mono_init () in the aot-only case */
mono_exceptions_init ();
/* This should come after mono_init () too */
mini_gc_init ();
mono_create_icall_signatures ();
register_counters ();
#define JIT_CALLS_WORK
#ifdef JIT_CALLS_WORK
/* Needs to be called here since register_jit_icall depends on it */
mono_marshal_init ();
mono_arch_register_lowlevel_calls ();
register_icalls ();
mono_generic_sharing_init ();
#endif
#ifdef MONO_ARCH_SIMD_INTRINSICS
mono_simd_intrinsics_init ();
#endif
register_trampolines (domain);
mono_mem_account_register_counters ();
#define JIT_RUNTIME_WORKS
#ifdef JIT_RUNTIME_WORKS
mono_install_runtime_cleanup (runtime_cleanup);
mono_runtime_init_checked (domain, (MonoThreadStartCB)mono_thread_start_cb, mono_thread_attach_cb, error);
mono_error_assert_ok (error);
mono_thread_internal_attach (domain);
MONO_PROFILER_RAISE (thread_name, (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ()), "Main"));
#endif
mono_threads_set_runtime_startup_finished ();
mono_component_event_pipe ()->finish_init ();
#ifdef ENABLE_EXPERIMENT_TIERED
if (!mono_compile_aot) {
/* create compilation thread in background */
mini_tiered_init ();
}
#endif
if (mono_profiler_sampling_enabled ())
mono_runtime_setup_stat_profiler ();
MONO_PROFILER_RAISE (runtime_initialized, ());
MONO_VES_INIT_END ();
return domain;
}
static void
register_icalls (void)
{
mono_add_internal_call_internal ("System.Diagnostics.StackFrame::get_frame_info",
ves_icall_get_frame_info);
mono_add_internal_call_internal ("System.Diagnostics.StackTrace::get_trace",
ves_icall_get_trace);
mono_add_internal_call_internal ("Mono.Runtime::mono_runtime_install_handlers",
mono_runtime_install_handlers);
/*
* It's important that we pass `TRUE` as the last argument here, as
* it causes the JIT to omit a wrapper for these icalls. If the JIT
* *did* emit a wrapper, we'd be looking at infinite recursion since
* the wrapper would call the icall which would call the wrapper and
* so on.
*/
register_icall (mono_profiler_raise_method_enter, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_method_leave, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_method_tail_call, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mono_profiler_raise_exception_clause, mono_icall_sig_void_ptr_int_int_object, TRUE);
register_icall (mono_trace_enter_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_trace_leave_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_trace_tail_method, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
g_assert (mono_get_lmf_addr == mono_tls_get_lmf_addr);
register_icall (mono_domain_get, mono_icall_sig_ptr, TRUE);
register_icall (mini_llvmonly_throw_exception, mono_icall_sig_void_object, TRUE);
register_icall (mini_llvmonly_rethrow_exception, mono_icall_sig_void_object, TRUE);
register_icall (mini_llvmonly_throw_corlib_exception, mono_icall_sig_void_int, TRUE);
register_icall (mini_llvmonly_resume_exception, mono_icall_sig_void, TRUE);
register_icall (mini_llvmonly_resume_exception_il_state, mono_icall_sig_void_ptr_ptr, TRUE);
register_icall (mini_llvmonly_load_exception, mono_icall_sig_object, TRUE);
register_icall (mini_llvmonly_clear_exception, NULL, TRUE);
register_icall (mini_llvmonly_match_exception, mono_icall_sig_int_ptr_int_int_ptr_object, TRUE);
#if defined(ENABLE_LLVM) && defined(HAVE_UNWIND_H)
register_icall (mono_llvm_set_unhandled_exception_handler, NULL, TRUE);
// FIXME: This is broken
#ifndef TARGET_WASM
register_icall (mono_debug_personality, mono_icall_sig_int_int_int_ptr_ptr_ptr, TRUE);
#endif
#endif
if (!mono_llvm_only) {
register_dyn_icall (mono_get_throw_exception (), mono_arch_throw_exception, mono_icall_sig_void_object, TRUE);
register_dyn_icall (mono_get_rethrow_exception (), mono_arch_rethrow_exception, mono_icall_sig_void_object, TRUE);
register_dyn_icall (mono_get_throw_corlib_exception (), mono_arch_throw_corlib_exception, mono_icall_sig_void_ptr, TRUE);
}
register_icall (mono_thread_get_undeniable_exception, mono_icall_sig_object, FALSE);
register_icall (ves_icall_thread_finish_async_abort, mono_icall_sig_void, FALSE);
register_icall (mono_thread_interruption_checkpoint, mono_icall_sig_object, FALSE);
register_icall (mono_thread_force_interruption_checkpoint_noraise, mono_icall_sig_object, FALSE);
register_icall (mono_threads_state_poll, mono_icall_sig_void, FALSE);
#ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
register_opcode_emulation (OP_LMUL, __emul_lmul, mono_icall_sig_long_long_long, mono_llmult, FALSE);
register_opcode_emulation (OP_LDIV, __emul_ldiv, mono_icall_sig_long_long_long, mono_lldiv, FALSE);
register_opcode_emulation (OP_LDIV_UN, __emul_ldiv_un, mono_icall_sig_long_long_long, mono_lldiv_un, FALSE);
register_opcode_emulation (OP_LREM, __emul_lrem, mono_icall_sig_long_long_long, mono_llrem, FALSE);
register_opcode_emulation (OP_LREM_UN, __emul_lrem_un, mono_icall_sig_long_long_long, mono_llrem_un, FALSE);
#endif
#if !defined(MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS) || defined(MONO_ARCH_EMULATE_LONG_MUL_OVF_OPTS)
register_opcode_emulation (OP_LMUL_OVF_UN, __emul_lmul_ovf_un, mono_icall_sig_long_long_long, mono_llmult_ovf_un, FALSE);
register_opcode_emulation (OP_LMUL_OVF, __emul_lmul_ovf, mono_icall_sig_long_long_long, mono_llmult_ovf, FALSE);
register_opcode_emulation (OP_LMUL_OVF_UN_OOM, __emul_lmul_ovf_un_oom, mono_icall_sig_long_long_long, mono_llmult_ovf_un_oom, FALSE);
#endif
#ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
register_opcode_emulation (OP_LSHL, __emul_lshl, mono_icall_sig_long_long_int32, mono_lshl, TRUE);
register_opcode_emulation (OP_LSHR, __emul_lshr, mono_icall_sig_long_long_int32, mono_lshr, TRUE);
register_opcode_emulation (OP_LSHR_UN, __emul_lshr_un, mono_icall_sig_long_long_int32, mono_lshr_un, TRUE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
register_opcode_emulation (OP_IDIV, __emul_op_idiv, mono_icall_sig_int32_int32_int32, mono_idiv, FALSE);
register_opcode_emulation (OP_IDIV_UN, __emul_op_idiv_un, mono_icall_sig_int32_int32_int32, mono_idiv_un, FALSE);
register_opcode_emulation (OP_IREM, __emul_op_irem, mono_icall_sig_int32_int32_int32, mono_irem, FALSE);
register_opcode_emulation (OP_IREM_UN, __emul_op_irem_un, mono_icall_sig_int32_int32_int32, mono_irem_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_MUL_DIV
register_opcode_emulation (OP_IMUL, __emul_op_imul, mono_icall_sig_int32_int32_int32, mono_imul, TRUE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
register_opcode_emulation (OP_IMUL_OVF, __emul_op_imul_ovf, mono_icall_sig_int32_int32_int32, mono_imul_ovf, FALSE);
register_opcode_emulation (OP_IMUL_OVF_UN, __emul_op_imul_ovf_un, mono_icall_sig_int32_int32_int32, mono_imul_ovf_un, FALSE);
register_opcode_emulation (OP_IMUL_OVF_UN_OOM, __emul_op_imul_ovf_un_oom, mono_icall_sig_int32_int32_int32, mono_imul_ovf_un_oom, FALSE);
#endif
#if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT_FALLBACK)
register_opcode_emulation (OP_FDIV, __emul_fdiv, mono_icall_sig_double_double_double, mono_fdiv, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FCONV_TO_U8
register_opcode_emulation (OP_FCONV_TO_U8, __emul_fconv_to_u8, mono_icall_sig_ulong_double, mono_fconv_u8, FALSE);
register_opcode_emulation (OP_RCONV_TO_U8, __emul_rconv_to_u8, mono_icall_sig_ulong_float, mono_rconv_u8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FCONV_TO_U4
register_opcode_emulation (OP_FCONV_TO_U4, __emul_fconv_to_u4, mono_icall_sig_uint32_double, mono_fconv_u4, FALSE);
register_opcode_emulation (OP_RCONV_TO_U4, __emul_rconv_to_u4, mono_icall_sig_uint32_float, mono_rconv_u4, FALSE);
#endif
register_opcode_emulation (OP_FCONV_TO_OVF_I8, __emul_fconv_to_ovf_i8, mono_icall_sig_long_double, mono_fconv_ovf_i8, FALSE);
register_opcode_emulation (OP_FCONV_TO_OVF_U8, __emul_fconv_to_ovf_u8, mono_icall_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
register_opcode_emulation (OP_RCONV_TO_OVF_I8, __emul_rconv_to_ovf_i8, mono_icall_sig_long_float, mono_rconv_ovf_i8, FALSE);
register_opcode_emulation (OP_RCONV_TO_OVF_U8, __emul_rconv_to_ovf_u8, mono_icall_sig_ulong_float, mono_rconv_ovf_u8, FALSE);
#ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
register_opcode_emulation (OP_FCONV_TO_I8, __emul_fconv_to_i8, mono_icall_sig_long_double, mono_fconv_i8, FALSE);
register_opcode_emulation (OP_RCONV_TO_I8, __emul_rconv_to_i8, mono_icall_sig_long_float, mono_rconv_i8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_CONV_R8_UN
register_opcode_emulation (OP_ICONV_TO_R_UN, __emul_iconv_to_r_un, mono_icall_sig_double_int32, mono_conv_to_r8_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
register_opcode_emulation (OP_LCONV_TO_R8, __emul_lconv_to_r8, mono_icall_sig_double_long, mono_lconv_to_r8, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
register_opcode_emulation (OP_LCONV_TO_R4, __emul_lconv_to_r4, mono_icall_sig_float_long, mono_lconv_to_r4, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
register_opcode_emulation (OP_LCONV_TO_R_UN, __emul_lconv_to_r8_un, mono_icall_sig_double_long, mono_lconv_to_r8_un, FALSE);
#endif
#ifdef MONO_ARCH_EMULATE_FREM
register_opcode_emulation (OP_FREM, __emul_frem, mono_icall_sig_double_double_double, mono_fmod, FALSE);
register_opcode_emulation (OP_RREM, __emul_rrem, mono_icall_sig_float_float_float, fmodf, FALSE);
#endif
#ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
if (mono_arch_is_soft_float ()) {
register_opcode_emulation (OP_FSUB, __emul_fsub, mono_icall_sig_double_double_double, mono_fsub, FALSE);
register_opcode_emulation (OP_FADD, __emul_fadd, mono_icall_sig_double_double_double, mono_fadd, FALSE);
register_opcode_emulation (OP_FMUL, __emul_fmul, mono_icall_sig_double_double_double, mono_fmul, FALSE);
register_opcode_emulation (OP_FNEG, __emul_fneg, mono_icall_sig_double_double, mono_fneg, FALSE);
register_opcode_emulation (OP_ICONV_TO_R8, __emul_iconv_to_r8, mono_icall_sig_double_int32, mono_conv_to_r8, FALSE);
register_opcode_emulation (OP_ICONV_TO_R4, __emul_iconv_to_r4, mono_icall_sig_double_int32, mono_conv_to_r4, FALSE);
register_opcode_emulation (OP_FCONV_TO_R4, __emul_fconv_to_r4, mono_icall_sig_double_double, mono_fconv_r4, FALSE);
register_opcode_emulation (OP_FCONV_TO_I1, __emul_fconv_to_i1, mono_icall_sig_int8_double, mono_fconv_i1, FALSE);
register_opcode_emulation (OP_FCONV_TO_I2, __emul_fconv_to_i2, mono_icall_sig_int16_double, mono_fconv_i2, FALSE);
register_opcode_emulation (OP_FCONV_TO_I4, __emul_fconv_to_i4, mono_icall_sig_int32_double, mono_fconv_i4, FALSE);
register_opcode_emulation (OP_FCONV_TO_U1, __emul_fconv_to_u1, mono_icall_sig_uint8_double, mono_fconv_u1, FALSE);
register_opcode_emulation (OP_FCONV_TO_U2, __emul_fconv_to_u2, mono_icall_sig_uint16_double, mono_fconv_u2, FALSE);
#if TARGET_SIZEOF_VOID_P == 4
register_opcode_emulation (OP_FCONV_TO_I, __emul_fconv_to_i, mono_icall_sig_int32_double, mono_fconv_i4, FALSE);
#endif
register_opcode_emulation (OP_FBEQ, __emul_fcmp_eq, mono_icall_sig_uint32_double_double, mono_fcmp_eq, FALSE);
register_opcode_emulation (OP_FBLT, __emul_fcmp_lt, mono_icall_sig_uint32_double_double, mono_fcmp_lt, FALSE);
register_opcode_emulation (OP_FBGT, __emul_fcmp_gt, mono_icall_sig_uint32_double_double, mono_fcmp_gt, FALSE);
register_opcode_emulation (OP_FBLE, __emul_fcmp_le, mono_icall_sig_uint32_double_double, mono_fcmp_le, FALSE);
register_opcode_emulation (OP_FBGE, __emul_fcmp_ge, mono_icall_sig_uint32_double_double, mono_fcmp_ge, FALSE);
register_opcode_emulation (OP_FBNE_UN, __emul_fcmp_ne_un, mono_icall_sig_uint32_double_double, mono_fcmp_ne_un, FALSE);
register_opcode_emulation (OP_FBLT_UN, __emul_fcmp_lt_un, mono_icall_sig_uint32_double_double, mono_fcmp_lt_un, FALSE);
register_opcode_emulation (OP_FBGT_UN, __emul_fcmp_gt_un, mono_icall_sig_uint32_double_double, mono_fcmp_gt_un, FALSE);
register_opcode_emulation (OP_FBLE_UN, __emul_fcmp_le_un, mono_icall_sig_uint32_double_double, mono_fcmp_le_un, FALSE);
register_opcode_emulation (OP_FBGE_UN, __emul_fcmp_ge_un, mono_icall_sig_uint32_double_double, mono_fcmp_ge_un, FALSE);
register_opcode_emulation (OP_FCEQ, __emul_fcmp_ceq, mono_icall_sig_uint32_double_double, mono_fceq, FALSE);
register_opcode_emulation (OP_FCGT, __emul_fcmp_cgt, mono_icall_sig_uint32_double_double, mono_fcgt, FALSE);
register_opcode_emulation (OP_FCGT_UN, __emul_fcmp_cgt_un, mono_icall_sig_uint32_double_double, mono_fcgt_un, FALSE);
register_opcode_emulation (OP_FCLT, __emul_fcmp_clt, mono_icall_sig_uint32_double_double, mono_fclt, FALSE);
register_opcode_emulation (OP_FCLT_UN, __emul_fcmp_clt_un, mono_icall_sig_uint32_double_double, mono_fclt_un, FALSE);
register_icall (mono_fload_r4, mono_icall_sig_double_ptr, FALSE);
register_icall (mono_fstore_r4, mono_icall_sig_void_double_ptr, FALSE);
register_icall (mono_fload_r4_arg, mono_icall_sig_uint32_double, FALSE);
register_icall (mono_isfinite_double, mono_icall_sig_int32_double, FALSE);
}
#endif
register_icall (mono_ckfinite, mono_icall_sig_double_double, FALSE);
#ifdef COMPRESSED_INTERFACE_BITMAP
register_icall (mono_class_interface_match, mono_icall_sig_uint32_ptr_int32, TRUE);
#endif
/* other jit icalls */
register_icall (ves_icall_mono_delegate_ctor, mono_icall_sig_void_object_object_ptr, FALSE);
register_icall (ves_icall_mono_delegate_ctor_interp, mono_icall_sig_void_object_object_ptr, FALSE);
register_icall (mono_class_static_field_address,
mono_icall_sig_ptr_ptr, FALSE);
register_icall (mono_ldtoken_wrapper, mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_ldtoken_wrapper_generic_shared,
mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_get_special_static_data, mono_icall_sig_ptr_int, FALSE);
register_icall (mono_helper_stelem_ref_check, mono_icall_sig_void_object_object, FALSE);
register_icall (ves_icall_object_new, mono_icall_sig_object_ptr, FALSE);
register_icall (ves_icall_object_new_specific, mono_icall_sig_object_ptr, FALSE);
register_icall (ves_icall_array_new_specific, mono_icall_sig_object_ptr_int32, FALSE);
register_icall (ves_icall_runtime_class_init, mono_icall_sig_void_ptr, FALSE);
register_icall (mono_ldftn, mono_icall_sig_ptr_ptr, FALSE);
register_icall (mono_ldvirtfn, mono_icall_sig_ptr_object_ptr, FALSE);
register_icall (mono_ldvirtfn_gshared, mono_icall_sig_ptr_object_ptr, FALSE);
register_icall (mono_helper_compile_generic_method, mono_icall_sig_ptr_object_ptr_ptr, FALSE);
register_icall (mono_helper_ldstr, mono_icall_sig_object_ptr_int, FALSE);
register_icall (mono_helper_ldstr_mscorlib, mono_icall_sig_object_int, FALSE);
register_icall (mono_helper_newobj_mscorlib, mono_icall_sig_object_int, FALSE);
register_icall (mono_value_copy_internal, mono_icall_sig_void_ptr_ptr_ptr, FALSE);
register_icall (mono_object_castclass_unbox, mono_icall_sig_object_object_ptr, FALSE);
register_icall (mono_break, NULL, TRUE);
register_icall (mono_create_corlib_exception_0, mono_icall_sig_object_int, TRUE);
register_icall (mono_create_corlib_exception_1, mono_icall_sig_object_int_object, TRUE);
register_icall (mono_create_corlib_exception_2, mono_icall_sig_object_int_object_object, TRUE);
register_icall (mono_array_new_1, mono_icall_sig_object_ptr_int, FALSE);
register_icall (mono_array_new_2, mono_icall_sig_object_ptr_int_int, FALSE);
register_icall (mono_array_new_3, mono_icall_sig_object_ptr_int_int_int, FALSE);
register_icall (mono_array_new_4, mono_icall_sig_object_ptr_int_int_int_int, FALSE);
register_icall (mono_array_new_n_icall, mono_icall_sig_object_ptr_int_ptr, FALSE);
register_icall (mono_get_native_calli_wrapper, mono_icall_sig_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_resume_unwind, mono_icall_sig_void_ptr, TRUE);
register_icall (mono_gsharedvt_constrained_call, mono_icall_sig_object_ptr_ptr_ptr_ptr_ptr, FALSE);
register_icall (mono_gsharedvt_value_copy, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
//WARNING We do runtime selection here but the string *MUST* be to a fallback function that has same signature and behavior
MonoRangeCopyFunction const mono_gc_wbarrier_range_copy = mono_gc_get_range_copy_func ();
register_icall_no_wrapper (mono_gc_wbarrier_range_copy, mono_icall_sig_void_ptr_ptr_int);
register_icall (mono_object_castclass_with_cache, mono_icall_sig_object_object_ptr_ptr, FALSE);
register_icall (mono_object_isinst_with_cache, mono_icall_sig_object_object_ptr_ptr, FALSE);
register_icall (mono_generic_class_init, mono_icall_sig_void_ptr, FALSE);
register_icall (mono_fill_class_rgctx, mono_icall_sig_ptr_ptr_int, FALSE);
register_icall (mono_fill_method_rgctx, mono_icall_sig_ptr_ptr_int, FALSE);
register_dyn_icall (mono_component_debugger ()->user_break, mono_debugger_agent_user_break, mono_icall_sig_void, FALSE);
register_icall (mini_llvm_init_method, mono_icall_sig_void_ptr_ptr_ptr_ptr, TRUE);
register_icall_no_wrapper (mini_llvmonly_resolve_iface_call_gsharedvt, mono_icall_sig_ptr_object_int_ptr_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_vcall_gsharedvt, mono_icall_sig_ptr_object_int_ptr_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_vcall_gsharedvt_fast, mono_icall_sig_ptr_object_int);
register_icall_no_wrapper (mini_llvmonly_resolve_generic_virtual_call, mono_icall_sig_ptr_ptr_int_ptr);
register_icall_no_wrapper (mini_llvmonly_resolve_generic_virtual_iface_call, mono_icall_sig_ptr_ptr_int_ptr);
/* This needs a wrapper so it can have a preserveall cconv */
register_icall (mini_llvmonly_init_vtable_slot, mono_icall_sig_ptr_ptr_int, FALSE);
register_icall (mini_llvmonly_init_delegate, mono_icall_sig_void_object_ptr, TRUE);
register_icall (mini_llvmonly_init_delegate_virtual, mono_icall_sig_void_object_object_ptr, TRUE);
register_icall (mini_llvmonly_throw_nullref_exception, mono_icall_sig_void, TRUE);
register_icall (mini_llvmonly_throw_aot_failed_exception, mono_icall_sig_void_ptr, TRUE);
register_icall (mini_llvmonly_pop_lmf, mono_icall_sig_void_ptr, TRUE);
register_icall (mini_llvmonly_interp_entry_gsharedvt, mono_icall_sig_void_ptr_ptr_ptr, TRUE);
register_icall (mono_get_assembly_object, mono_icall_sig_object_ptr, TRUE);
register_icall (mono_get_method_object, mono_icall_sig_object_ptr, TRUE);
register_icall (mono_throw_method_access, mono_icall_sig_void_ptr_ptr, FALSE);
register_icall (mono_throw_bad_image, mono_icall_sig_void, FALSE);
register_icall (mono_throw_not_supported, mono_icall_sig_void, FALSE);
register_icall (mono_throw_platform_not_supported, mono_icall_sig_void, FALSE);
register_icall (mono_throw_invalid_program, mono_icall_sig_void_ptr, FALSE);
register_icall_no_wrapper (mono_dummy_jit_icall, mono_icall_sig_void);
//register_icall_no_wrapper (mono_dummy_jit_icall_val, mono_icall_sig_void_ptr);
register_icall_with_wrapper (mono_monitor_enter_internal, mono_icall_sig_int32_obj);
register_icall_with_wrapper (mono_monitor_enter_v4_internal, mono_icall_sig_void_obj_ptr);
register_icall_no_wrapper (mono_monitor_enter_fast, mono_icall_sig_int_obj);
register_icall_no_wrapper (mono_monitor_enter_v4_fast, mono_icall_sig_int_obj_ptr);
#ifdef TARGET_IOS
register_icall (pthread_getspecific, mono_icall_sig_ptr_ptr, TRUE);
#endif
/* Register tls icalls */
register_icall_no_wrapper (mono_tls_get_thread_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_jit_tls_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_domain_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_sgen_thread_info_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_tls_get_lmf_addr_extern, mono_icall_sig_ptr);
register_icall_no_wrapper (mono_interp_entry_from_trampoline, mono_icall_sig_void_ptr_ptr);
register_icall_no_wrapper (mono_interp_to_native_trampoline, mono_icall_sig_void_ptr_ptr);
#ifdef MONO_ARCH_HAS_REGISTER_ICALL
mono_arch_register_icall ();
#endif
}
MonoJitStats mono_jit_stats = {0};
/**
* Counters of mono_stats and mono_jit_stats can be read without locking during shutdown.
* For all other contexts, assumes that the domain lock is held.
* MONO_NO_SANITIZE_THREAD tells Clang's ThreadSanitizer to hide all reports of these (known) races.
*/
MONO_NO_SANITIZE_THREAD
void
mono_runtime_print_stats (void)
{
if (mono_jit_stats.enabled) {
g_print ("Mono Jit statistics\n");
g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio / 100.0,
mono_jit_stats.max_ratio_method);
g_print ("Biggest method: %" G_GINT32_FORMAT " (%s)\n", mono_jit_stats.biggest_method_size,
mono_jit_stats.biggest_method);
g_print ("Delegates created: %" G_GINT32_FORMAT "\n", mono_stats.delegate_creations);
g_print ("Initialized classes: %" G_GINT32_FORMAT "\n", mono_stats.initialized_class_count);
g_print ("Used classes: %" G_GINT32_FORMAT "\n", mono_stats.used_class_count);
g_print ("Generic vtables: %" G_GINT32_FORMAT "\n", mono_stats.generic_vtable_count);
g_print ("Methods: %" G_GINT32_FORMAT "\n", mono_stats.method_count);
g_print ("Static data size: %" G_GINT32_FORMAT "\n", mono_stats.class_static_data_size);
g_print ("VTable data size: %" G_GINT32_FORMAT "\n", mono_stats.class_vtable_size);
g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
g_print ("\nInitialized classes: %" G_GINT32_FORMAT "\n", mono_stats.generic_class_count);
g_print ("Inflated types: %" G_GINT32_FORMAT "\n", mono_stats.inflated_type_count);
g_print ("Generics virtual invokes: %" G_GINT32_FORMAT "\n", mono_jit_stats.generic_virtual_invocations);
g_print ("Sharable generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_sharable_methods);
g_print ("Unsharable generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_unsharable_methods);
g_print ("Shared generic methods: %" G_GINT32_FORMAT "\n", mono_stats.generics_shared_methods);
g_print ("Shared vtype generic methods: %" G_GINT32_FORMAT "\n", mono_stats.gsharedvt_methods);
g_print ("IMT tables size: %" G_GINT32_FORMAT "\n", mono_stats.imt_tables_size);
g_print ("IMT number of tables: %" G_GINT32_FORMAT "\n", mono_stats.imt_number_of_tables);
g_print ("IMT number of methods: %" G_GINT32_FORMAT "\n", mono_stats.imt_number_of_methods);
g_print ("IMT used slots: %" G_GINT32_FORMAT "\n", mono_stats.imt_used_slots);
g_print ("IMT colliding slots: %" G_GINT32_FORMAT "\n", mono_stats.imt_slots_with_collisions);
g_print ("IMT max collisions: %" G_GINT32_FORMAT "\n", mono_stats.imt_max_collisions_in_slot);
g_print ("IMT methods at max col: %" G_GINT32_FORMAT "\n", mono_stats.imt_method_count_when_max_collisions);
g_print ("IMT trampolines size: %" G_GINT32_FORMAT "\n", mono_stats.imt_trampolines_size);
g_print ("JIT info table inserts: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_insert_count);
g_print ("JIT info table removes: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_remove_count);
g_print ("JIT info table lookups: %" G_GINT32_FORMAT "\n", mono_stats.jit_info_table_lookup_count);
mono_counters_dump (MONO_COUNTER_SECTION_MASK | MONO_COUNTER_MONOTONIC, NULL);
g_print ("\n");
}
}
static void
jit_stats_cleanup (void)
{
g_free (mono_jit_stats.max_ratio_method);
mono_jit_stats.max_ratio_method = NULL;
g_free (mono_jit_stats.biggest_method);
mono_jit_stats.biggest_method = NULL;
}
static void
runtime_cleanup (MonoDomain *domain, gpointer user_data)
{
mini_cleanup (domain);
}
void
mini_cleanup (MonoDomain *domain)
{
if (mono_stats.enabled)
g_printf ("Printing runtime stats at shutdown\n");
mono_runtime_print_stats ();
jit_stats_cleanup ();
mono_jit_dump_cleanup ();
mini_get_interp_callbacks ()->cleanup ();
mono_component_event_pipe ()->shutdown ();
mono_component_diagnostics_server ()->shutdown ();
}
void
mono_set_defaults (int verbose_level, guint32 opts)
{
mini_verbose = verbose_level;
mono_set_optimizations (opts);
}
void
mono_disable_optimizations (guint32 opts)
{
default_opt &= ~opts;
}
void
mono_set_optimizations (guint32 opts)
{
if (opts & MONO_OPT_AGGRESSIVE_INLINING)
opts |= MONO_OPT_INLINE;
default_opt = opts;
default_opt_set = TRUE;
#ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
mono_set_generic_sharing_vt_supported (mono_aot_only || ((default_opt & MONO_OPT_GSHAREDVT) != 0));
#else
if (mono_llvm_only)
mono_set_generic_sharing_vt_supported (TRUE);
#endif
}
void
mono_set_verbose_level (guint32 level)
{
mini_verbose = level;
}
static const char*
mono_get_runtime_build_version (void)
{
return FULL_VERSION;
}
/**
* mono_get_runtime_build_info:
* The returned string is owned by the caller. The returned string
* format is <code>VERSION (FULL_VERSION BUILD_DATE)</code> and build date is optional.
* \returns the runtime version + build date in string format.
*/
char*
mono_get_runtime_build_info (void)
{
if (mono_build_date)
return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
else
return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
}
static void
mono_precompile_assembly (MonoAssembly *ass, void *user_data)
{
GHashTable *assemblies = (GHashTable*)user_data;
MonoImage *image = mono_assembly_get_image_internal (ass);
MonoMethod *method, *invoke;
int i, count = 0;
if (g_hash_table_lookup (assemblies, ass))
return;
g_hash_table_insert (assemblies, ass, ass);
if (mini_verbose > 0)
printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
ERROR_DECL (error);
method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL, NULL, error);
if (!method) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
continue;
}
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
continue;
if (method->is_generic || mono_class_is_gtd (method->klass))
continue;
count++;
if (mini_verbose > 1) {
char * desc = mono_method_full_name (method, TRUE);
g_print ("Compiling %d %s\n", count, desc);
g_free (desc);
}
mono_compile_method_checked (method, error);
if (!is_ok (error)) {
mono_error_cleanup (error); /* FIXME don't swallow the error */
continue;
}
if (strcmp (method->name, "Finalize") == 0) {
invoke = mono_marshal_get_runtime_invoke (method, FALSE);
mono_compile_method_checked (invoke, error);
mono_error_assert_ok (error);
}
}
/* Load and precompile referenced assemblies as well */
for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
mono_assembly_load_reference (image, i);
if (image->references [i])
mono_precompile_assembly (image->references [i], assemblies);
}
}
void mono_precompile_assemblies ()
{
GHashTable *assemblies = g_hash_table_new (NULL, NULL);
mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
g_hash_table_destroy (assemblies);
}
/*
* Used by LLVM.
* Have to export this for AOT.
*/
void
mono_personality (void)
{
/* Not used */
g_assert_not_reached ();
}
static MonoBreakPolicy
always_insert_breakpoint (MonoMethod *method)
{
return MONO_BREAK_POLICY_ALWAYS;
}
static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
/**
* mono_set_break_policy:
* \param policy_callback the new callback function
*
* Allow embedders to decide whether to actually obey breakpoint instructions
* (both break IL instructions and \c Debugger.Break method calls), for example
* to not allow an app to be aborted by a perfectly valid IL opcode when executing
* untrusted or semi-trusted code.
*
* \p policy_callback will be called every time a break point instruction needs to
* be inserted with the method argument being the method that calls \c Debugger.Break
* or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
* if it wants the breakpoint to not be effective in the given method.
* \c MONO_BREAK_POLICY_ALWAYS is the default.
*/
void
mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
{
if (policy_callback)
break_policy_func = policy_callback;
else
break_policy_func = always_insert_breakpoint;
}
gboolean
mini_should_insert_breakpoint (MonoMethod *method)
{
switch (break_policy_func (method)) {
case MONO_BREAK_POLICY_ALWAYS:
return TRUE;
case MONO_BREAK_POLICY_NEVER:
return FALSE;
case MONO_BREAK_POLICY_ON_DBG:
g_warning ("mdb no longer supported");
return FALSE;
default:
g_warning ("Incorrect value returned from break policy callback");
return FALSE;
}
}
// Custom handlers currently only implemented by Windows.
#ifndef HOST_WIN32
gboolean
mono_runtime_install_custom_handlers (const char *handlers)
{
return FALSE;
}
void
mono_runtime_install_custom_handlers_usage (void)
{
fprintf (stdout,
"Custom Handlers:\n"
" --handlers=HANDLERS Enable handler support, HANDLERS is a comma\n"
" separated list of available handlers to install.\n"
"\n"
"No handlers supported on current platform.\n");
}
#endif /* HOST_WIN32 */
static void
mini_invalidate_transformed_interp_methods (MonoAssemblyLoadContext *alc G_GNUC_UNUSED, uint32_t generation G_GNUC_UNUSED)
{
mini_get_interp_callbacks ()->invalidate_transformed ();
}
static void
mini_interp_jit_info_foreach(InterpJitInfoFunc func, gpointer user_data)
{
mini_get_interp_callbacks ()->jit_info_foreach (func, user_data);
}
static gboolean
mini_interp_sufficient_stack (gsize size)
{
return mini_get_interp_callbacks ()->sufficient_stack (size);
}
/*
* mini_get_default_mem_manager:
*
* Return a memory manager which can be used for default allocation.
* FIXME: Review all callers and change them to allocate from a
* class/method/assembly specific memory manager.
*/
MonoMemoryManager*
mini_get_default_mem_manager (void)
{
return mono_mem_manager_get_ambient ();
}
gpointer
mini_alloc_generic_virtual_trampoline (MonoVTable *vtable, int size)
{
static gboolean inited = FALSE;
static int generic_virtual_trampolines_size = 0;
if (!inited) {
mono_counters_register ("Generic virtual trampoline bytes",
MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &generic_virtual_trampolines_size);
inited = TRUE;
}
generic_virtual_trampolines_size += size;
return mono_mem_manager_code_reserve (m_class_get_mem_manager (vtable->klass), size);
}
MonoException*
mini_get_stack_overflow_ex (void)
{
return mono_get_root_domain ()->stack_overflow_ex;
}
const MonoEECallbacks*
mini_get_interp_callbacks_api (void)
{
return mono_interp_callbacks_pointer;
}
| 1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/mini/mini-riscv.h | /*
* Licensed to the .NET Foundation under one or more agreements.
* The .NET Foundation licenses this file to you under the MIT license.
*/
#ifndef __MONO_MINI_RISCV_H__
#define __MONO_MINI_RISCV_H__
#include <mono/arch/riscv/riscv-codegen.h>
#ifdef TARGET_RISCV64
#define MONO_RISCV_ARCHITECTURE "riscv64"
#else
#define MONO_RISCV_ARCHITECTURE "riscv32"
#endif
#if defined (RISCV_FPABI_SOFT)
#define MONO_ARCH_SOFT_FLOAT_FALLBACK
#define RISCV_FP_MODEL "soft-fp"
#elif defined (RISCV_FPABI_DOUBLE)
#define RISCV_FP_MODEL "double-fp"
#elif defined (RISCV_FPABI_SINGLE)
#define RISCV_FP_MODEL "single-fp"
#error "The single-precision RISC-V hard float ABI is not currently supported."
#else
#error "Unknown RISC-V FPABI. This is probably a bug in configure.ac."
#endif
#define MONO_ARCH_ARCHITECTURE MONO_RISCV_ARCHITECTURE "," RISCV_FP_MODEL
#ifdef TARGET_RISCV64
#define MONO_ARCH_CPU_SPEC mono_riscv64_cpu_desc
#else
#define MONO_ARCH_CPU_SPEC mono_riscv32_cpu_desc
#endif
#define MONO_MAX_IREGS (RISCV_N_GREGS)
#define MONO_MAX_FREGS (RISCV_N_FREGS)
/*
* Register usage conventions:
*
* - a0..a7 and fa0..fa7 are argument/return registers.
* - s0..11 and fs0..fs11 are callee-saved registers.
* - a0..a1 are used as fixed registers (for the 'a' spec, soft float, and
* longs on 32-bit, as appropriate).
* - t0..t1, ra, and ft0..ft2 are used as scratch registers and can't be
* allocated by the register allocator.
* - t2 is used as the RGCTX/IMT register and can't be allocated by the
* register allocator.
* - a0 is used as the VTable register for lazy fetch trampolines.
* - sp, fp, gp, and tp are all reserved by the ABI and can't be allocated by
* the register allocator.
* - x0 is hard-wired to zero and can't be allocated by the register allocator.
*/
#define MONO_ARCH_CALLEE_REGS (0b11110000000000111111110000000000)
#define MONO_ARCH_CALLEE_SAVED_REGS (0b00001111111111000000001100000000)
#ifdef RISCV_FPABI_SOFT
#define MONO_ARCH_CALLEE_FREGS (0b11111111111111111111111111111000)
#define MONO_ARCH_CALLEE_SAVED_FREGS (0b00000000000000000000000000000000)
#else
#define MONO_ARCH_CALLEE_FREGS (0b11110000000000111111110011111000)
#define MONO_ARCH_CALLEE_SAVED_FREGS (0b00001111111111000000001100000000)
#endif
#define MONO_ARCH_INST_SREG2_MASK(ins) \
(0)
#define MONO_ARCH_INST_IS_FLOAT(desc) \
(!mono_arch_is_soft_float () && (desc) == 'f')
#ifdef TARGET_RISCV64
#define MONO_ARCH_INST_FIXED_REG(desc) \
((desc) == 'a' || (mono_arch_is_soft_float () && (desc) == 'f') ? RISCV_A0 : -1)
#define MONO_ARCH_INST_IS_REGPAIR(desc) \
(FALSE)
#define MONO_ARCH_INST_REGPAIR_REG2(desc, hreg1) \
(-1)
#else
#define MONO_ARCH_INST_FIXED_REG(desc) \
((desc) == 'a' || (desc) == 'l' || (mono_arch_is_soft_float () && (desc) == 'f') ? RISCV_A0 : -1)
#define MONO_ARCH_INST_IS_REGPAIR(desc) \
((desc) == 'l' || (mono_arch_is_soft_float () && (desc) == 'f'))
#define MONO_ARCH_INST_REGPAIR_REG2(desc, hreg1) \
(RISCV_A1)
#endif
#define MONO_ARCH_RGCTX_REG (RISCV_T2)
#define MONO_ARCH_IMT_REG (RISCV_T2)
#define MONO_ARCH_VTABLE_REG (RISCV_A0)
#define MONO_ARCH_HAVE_VOLATILE_NON_PARAM_REGISTER 0
#define MONO_ARCH_USE_FPSTACK (FALSE)
#define MONO_ARCH_FRAME_ALIGNMENT (16)
#define MONO_ARCH_CODE_ALIGNMENT (32)
#define MONO_ARCH_EMULATE_MUL_DIV (1)
#define MONO_ARCH_EMULATE_FREM (1)
#ifdef TARGET_RISCV64
#define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS (1)
#endif
#define MONO_ARCH_EMULATE_CONV_R8_UN (1)
#define MONO_ARCH_EMULATE_FCONV_TO_U8 (1)
#define MONO_ARCH_EMULATE_FCONV_TO_U4 (1)
#define MONO_ARCH_EMULATE_FCONV_TO_I8 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R8 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R4 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R8_UN (1)
#define MONO_ARCH_NEED_DIV_CHECK (1)
#define MONO_ARCH_HAVE_OP_TAIL_CALL (1)
#define MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT (1)
#define MONO_ARCH_HAVE_CARD_TABLE_WBARRIER (1)
#define MONO_ARCH_HAVE_GENERALIZED_IMT_TRAMPOLINE (1)
#define MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE (1)
#define MONO_ARCH_HAVE_SDB_TRAMPOLINES (1)
#define MONO_ARCH_HAVE_INTERP_PINVOKE_TRAMP (1)
#define MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES (1)
#define MONO_ARCH_USE_SIGACTION (1)
#define MONO_ARCH_HAVE_CONTEXT_SET_INT_REG (1)
#define MONO_ARCH_HAVE_DECOMPOSE_LONG_OPTS (1)
#define MONO_ARCH_HAVE_DECOMPOSE_OPTS (1)
#define MONO_ARCH_HAVE_EXCEPTIONS_INIT (1)
#define MONO_ARCH_HAVE_GET_TRAMPOLINES (1)
#define MONO_ARCH_HAVE_OPCODE_NEEDS_EMULATION (1)
#define MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK (1)
#define MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX (1)
#define MONO_ARCH_GSHARED_SUPPORTED (1)
#define MONO_ARCH_INTERPRETER_SUPPORTED (1)
//#define MONO_ARCH_AOT_SUPPORTED (1)
//#define MONO_ARCH_LLVM_SUPPORTED (1)
//#define MONO_ARCH_SOFT_DEBUG_SUPPORTED (1)
// #define MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE (1)
// #define MONO_ARCH_HAVE_INTERP_PINVOKE_TRAMP (1)
// #define MONO_ARCH_HAVE_INTERP_NATIVE_TO_MANAGED (1)
typedef struct {
} MonoCompileArch;
#define MONO_CONTEXT_SET_LLVM_EXC_REG(ctx, exc) \
do { \
(ctx)->gregs [RISCV_A0] = (host_mgreg_t) exc; \
} while (0)
#define MONO_INIT_CONTEXT_FROM_FUNC(ctx, func) \
do { \
MONO_CONTEXT_SET_IP ((ctx), (func)); \
MONO_CONTEXT_SET_SP ((ctx), __builtin_frame_address (0)); \
MONO_CONTEXT_SET_BP ((ctx), __builtin_frame_address (0)); \
} while (0)
struct MonoLMF {
// If the second-lowest bit of this field is set, this is a MonoLMFExt.
gpointer previous_lmf;
gpointer lmf_addr;
host_mgreg_t pc;
host_mgreg_t sp;
host_mgreg_t ra;
host_mgreg_t gregs [RISCV_N_GSREGS]; // s0..s11
double fregs [RISCV_N_FSREGS]; // fs0..fs11
};
#define MONO_ARCH_INIT_TOP_LMF_ENTRY(lmf)
typedef struct {
guint8 *stack;
} CallContext;
enum {
MONO_R_RISCV_IMM = 1,
MONO_R_RISCV_B = 2,
MONO_R_RISCV_BEQ = 3,
MONO_R_RISCV_BNE = 4,
MONO_R_RISCV_BLT = 5,
MONO_R_RISCV_BGE = 6,
MONO_R_RISCV_BLTU = 7,
MONO_R_RISCV_BGEU = 8,
};
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_imm (guint8 *code, int rd, gsize imm);
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_load (guint8 *code, int rd, int rs1, gint32 imm);
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_store (guint8 *code, int rs1, int rs2, gint32 imm);
#endif
| /*
* Licensed to the .NET Foundation under one or more agreements.
* The .NET Foundation licenses this file to you under the MIT license.
*/
#ifndef __MONO_MINI_RISCV_H__
#define __MONO_MINI_RISCV_H__
#include <mono/arch/riscv/riscv-codegen.h>
#ifdef TARGET_RISCV64
#define MONO_RISCV_ARCHITECTURE "riscv64"
#else
#define MONO_RISCV_ARCHITECTURE "riscv32"
#endif
#if defined (RISCV_FPABI_SOFT)
#define MONO_ARCH_SOFT_FLOAT_FALLBACK
#define RISCV_FP_MODEL "soft-fp"
#elif defined (RISCV_FPABI_DOUBLE)
#define RISCV_FP_MODEL "double-fp"
#elif defined (RISCV_FPABI_SINGLE)
#define RISCV_FP_MODEL "single-fp"
#error "The single-precision RISC-V hard float ABI is not currently supported."
#else
#error "Unknown RISC-V FPABI. This is probably a bug in configure.ac."
#endif
#define MONO_ARCH_ARCHITECTURE MONO_RISCV_ARCHITECTURE "," RISCV_FP_MODEL
#ifdef TARGET_RISCV64
#define MONO_ARCH_CPU_SPEC mono_riscv64_cpu_desc
#else
#define MONO_ARCH_CPU_SPEC mono_riscv32_cpu_desc
#endif
#define MONO_MAX_IREGS (RISCV_N_GREGS)
#define MONO_MAX_FREGS (RISCV_N_FREGS)
/*
* Register usage conventions:
*
* - a0..a7 and fa0..fa7 are argument/return registers.
* - s0..11 and fs0..fs11 are callee-saved registers.
* - a0..a1 are used as fixed registers (for the 'a' spec, soft float, and
* longs on 32-bit, as appropriate).
* - t0..t1, ra, and ft0..ft2 are used as scratch registers and can't be
* allocated by the register allocator.
* - t2 is used as the RGCTX/IMT register and can't be allocated by the
* register allocator.
* - a0 is used as the VTable register for lazy fetch trampolines.
* - sp, fp, gp, and tp are all reserved by the ABI and can't be allocated by
* the register allocator.
* - x0 is hard-wired to zero and can't be allocated by the register allocator.
*/
#define MONO_ARCH_CALLEE_REGS (0b11110000000000111111110000000000)
#define MONO_ARCH_CALLEE_SAVED_REGS (0b00001111111111000000001100000000)
#ifdef RISCV_FPABI_SOFT
#define MONO_ARCH_CALLEE_FREGS (0b11111111111111111111111111111000)
#define MONO_ARCH_CALLEE_SAVED_FREGS (0b00000000000000000000000000000000)
#else
#define MONO_ARCH_CALLEE_FREGS (0b11110000000000111111110011111000)
#define MONO_ARCH_CALLEE_SAVED_FREGS (0b00001111111111000000001100000000)
#endif
#define MONO_ARCH_INST_SREG2_MASK(ins) \
(0)
#define MONO_ARCH_INST_IS_FLOAT(desc) \
(!mono_arch_is_soft_float () && (desc) == 'f')
#ifdef TARGET_RISCV64
#define MONO_ARCH_INST_FIXED_REG(desc) \
((desc) == 'a' || (mono_arch_is_soft_float () && (desc) == 'f') ? RISCV_A0 : -1)
#define MONO_ARCH_INST_IS_REGPAIR(desc) \
(FALSE)
#define MONO_ARCH_INST_REGPAIR_REG2(desc, hreg1) \
(-1)
#else
#define MONO_ARCH_INST_FIXED_REG(desc) \
((desc) == 'a' || (desc) == 'l' || (mono_arch_is_soft_float () && (desc) == 'f') ? RISCV_A0 : -1)
#define MONO_ARCH_INST_IS_REGPAIR(desc) \
((desc) == 'l' || (mono_arch_is_soft_float () && (desc) == 'f'))
#define MONO_ARCH_INST_REGPAIR_REG2(desc, hreg1) \
(RISCV_A1)
#endif
#define MONO_ARCH_RGCTX_REG (RISCV_T2)
#define MONO_ARCH_IMT_REG (RISCV_T2)
#define MONO_ARCH_VTABLE_REG (RISCV_A0)
#define MONO_ARCH_HAVE_VOLATILE_NON_PARAM_REGISTER 0
#define MONO_ARCH_USE_FPSTACK (FALSE)
#define MONO_ARCH_FRAME_ALIGNMENT (16)
#define MONO_ARCH_CODE_ALIGNMENT (32)
#define MONO_ARCH_EMULATE_MUL_DIV (1)
#define MONO_ARCH_EMULATE_FREM (1)
#ifdef TARGET_RISCV64
#define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS (1)
#endif
#define MONO_ARCH_EMULATE_CONV_R8_UN (1)
#define MONO_ARCH_EMULATE_FCONV_TO_U8 (1)
#define MONO_ARCH_EMULATE_FCONV_TO_U4 (1)
#define MONO_ARCH_EMULATE_FCONV_TO_I8 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R8 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R4 (1)
#define MONO_ARCH_EMULATE_LCONV_TO_R8_UN (1)
#define MONO_ARCH_NEED_DIV_CHECK (1)
#define MONO_ARCH_HAVE_OP_TAIL_CALL (1)
#define MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT (1)
#define MONO_ARCH_HAVE_CARD_TABLE_WBARRIER (1)
#define MONO_ARCH_HAVE_GENERALIZED_IMT_TRAMPOLINE (1)
#define MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE (1)
#define MONO_ARCH_HAVE_SDB_TRAMPOLINES (1)
#define MONO_ARCH_HAVE_INTERP_PINVOKE_TRAMP (1)
#define MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES (1)
#define MONO_ARCH_USE_SIGACTION (1)
#define MONO_ARCH_HAVE_CONTEXT_SET_INT_REG (1)
#define MONO_ARCH_HAVE_DECOMPOSE_LONG_OPTS (1)
#define MONO_ARCH_HAVE_DECOMPOSE_OPTS (1)
#define MONO_ARCH_HAVE_EXCEPTIONS_INIT (1)
#define MONO_ARCH_HAVE_GET_TRAMPOLINES (1)
#define MONO_ARCH_HAVE_OPCODE_NEEDS_EMULATION (1)
#define MONO_ARCH_HAVE_SETUP_ASYNC_CALLBACK (1)
#define MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX (1)
#define MONO_ARCH_GSHARED_SUPPORTED (1)
#define MONO_ARCH_INTERPRETER_SUPPORTED (1)
//#define MONO_ARCH_AOT_SUPPORTED (1)
//#define MONO_ARCH_LLVM_SUPPORTED (1)
//#define MONO_ARCH_SOFT_DEBUG_SUPPORTED (1)
// #define MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE (1)
// #define MONO_ARCH_HAVE_INTERP_PINVOKE_TRAMP (1)
// #define MONO_ARCH_HAVE_INTERP_NATIVE_TO_MANAGED (1)
typedef struct {
} MonoCompileArch;
#define MONO_CONTEXT_SET_LLVM_EXC_REG(ctx, exc) \
do { \
(ctx)->gregs [RISCV_A0] = (host_mgreg_t) exc; \
} while (0)
#define MONO_INIT_CONTEXT_FROM_FUNC(ctx, func) \
do { \
MONO_CONTEXT_SET_IP ((ctx), (func)); \
MONO_CONTEXT_SET_SP ((ctx), __builtin_frame_address (0)); \
MONO_CONTEXT_SET_BP ((ctx), __builtin_frame_address (0)); \
} while (0)
struct MonoLMF {
// If the second-lowest bit of this field is set, this is a MonoLMFExt.
gpointer previous_lmf;
gpointer lmf_addr;
host_mgreg_t pc;
host_mgreg_t sp;
host_mgreg_t ra;
host_mgreg_t gregs [RISCV_N_GSREGS]; // s0..s11
double fregs [RISCV_N_FSREGS]; // fs0..fs11
};
#define MONO_ARCH_INIT_TOP_LMF_ENTRY(lmf)
typedef struct {
guint8 *stack;
} CallContext;
enum {
MONO_R_RISCV_IMM = 1,
MONO_R_RISCV_B = 2,
MONO_R_RISCV_BEQ = 3,
MONO_R_RISCV_BNE = 4,
MONO_R_RISCV_BLT = 5,
MONO_R_RISCV_BGE = 6,
MONO_R_RISCV_BLTU = 7,
MONO_R_RISCV_BGEU = 8,
};
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_imm (guint8 *code, int rd, gsize imm);
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_load (guint8 *code, int rd, int rs1, gint32 imm);
__attribute__ ((warn_unused_result)) guint8 *
mono_riscv_emit_store (guint8 *code, int rs1, int rs2, gint32 imm);
#endif
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/pal/src/libunwind/src/ia64/init.h | /* libunwind - a platform-independent unwind library
Copyright (C) 2002-2005 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "unwind_i.h"
static ALWAYS_INLINE int
common_init (struct cursor *c, unw_word_t sp, unw_word_t bsp)
{
unw_word_t bspstore, rbs_base;
int ret;
if (c->as->caching_policy != UNW_CACHE_NONE)
/* ensure cache doesn't have any stale contents: */
ia64_validate_cache (c->as, c->as_arg);
c->cfm_loc = IA64_REG_LOC (c, UNW_IA64_CFM);
c->loc[IA64_REG_BSP] = IA64_NULL_LOC;
c->loc[IA64_REG_BSPSTORE] = IA64_REG_LOC (c, UNW_IA64_AR_BSPSTORE);
c->loc[IA64_REG_PFS] = IA64_REG_LOC (c, UNW_IA64_AR_PFS);
c->loc[IA64_REG_RNAT] = IA64_REG_LOC (c, UNW_IA64_AR_RNAT);
c->loc[IA64_REG_IP] = IA64_REG_LOC (c, UNW_IA64_IP);
c->loc[IA64_REG_PRI_UNAT_MEM] = IA64_NULL_LOC; /* no primary UNaT location */
c->loc[IA64_REG_UNAT] = IA64_REG_LOC (c, UNW_IA64_AR_UNAT);
c->loc[IA64_REG_PR] = IA64_REG_LOC (c, UNW_IA64_PR);
c->loc[IA64_REG_LC] = IA64_REG_LOC (c, UNW_IA64_AR_LC);
c->loc[IA64_REG_FPSR] = IA64_REG_LOC (c, UNW_IA64_AR_FPSR);
c->loc[IA64_REG_R4] = IA64_REG_LOC (c, UNW_IA64_GR + 4);
c->loc[IA64_REG_R5] = IA64_REG_LOC (c, UNW_IA64_GR + 5);
c->loc[IA64_REG_R6] = IA64_REG_LOC (c, UNW_IA64_GR + 6);
c->loc[IA64_REG_R7] = IA64_REG_LOC (c, UNW_IA64_GR + 7);
c->loc[IA64_REG_NAT4] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 4, &c->nat_bitnr[0]);
c->loc[IA64_REG_NAT5] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 5, &c->nat_bitnr[1]);
c->loc[IA64_REG_NAT6] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 6, &c->nat_bitnr[2]);
c->loc[IA64_REG_NAT7] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 7, &c->nat_bitnr[3]);
c->loc[IA64_REG_B1] = IA64_REG_LOC (c, UNW_IA64_BR + 1);
c->loc[IA64_REG_B2] = IA64_REG_LOC (c, UNW_IA64_BR + 2);
c->loc[IA64_REG_B3] = IA64_REG_LOC (c, UNW_IA64_BR + 3);
c->loc[IA64_REG_B4] = IA64_REG_LOC (c, UNW_IA64_BR + 4);
c->loc[IA64_REG_B5] = IA64_REG_LOC (c, UNW_IA64_BR + 5);
c->loc[IA64_REG_F2] = IA64_FPREG_LOC (c, UNW_IA64_FR + 2);
c->loc[IA64_REG_F3] = IA64_FPREG_LOC (c, UNW_IA64_FR + 3);
c->loc[IA64_REG_F4] = IA64_FPREG_LOC (c, UNW_IA64_FR + 4);
c->loc[IA64_REG_F5] = IA64_FPREG_LOC (c, UNW_IA64_FR + 5);
c->loc[IA64_REG_F16] = IA64_FPREG_LOC (c, UNW_IA64_FR + 16);
c->loc[IA64_REG_F17] = IA64_FPREG_LOC (c, UNW_IA64_FR + 17);
c->loc[IA64_REG_F18] = IA64_FPREG_LOC (c, UNW_IA64_FR + 18);
c->loc[IA64_REG_F19] = IA64_FPREG_LOC (c, UNW_IA64_FR + 19);
c->loc[IA64_REG_F20] = IA64_FPREG_LOC (c, UNW_IA64_FR + 20);
c->loc[IA64_REG_F21] = IA64_FPREG_LOC (c, UNW_IA64_FR + 21);
c->loc[IA64_REG_F22] = IA64_FPREG_LOC (c, UNW_IA64_FR + 22);
c->loc[IA64_REG_F23] = IA64_FPREG_LOC (c, UNW_IA64_FR + 23);
c->loc[IA64_REG_F24] = IA64_FPREG_LOC (c, UNW_IA64_FR + 24);
c->loc[IA64_REG_F25] = IA64_FPREG_LOC (c, UNW_IA64_FR + 25);
c->loc[IA64_REG_F26] = IA64_FPREG_LOC (c, UNW_IA64_FR + 26);
c->loc[IA64_REG_F27] = IA64_FPREG_LOC (c, UNW_IA64_FR + 27);
c->loc[IA64_REG_F28] = IA64_FPREG_LOC (c, UNW_IA64_FR + 28);
c->loc[IA64_REG_F29] = IA64_FPREG_LOC (c, UNW_IA64_FR + 29);
c->loc[IA64_REG_F30] = IA64_FPREG_LOC (c, UNW_IA64_FR + 30);
c->loc[IA64_REG_F31] = IA64_FPREG_LOC (c, UNW_IA64_FR + 31);
ret = ia64_get (c, c->loc[IA64_REG_IP], &c->ip);
if (ret < 0)
return ret;
ret = ia64_get (c, c->cfm_loc, &c->cfm);
if (ret < 0)
return ret;
ret = ia64_get (c, c->loc[IA64_REG_PR], &c->pr);
if (ret < 0)
return ret;
c->sp = c->psp = sp;
c->bsp = bsp;
ret = ia64_get (c, c->loc[IA64_REG_BSPSTORE], &bspstore);
if (ret < 0)
return ret;
c->rbs_curr = c->rbs_left_edge = 0;
/* Try to find a base of the register backing-store. We may default
to a reasonable value (e.g., half the address-space down from
bspstore). If the BSPSTORE looks corrupt, we fail. */
if ((ret = rbs_get_base (c, bspstore, &rbs_base)) < 0)
return ret;
c->rbs_area[0].end = bspstore;
c->rbs_area[0].size = bspstore - rbs_base;
c->rbs_area[0].rnat_loc = IA64_REG_LOC (c, UNW_IA64_AR_RNAT);
Debug (10, "initial rbs-area: [0x%llx-0x%llx), rnat@%s\n",
(long long) rbs_base, (long long) c->rbs_area[0].end,
ia64_strloc (c->rbs_area[0].rnat_loc));
c->pi.flags = 0;
c->sigcontext_addr = 0;
c->abi_marker = 0;
c->last_abi_marker = 0;
c->hint = 0;
c->prev_script = 0;
c->eh_valid_mask = 0;
c->pi_valid = 0;
return 0;
}
| /* libunwind - a platform-independent unwind library
Copyright (C) 2002-2005 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "unwind_i.h"
static ALWAYS_INLINE int
common_init (struct cursor *c, unw_word_t sp, unw_word_t bsp)
{
unw_word_t bspstore, rbs_base;
int ret;
if (c->as->caching_policy != UNW_CACHE_NONE)
/* ensure cache doesn't have any stale contents: */
ia64_validate_cache (c->as, c->as_arg);
c->cfm_loc = IA64_REG_LOC (c, UNW_IA64_CFM);
c->loc[IA64_REG_BSP] = IA64_NULL_LOC;
c->loc[IA64_REG_BSPSTORE] = IA64_REG_LOC (c, UNW_IA64_AR_BSPSTORE);
c->loc[IA64_REG_PFS] = IA64_REG_LOC (c, UNW_IA64_AR_PFS);
c->loc[IA64_REG_RNAT] = IA64_REG_LOC (c, UNW_IA64_AR_RNAT);
c->loc[IA64_REG_IP] = IA64_REG_LOC (c, UNW_IA64_IP);
c->loc[IA64_REG_PRI_UNAT_MEM] = IA64_NULL_LOC; /* no primary UNaT location */
c->loc[IA64_REG_UNAT] = IA64_REG_LOC (c, UNW_IA64_AR_UNAT);
c->loc[IA64_REG_PR] = IA64_REG_LOC (c, UNW_IA64_PR);
c->loc[IA64_REG_LC] = IA64_REG_LOC (c, UNW_IA64_AR_LC);
c->loc[IA64_REG_FPSR] = IA64_REG_LOC (c, UNW_IA64_AR_FPSR);
c->loc[IA64_REG_R4] = IA64_REG_LOC (c, UNW_IA64_GR + 4);
c->loc[IA64_REG_R5] = IA64_REG_LOC (c, UNW_IA64_GR + 5);
c->loc[IA64_REG_R6] = IA64_REG_LOC (c, UNW_IA64_GR + 6);
c->loc[IA64_REG_R7] = IA64_REG_LOC (c, UNW_IA64_GR + 7);
c->loc[IA64_REG_NAT4] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 4, &c->nat_bitnr[0]);
c->loc[IA64_REG_NAT5] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 5, &c->nat_bitnr[1]);
c->loc[IA64_REG_NAT6] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 6, &c->nat_bitnr[2]);
c->loc[IA64_REG_NAT7] = IA64_REG_NAT_LOC (c, UNW_IA64_NAT + 7, &c->nat_bitnr[3]);
c->loc[IA64_REG_B1] = IA64_REG_LOC (c, UNW_IA64_BR + 1);
c->loc[IA64_REG_B2] = IA64_REG_LOC (c, UNW_IA64_BR + 2);
c->loc[IA64_REG_B3] = IA64_REG_LOC (c, UNW_IA64_BR + 3);
c->loc[IA64_REG_B4] = IA64_REG_LOC (c, UNW_IA64_BR + 4);
c->loc[IA64_REG_B5] = IA64_REG_LOC (c, UNW_IA64_BR + 5);
c->loc[IA64_REG_F2] = IA64_FPREG_LOC (c, UNW_IA64_FR + 2);
c->loc[IA64_REG_F3] = IA64_FPREG_LOC (c, UNW_IA64_FR + 3);
c->loc[IA64_REG_F4] = IA64_FPREG_LOC (c, UNW_IA64_FR + 4);
c->loc[IA64_REG_F5] = IA64_FPREG_LOC (c, UNW_IA64_FR + 5);
c->loc[IA64_REG_F16] = IA64_FPREG_LOC (c, UNW_IA64_FR + 16);
c->loc[IA64_REG_F17] = IA64_FPREG_LOC (c, UNW_IA64_FR + 17);
c->loc[IA64_REG_F18] = IA64_FPREG_LOC (c, UNW_IA64_FR + 18);
c->loc[IA64_REG_F19] = IA64_FPREG_LOC (c, UNW_IA64_FR + 19);
c->loc[IA64_REG_F20] = IA64_FPREG_LOC (c, UNW_IA64_FR + 20);
c->loc[IA64_REG_F21] = IA64_FPREG_LOC (c, UNW_IA64_FR + 21);
c->loc[IA64_REG_F22] = IA64_FPREG_LOC (c, UNW_IA64_FR + 22);
c->loc[IA64_REG_F23] = IA64_FPREG_LOC (c, UNW_IA64_FR + 23);
c->loc[IA64_REG_F24] = IA64_FPREG_LOC (c, UNW_IA64_FR + 24);
c->loc[IA64_REG_F25] = IA64_FPREG_LOC (c, UNW_IA64_FR + 25);
c->loc[IA64_REG_F26] = IA64_FPREG_LOC (c, UNW_IA64_FR + 26);
c->loc[IA64_REG_F27] = IA64_FPREG_LOC (c, UNW_IA64_FR + 27);
c->loc[IA64_REG_F28] = IA64_FPREG_LOC (c, UNW_IA64_FR + 28);
c->loc[IA64_REG_F29] = IA64_FPREG_LOC (c, UNW_IA64_FR + 29);
c->loc[IA64_REG_F30] = IA64_FPREG_LOC (c, UNW_IA64_FR + 30);
c->loc[IA64_REG_F31] = IA64_FPREG_LOC (c, UNW_IA64_FR + 31);
ret = ia64_get (c, c->loc[IA64_REG_IP], &c->ip);
if (ret < 0)
return ret;
ret = ia64_get (c, c->cfm_loc, &c->cfm);
if (ret < 0)
return ret;
ret = ia64_get (c, c->loc[IA64_REG_PR], &c->pr);
if (ret < 0)
return ret;
c->sp = c->psp = sp;
c->bsp = bsp;
ret = ia64_get (c, c->loc[IA64_REG_BSPSTORE], &bspstore);
if (ret < 0)
return ret;
c->rbs_curr = c->rbs_left_edge = 0;
/* Try to find a base of the register backing-store. We may default
to a reasonable value (e.g., half the address-space down from
bspstore). If the BSPSTORE looks corrupt, we fail. */
if ((ret = rbs_get_base (c, bspstore, &rbs_base)) < 0)
return ret;
c->rbs_area[0].end = bspstore;
c->rbs_area[0].size = bspstore - rbs_base;
c->rbs_area[0].rnat_loc = IA64_REG_LOC (c, UNW_IA64_AR_RNAT);
Debug (10, "initial rbs-area: [0x%llx-0x%llx), rnat@%s\n",
(long long) rbs_base, (long long) c->rbs_area[0].end,
ia64_strloc (c->rbs_area[0].rnat_loc));
c->pi.flags = 0;
c->sigcontext_addr = 0;
c->abi_marker = 0;
c->last_abi_marker = 0;
c->hint = 0;
c->prev_script = 0;
c->eh_valid_mask = 0;
c->pi_valid = 0;
return 0;
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/inc/memorypool.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _MEMORYPOOL_
#define _MEMORYPOOL_
#include "daccess.h"
#include "contract.h"
//
// A MemoryPool is an allocator for a fixed size elements.
// Allocating and freeing elements from the pool is very cheap compared
// to a general allocator like new. However, a MemoryPool is slightly
// more greedy - it preallocates a bunch of elements at a time, and NEVER
// RELEASES MEMORY FROM THE POOL ONCE IT IS ALLOCATED, (unless you call
// FreeAllElements.)
//
// It also has several additional features:
// * you can free the entire pool of objects cheaply.
// * you can test an object to see if it's an element of the pool.
//
class MemoryPool
{
public:
#ifndef DACCESS_COMPILE
MemoryPool(SIZE_T elementSize, SIZE_T initGrowth = 20, SIZE_T initCount = 0);
#else
MemoryPool() {}
#endif
~MemoryPool() DAC_EMPTY();
BOOL IsElement(void *element);
BOOL IsAllocatedElement(void *element);
void *AllocateElement();
void *AllocateElementNoThrow();
void FreeElement(void *element);
void FreeAllElements();
size_t GetSize();
private:
struct Element
{
Element *next;
#if _DEBUG
int deadBeef;
#endif
};
struct Block
{
Block *next;
Element *elementsEnd;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4200)
#endif
Element elements[0];
#ifdef _MSC_VER
#pragma warning(pop)
#endif
};
SIZE_T m_elementSize;
SIZE_T m_growCount;
Block *m_blocks;
Element *m_freeList;
BOOL AddBlock(SIZE_T elementCount);
void DeadBeef(Element *element);
public:
//
// NOTE: You can currently only iterate the elements
// if none have been freed.
//
class Iterator
{
private:
Block *m_next;
BYTE *m_e, *m_eEnd;
BYTE *m_end;
SIZE_T m_size;
public:
Iterator(MemoryPool *pool);
BOOL Next();
void *GetElement() {LIMITED_METHOD_CONTRACT; return (void *) (m_e-m_size); }
};
friend class Iterator;
};
class MemoryPoolElementHolder
{
protected:
MemoryPool* m_pool;
void* m_element;
BOOL bRelease;
public:
void SuppressRelease()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(bRelease);
bRelease=false;
}
void Release()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(bRelease);
m_pool->FreeElement(m_element);
bRelease=false;
}
MemoryPoolElementHolder(MemoryPool* pool, void* element)
{
LIMITED_METHOD_CONTRACT;
m_pool=pool;
m_element=element;
bRelease=true;
}
~MemoryPoolElementHolder()
{
LIMITED_METHOD_CONTRACT;
if (bRelease)
Release();
}
operator void* ()
{
LIMITED_METHOD_CONTRACT;
return m_element;
}
};
#endif // _MEMORYPOOL_
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _MEMORYPOOL_
#define _MEMORYPOOL_
#include "daccess.h"
#include "contract.h"
//
// A MemoryPool is an allocator for a fixed size elements.
// Allocating and freeing elements from the pool is very cheap compared
// to a general allocator like new. However, a MemoryPool is slightly
// more greedy - it preallocates a bunch of elements at a time, and NEVER
// RELEASES MEMORY FROM THE POOL ONCE IT IS ALLOCATED, (unless you call
// FreeAllElements.)
//
// It also has several additional features:
// * you can free the entire pool of objects cheaply.
// * you can test an object to see if it's an element of the pool.
//
class MemoryPool
{
public:
#ifndef DACCESS_COMPILE
MemoryPool(SIZE_T elementSize, SIZE_T initGrowth = 20, SIZE_T initCount = 0);
#else
MemoryPool() {}
#endif
~MemoryPool() DAC_EMPTY();
BOOL IsElement(void *element);
BOOL IsAllocatedElement(void *element);
void *AllocateElement();
void *AllocateElementNoThrow();
void FreeElement(void *element);
void FreeAllElements();
size_t GetSize();
private:
struct Element
{
Element *next;
#if _DEBUG
int deadBeef;
#endif
};
struct Block
{
Block *next;
Element *elementsEnd;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4200)
#endif
Element elements[0];
#ifdef _MSC_VER
#pragma warning(pop)
#endif
};
SIZE_T m_elementSize;
SIZE_T m_growCount;
Block *m_blocks;
Element *m_freeList;
BOOL AddBlock(SIZE_T elementCount);
void DeadBeef(Element *element);
public:
//
// NOTE: You can currently only iterate the elements
// if none have been freed.
//
class Iterator
{
private:
Block *m_next;
BYTE *m_e, *m_eEnd;
BYTE *m_end;
SIZE_T m_size;
public:
Iterator(MemoryPool *pool);
BOOL Next();
void *GetElement() {LIMITED_METHOD_CONTRACT; return (void *) (m_e-m_size); }
};
friend class Iterator;
};
class MemoryPoolElementHolder
{
protected:
MemoryPool* m_pool;
void* m_element;
BOOL bRelease;
public:
void SuppressRelease()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(bRelease);
bRelease=false;
}
void Release()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(bRelease);
m_pool->FreeElement(m_element);
bRelease=false;
}
MemoryPoolElementHolder(MemoryPool* pool, void* element)
{
LIMITED_METHOD_CONTRACT;
m_pool=pool;
m_element=element;
bRelease=true;
}
~MemoryPoolElementHolder()
{
LIMITED_METHOD_CONTRACT;
if (bRelease)
Release();
}
operator void* ()
{
LIMITED_METHOD_CONTRACT;
return m_element;
}
};
#endif // _MEMORYPOOL_
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/gc.c | /**
* \file
* GC icalls.
*
* Author: Paolo Molaro <[email protected]>
*
* Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2012 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 <glib.h>
#include <string.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/sgen/sgen-conf.h>
#include <mono/sgen/sgen-gc.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
#include <mono/utils/mono-os-semaphore.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/dtrace.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-coop-semaphore.h>
#include <mono/utils/hazard-pointer.h>
#include <mono/utils/w32api.h>
#include <mono/utils/unlocked.h>
#include <mono/utils/mono-os-wait.h>
#include <mono/utils/mono-lazy-init.h>
#ifndef HOST_WIN32
#include <pthread.h>
#endif
#include "external-only.h"
#include "icall-decl.h"
#if _MSC_VER
#pragma warning(disable:4312) // FIXME pointer cast to different size
#endif
typedef struct DomainFinalizationReq {
gint32 ref;
MonoDomain *domain;
MonoCoopSem done;
} DomainFinalizationReq;
static gboolean gc_disabled;
static gboolean finalizing_root_domain;
gboolean mono_log_finalizers;
gboolean mono_do_not_finalize;
static volatile gboolean suspend_finalizers;
gchar **mono_do_not_finalize_class_names ;
#define mono_finalizer_lock() mono_coop_mutex_lock (&finalizer_mutex)
#define mono_finalizer_unlock() mono_coop_mutex_unlock (&finalizer_mutex)
static MonoCoopMutex finalizer_mutex;
static MonoCoopMutex reference_queue_mutex;
static mono_lazy_init_t reference_queue_mutex_inited = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
static GSList *domains_to_finalize;
static gboolean finalizer_thread_exited;
/* Uses finalizer_mutex */
static MonoCoopCond exited_cond;
static MonoInternalThread *gc_thread;
#ifndef HOST_WASM
static RuntimeInvokeFunction finalize_runtime_invoke;
#endif
/*
* This must be a GHashTable, since these objects can't be finalized
* if the hashtable contains a GC visible reference to them.
*/
static GHashTable *finalizable_objects_hash;
static mono_mutex_t finalizable_objects_hash_lock;
#ifdef TARGET_WIN32
static HANDLE pending_done_event;
#else
static gboolean pending_done;
static MonoCoopCond pending_done_cond;
static MonoCoopMutex pending_done_mutex;
#endif
#define finalizers_lock() mono_os_mutex_lock (&finalizable_objects_hash_lock);
#define finalizers_unlock() mono_os_mutex_unlock (&finalizable_objects_hash_lock);
static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
static void reference_queue_proccess_all (void);
static void mono_reference_queue_cleanup (void);
static void reference_queue_clear_for_domain (MonoDomain *domain);
static void mono_runtime_do_background_work (void);
static MonoThreadInfoWaitRet
guarded_wait (MonoThreadHandle *thread_handle, guint32 timeout, gboolean alertable)
{
MonoThreadInfoWaitRet result;
MONO_ENTER_GC_SAFE;
result = mono_thread_info_wait_one_handle (thread_handle, timeout, alertable);
MONO_EXIT_GC_SAFE;
return result;
}
typedef struct {
MonoCoopCond *cond;
MonoCoopMutex *mutex;
} BreakCoopAlertableWaitUD;
static void
break_coop_alertable_wait (gpointer user_data)
{
BreakCoopAlertableWaitUD *ud = (BreakCoopAlertableWaitUD*)user_data;
mono_coop_mutex_lock (ud->mutex);
mono_coop_cond_signal (ud->cond);
mono_coop_mutex_unlock (ud->mutex);
g_free (ud);
}
/*
* coop_cond_timedwait_alertable:
*
* Wait on COND/MUTEX. If ALERTABLE is non-null, the wait can be interrupted.
* In that case, *ALERTABLE will be set to TRUE, and 0 is returned.
*/
static gint
coop_cond_timedwait_alertable (MonoCoopCond *cond, MonoCoopMutex *mutex, guint32 timeout_ms, gboolean *alertable)
{
BreakCoopAlertableWaitUD *ud;
int res;
if (alertable) {
ud = g_new0 (BreakCoopAlertableWaitUD, 1);
ud->cond = cond;
ud->mutex = mutex;
mono_thread_info_install_interrupt (break_coop_alertable_wait, ud, alertable);
if (*alertable) {
g_free (ud);
return 0;
}
}
res = mono_coop_cond_timedwait (cond, mutex, timeout_ms);
if (alertable) {
mono_thread_info_uninstall_interrupt (alertable);
if (*alertable)
return 0;
else {
/* the interrupt token has not been taken by another
* thread, so it's our responsability to free it up. */
g_free (ud);
}
}
return res;
}
/*
* actually, we might want to queue the finalize requests in a separate thread,
* but we need to be careful about the execution domain of the thread...
*/
void
mono_gc_run_finalize (void *obj, void *data)
{
ERROR_DECL (error);
MonoObject *exc = NULL;
MonoObject *o;
#ifndef HAVE_SGEN_GC
MonoObject *o2;
#endif
MonoMethod* finalizer = NULL;
MonoDomain *caller_domain = mono_domain_get ();
// This function is called from the innards of the GC, so our best alternative for now is to do polling here
mono_threads_safepoint ();
o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
const char *o_ns = m_class_get_name_space (mono_object_class (o));
const char *o_name = m_class_get_name (mono_object_class (o));
if (mono_do_not_finalize) {
if (!mono_do_not_finalize_class_names)
return;
size_t namespace_len = strlen (o_ns);
for (int i = 0; mono_do_not_finalize_class_names [i]; ++i) {
const char *name = mono_do_not_finalize_class_names [i];
if (strncmp (name, o_ns, namespace_len))
break;
if (name [namespace_len] != '.')
break;
if (strcmp (name + namespace_len + 1, o_name))
break;
return;
}
}
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_DEBUG, "<%s at %p> Starting finalizer checks.", o_name, o);
if (suspend_finalizers)
return;
#ifndef HAVE_SGEN_GC
finalizers_lock ();
o2 = (MonoObject *)g_hash_table_lookup (finalizable_objects_hash, o);
finalizers_unlock ();
if (!o2)
/* Already finalized somehow */
return;
#endif
/* make sure the finalizer is not called again if the object is resurrected */
object_register_finalizer ((MonoObject *)obj, NULL);
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Registered finalizer as processed.", o_name, o);
if (o->vtable->klass == mono_defaults.internal_thread_class) {
MonoInternalThread *t = (MonoInternalThread*)o;
if (mono_gc_is_finalizer_internal_thread (t))
/* Avoid finalizing ourselves */
return;
}
if (m_class_get_image (mono_object_class (o)) == mono_defaults.corlib && !strcmp (o_name, "DynamicMethod") && finalizing_root_domain) {
/*
* These can't be finalized during unloading/shutdown, since that would
* free the native code which can still be referenced by other
* finalizers.
* FIXME: This is not perfect, objects dying at the same time as
* dynamic methods can still reference them even when !shutdown.
*/
return;
}
if (mono_runtime_get_no_exec ())
return;
/* speedup later... and use a timeout */
/* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
/* Use _internal here, since this thread can enter a doomed appdomain */
mono_domain_set_internal_with_options (mono_object_domain (o), TRUE);
/* delegates that have a native function pointer allocated are
* registered for finalization, but they don't have a Finalize
* method, because in most cases it's not needed and it's just a waste.
*/
if (m_class_is_delegate (mono_object_class (o))) {
MonoDelegate* del = (MonoDelegate*)o;
if (del->delegate_trampoline)
mono_delegate_free_ftnptr ((MonoDelegate*)o);
mono_domain_set_internal_with_options (caller_domain, TRUE);
return;
}
finalizer = mono_class_get_finalizer (o->vtable->klass);
/* If object has a CCW but has no finalizer, it was only
* registered for finalization in order to free the CCW.
* Else it needs the regular finalizer run.
* FIXME: what to do about ressurection and suppression
* of finalizer on object with CCW.
*/
if (mono_marshal_free_ccw (o) && !finalizer) {
mono_domain_set_internal_with_options (caller_domain, TRUE);
return;
}
/*
* To avoid the locking plus the other overhead of mono_runtime_invoke_checked (),
* create and precompile a wrapper which calls the finalize method using
* a CALLVIRT.
*/
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Compiling finalizer.", o_name, o);
#ifndef HOST_WASM
if (!finalize_runtime_invoke) {
MonoMethod *finalize_method = mono_class_get_method_from_name_checked (mono_defaults.object_class, "Finalize", 0, 0, error);
mono_error_assert_ok (error);
MonoMethod *invoke = mono_marshal_get_runtime_invoke (finalize_method, TRUE);
finalize_runtime_invoke = (RuntimeInvokeFunction)mono_compile_method_checked (invoke, error);
mono_error_assert_ok (error); /* expect this not to fail */
}
RuntimeInvokeFunction runtime_invoke = finalize_runtime_invoke;
#endif
mono_runtime_class_init_full (o->vtable, error);
goto_if_nok (error, unhandled_error);
if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size_internal (o),
o_ns, o_name);
}
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Calling finalizer.", o_name, o);
MONO_PROFILER_RAISE (gc_finalizing_object, (o));
#ifdef HOST_WASM
if (finalizer) { // null finalizers work fine when using the vcall invoke as Object has an empty one
gpointer params [1];
params [0] = NULL;
mono_runtime_try_invoke (finalizer, o, params, &exc, error);
}
#else
runtime_invoke (o, NULL, &exc, NULL);
#endif
MONO_PROFILER_RAISE (gc_finalized_object, (o));
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Returned from finalizer.", o_name, o);
unhandled_error:
if (!is_ok (error))
exc = (MonoObject*)mono_error_convert_to_exception (error);
if (exc)
mono_thread_internal_unhandled_exception (exc);
mono_domain_set_internal_with_options (caller_domain, TRUE);
}
/*
* Some of our objects may point to a different address than the address returned by GC_malloc()
* (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
* This also means that in the callback we need to adjust the pointer to get back the real
* MonoObject*.
* We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
* since that, too, can cause the underlying pointer to be offset.
*/
static void
object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
{
g_assert (obj != NULL);
#if HAVE_BOEHM_GC
finalizers_lock ();
if (callback)
g_hash_table_insert (finalizable_objects_hash, obj, obj);
else
g_hash_table_remove (finalizable_objects_hash, obj);
finalizers_unlock ();
mono_gc_register_for_finalization (obj, callback);
#elif defined(HAVE_SGEN_GC)
mono_gc_register_for_finalization (obj, callback);
#endif
}
/**
* mono_object_register_finalizer:
* \param obj object to register
*
* Records that object \p obj has a finalizer, this will call the
* Finalize method when the garbage collector disposes the object.
*
*/
void
mono_object_register_finalizer_handle (MonoObjectHandle obj)
{
/* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_handle_class (obj)->name_space, mono_handle_class (obj)->name); */
object_register_finalizer (MONO_HANDLE_RAW (obj), mono_gc_run_finalize);
}
static void
mono_object_unregister_finalizer_handle (MonoObjectHandle obj)
{
/* g_print ("Unregistered finalizer on %p %s.%s\n", obj, mono_handle_class (obj)->name_space, mono_handle_class (obj)->name); */
object_register_finalizer (MONO_HANDLE_RAW (obj), NULL);
}
void
mono_object_register_finalizer (MonoObject *obj)
{
/* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
object_register_finalizer (obj, mono_gc_run_finalize);
}
/**
* mono_domain_finalize:
* \param domain the domain to finalize
* \param timeout msecs to wait for the finalization to complete, \c -1 to wait indefinitely
*
* Request finalization of all finalizable objects inside \p domain. Wait
* \p timeout msecs for the finalization to complete.
*
* \returns TRUE if succeeded, FALSE if there was a timeout
*/
gboolean
mono_domain_finalize (MonoDomain *domain, guint32 timeout)
{
DomainFinalizationReq *req;
MonoInternalThread *thread = mono_thread_internal_current ();
gint res;
gboolean ret;
gint64 start;
if (mono_thread_internal_current () == gc_thread)
/* We are called from inside a finalizer, not much we can do here */
return FALSE;
/*
* No need to create another thread 'cause the finalizer thread
* is still working and will take care of running the finalizers
*/
if (gc_disabled)
return TRUE;
/* We don't support domain finalization without a GC */
if (mono_gc_is_null ())
return FALSE;
mono_gc_collect (mono_gc_max_generation ());
req = g_new0 (DomainFinalizationReq, 1);
req->ref = 2;
req->domain = domain;
mono_coop_sem_init (&req->done, 0);
if (domain == mono_get_root_domain ())
finalizing_root_domain = TRUE;
mono_finalizer_lock ();
domains_to_finalize = g_slist_append (domains_to_finalize, req);
mono_finalizer_unlock ();
/* Tell the finalizer thread to finalize this appdomain */
mono_gc_finalize_notify ();
if (timeout == -1)
timeout = MONO_INFINITE_WAIT;
if (timeout != MONO_INFINITE_WAIT)
start = mono_msec_ticks ();
ret = TRUE;
for (;;) {
if (timeout == MONO_INFINITE_WAIT) {
res = mono_coop_sem_wait (&req->done, MONO_SEM_FLAGS_ALERTABLE);
} else {
gint64 elapsed = mono_msec_ticks () - start;
if (elapsed >= timeout) {
ret = FALSE;
break;
}
res = mono_coop_sem_timedwait (&req->done, timeout - elapsed, MONO_SEM_FLAGS_ALERTABLE);
}
if (res == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
break;
} else if (res == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
ret = FALSE;
break;
}
} else if (res == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
ret = FALSE;
break;
} else {
g_error ("%s: unknown result %d", __func__, res);
}
}
if (!ret) {
/* Try removing the req from domains_to_finalize:
* - if it's not found: the domain is being finalized,
* so we the ref count is already decremented
* - if it's found: the domain is not yet being finalized,
* so we can safely decrement the ref */
gboolean found;
mono_finalizer_lock ();
found = g_slist_index (domains_to_finalize, req) != -1;
if (found)
domains_to_finalize = g_slist_remove (domains_to_finalize, req);
mono_finalizer_unlock ();
if (found) {
/* We have to decrement it wherever we
* remove it from domains_to_finalize */
if (mono_atomic_dec_i32 (&req->ref) != 1)
g_error ("%s: req->ref should be 1, as we are the first one to decrement it", __func__);
}
goto done;
}
done:
if (mono_atomic_dec_i32 (&req->ref) == 0) {
mono_coop_sem_destroy (&req->done);
g_free (req);
}
return ret;
}
void
ves_icall_System_GC_InternalCollect (int generation)
{
mono_gc_collect (generation);
}
gint64
ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
{
if (forceCollection)
mono_gc_collect (mono_gc_max_generation ());
return mono_gc_get_used_size ();
}
void
ves_icall_System_GC_GetGCMemoryInfo (
gint64 *high_memory_load_threshold_bytes,
gint64 *memory_load_bytes,
gint64 *total_available_memory_bytes,
gint64 *total_committed_bytes,
gint64 *heap_size_bytes,
gint64 *fragmented_bytes)
{
mono_gc_get_gcmemoryinfo (high_memory_load_threshold_bytes, memory_load_bytes, total_available_memory_bytes, total_committed_bytes, heap_size_bytes, fragmented_bytes);
}
void
ves_icall_System_GC_ReRegisterForFinalize (MonoObjectHandle obj, MonoError *error)
{
MONO_CHECK_ARG_NULL_HANDLE (obj,);
mono_object_register_finalizer_handle (obj);
}
void
ves_icall_System_GC_SuppressFinalize (MonoObjectHandle obj, MonoError *error)
{
MONO_CHECK_ARG_NULL_HANDLE (obj,);
/* delegates have no finalizers, but we register them to deal with the
* unmanaged->managed trampoline. We don't let the user suppress it
* otherwise we'd leak it.
*/
if (m_class_is_delegate (mono_handle_class (obj)))
return;
/* FIXME: Need to handle case where obj has COM Callable Wrapper
* generated for it that needs cleaned up, but user wants to suppress
* their derived object finalizer. */
mono_object_unregister_finalizer_handle (obj);
}
void
ves_icall_System_GC_WaitForPendingFinalizers (void)
{
if (mono_gc_is_null ())
return;
if (!mono_gc_pending_finalizers ())
return;
if (mono_thread_internal_current () == gc_thread)
/* Avoid deadlocks */
return;
/*
If the finalizer thread is not live, lets pretend no finalizers are pending since the current thread might
be the one responsible for starting it up.
*/
if (gc_thread == NULL)
return;
#ifdef TARGET_WIN32
ResetEvent (pending_done_event);
mono_gc_finalize_notify ();
/* g_print ("Waiting for pending finalizers....\n"); */
mono_coop_win32_wait_for_single_object_ex (pending_done_event, INFINITE, TRUE);
/* g_print ("Done pending....\n"); */
#else
gboolean alerted = FALSE;
mono_coop_mutex_lock (&pending_done_mutex);
pending_done = FALSE;
mono_gc_finalize_notify ();
while (!pending_done) {
coop_cond_timedwait_alertable (&pending_done_cond, &pending_done_mutex, MONO_INFINITE_WAIT, &alerted);
if (alerted)
break;
}
mono_coop_mutex_unlock (&pending_done_mutex);
#endif
}
void
ves_icall_System_GC_register_ephemeron_array (MonoObjectHandle array, MonoError *error)
{
if (!mono_gc_ephemeron_array_add (MONO_HANDLE_RAW (array)))
mono_error_set_out_of_memory (error, "");
}
MonoObjectHandle
ves_icall_System_GC_get_ephemeron_tombstone (MonoError *error)
{
return MONO_HANDLE_NEW (MonoObject, mono_domain_get ()->ephemeron_tombstone);
}
MonoGCHandle
ves_icall_System_GCHandle_InternalAlloc (MonoObjectHandle obj, gint32 type, MonoError *error)
{
MonoGCHandle handle = NULL;
switch (type) {
case HANDLE_WEAK:
handle = mono_gchandle_new_weakref_from_handle (obj);
break;
case HANDLE_WEAK_TRACK:
handle = mono_gchandle_new_weakref_from_handle_track_resurrection (obj);
break;
case HANDLE_NORMAL:
handle = mono_gchandle_from_handle (obj, FALSE);
break;
case HANDLE_PINNED:
handle = mono_gchandle_from_handle (obj, TRUE);
break;
default:
g_assert_not_reached ();
}
return handle;
}
void
ves_icall_System_GCHandle_InternalFree (MonoGCHandle handle, MonoError *error)
{
mono_gchandle_free_internal (handle);
}
MonoObjectHandle
ves_icall_System_GCHandle_InternalGet (MonoGCHandle handle, MonoError *error)
{
return mono_gchandle_get_target_handle (handle);
}
void
ves_icall_System_GCHandle_InternalSet (MonoGCHandle handle, MonoObjectHandle obj, MonoError *error)
{
mono_gchandle_set_target_handle (handle, obj);
}
static MonoCoopSem finalizer_sem;
static volatile gboolean finished;
/*
* mono_gc_finalize_notify:
*
* Notify the finalizer thread that finalizers etc.
* are available to be processed.
* This is async signal safe.
*/
void
mono_gc_finalize_notify (void)
{
#ifdef DEBUG
g_message ( "%s: prodding finalizer", __func__);
#endif
if (mono_gc_is_null ())
return;
#if defined(HOST_WASI)
// TODO: Schedule the background job on WASI. Threads aren't yet supported in this build.
#elif defined(HOST_WASM)
mono_threads_schedule_background_job (mono_runtime_do_background_work);
#else
mono_coop_sem_post (&finalizer_sem);
#endif
}
/*
This is the number of entries allowed in the hazard free queue before
we explicitly cycle the finalizer thread to trigger pumping the queue.
It was picked empirically by running the corlib test suite in a stress
scenario where all hazard entries are queued.
In this extreme scenario we double the number of times we cycle the finalizer
thread compared to just GC calls.
Entries are usually in the order of 100's of bytes each, so we're limiting
floating garbage to be in the order of a dozen kb.
*/
static gboolean finalizer_thread_pulsed;
#define HAZARD_QUEUE_OVERFLOW_SIZE 20
static void
hazard_free_queue_is_too_big (size_t size)
{
if (size < HAZARD_QUEUE_OVERFLOW_SIZE)
return;
if (finalizer_thread_pulsed || mono_atomic_cas_i32 (&finalizer_thread_pulsed, TRUE, FALSE))
return;
mono_gc_finalize_notify ();
}
static void
hazard_free_queue_pump (void)
{
mono_thread_hazardous_try_free_all ();
finalizer_thread_pulsed = FALSE;
}
#ifdef HAVE_BOEHM_GC
static void
collect_objects (gpointer key, gpointer value, gpointer user_data)
{
GPtrArray *arr = (GPtrArray*)user_data;
g_ptr_array_add (arr, key);
}
#endif
/*
* finalize_domain_objects:
*
* Run the finalizers of all finalizable objects in req->domain.
*/
static void
finalize_domain_objects (void)
{
DomainFinalizationReq *req = NULL;
MonoDomain *domain;
if (UnlockedReadPointer ((gpointer volatile*)&domains_to_finalize)) {
mono_finalizer_lock ();
if (domains_to_finalize) {
req = (DomainFinalizationReq *)domains_to_finalize->data;
domains_to_finalize = g_slist_remove (domains_to_finalize, req);
}
mono_finalizer_unlock ();
}
if (!req)
return;
domain = req->domain;
/* Process finalizers which are already in the queue */
mono_gc_invoke_finalizers ();
#ifdef HAVE_BOEHM_GC
while (g_hash_table_size (finalizable_objects_hash) > 0) {
int i;
GPtrArray *objs;
/*
* Since the domain is unloading, nobody is allowed to put
* new entries into the hash table. But finalize_object might
* remove entries from the hash table, so we make a copy.
*/
objs = g_ptr_array_new ();
g_hash_table_foreach (finalizable_objects_hash, collect_objects, objs);
/* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
for (i = 0; i < objs->len; ++i) {
MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
/* FIXME: Avoid finalizing threads, etc */
mono_gc_run_finalize (o, 0);
}
g_ptr_array_free (objs, TRUE);
}
#elif defined(HAVE_SGEN_GC)
mono_gc_finalize_domain (domain);
mono_gc_invoke_finalizers ();
#endif
/* cleanup the reference queue */
reference_queue_clear_for_domain (domain);
/* printf ("DONE.\n"); */
mono_coop_sem_post (&req->done);
if (mono_atomic_dec_i32 (&req->ref) == 0) {
/* mono_domain_finalize already returned, and
* doesn't hold a reference to req anymore. */
mono_coop_sem_destroy (&req->done);
g_free (req);
}
}
static void
mono_runtime_do_background_work (void)
{
mono_threads_perform_thread_dump ();
mono_threads_exiting ();
finalize_domain_objects ();
MONO_PROFILER_RAISE (gc_finalizing, ());
/* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
* before the domain is unloaded.
*/
mono_gc_invoke_finalizers ();
MONO_PROFILER_RAISE (gc_finalized, ());
mono_threads_join_threads ();
reference_queue_proccess_all ();
hazard_free_queue_pump ();
}
static gsize WINAPI
finalizer_thread (gpointer unused)
{
gboolean wait = TRUE;
gboolean did_init_from_native = FALSE;
mono_thread_set_name_constant_ignore_error (mono_thread_internal_current (), "Finalizer", MonoSetThreadNameFlag_None);
/* Register a hazard free queue pump callback */
mono_hazard_pointer_install_free_queue_size_callback (hazard_free_queue_is_too_big);
while (!finished) {
/* Wait to be notified that there's at least one
* finaliser to run
*/
g_assert (mono_domain_get () == mono_get_root_domain ());
mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NO_GC);
if (wait) {
/* An alertable wait is required so this thread can be suspended on windows */
mono_coop_sem_wait (&finalizer_sem, MONO_SEM_FLAGS_ALERTABLE);
}
wait = TRUE;
mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NONE);
/* The Finalizer thread doesn't initialize during creation because base managed
libraries may not be loaded yet. However, the first time the Finalizer is
to run managed finalizer, we can take this opportunity to initialize. */
if (!did_init_from_native) {
did_init_from_native = TRUE;
mono_thread_init_from_native ();
}
mono_runtime_do_background_work ();
/* Avoid posting the pending done event until there are pending finalizers */
if (mono_coop_sem_timedwait (&finalizer_sem, 0, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
/* Don't wait again at the start of the loop */
wait = FALSE;
} else {
#ifdef TARGET_WIN32
SetEvent (pending_done_event);
#else
mono_coop_mutex_lock (&pending_done_mutex);
pending_done = TRUE;
mono_coop_cond_signal (&pending_done_cond);
mono_coop_mutex_unlock (&pending_done_mutex);
#endif
}
}
/* If the initialization from native was done, do the clean up */
if (did_init_from_native) {
mono_thread_cleanup_from_native ();
}
mono_finalizer_lock ();
finalizer_thread_exited = TRUE;
mono_coop_cond_signal (&exited_cond);
mono_finalizer_unlock ();
return 0;
}
static void
init_finalizer_thread (void)
{
ERROR_DECL (error);
gc_thread = mono_thread_create_internal ((MonoThreadStart)finalizer_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
mono_error_assert_ok (error);
}
/**
* mono_gc_init_finalizer_thread:
*
* If the runtime is compiled with --with-lazy-gc-thread-creation, this
* function must be called by embedders to create the finalizer. Otherwise, the
* function does nothing and the runtime creates the finalizer thread
* automatically.
*/
void
mono_gc_init_finalizer_thread (void)
{
#ifndef LAZY_GC_THREAD_CREATION
/* do nothing */
#else
MONO_ENTER_GC_UNSAFE;
init_finalizer_thread ();
MONO_EXIT_GC_UNSAFE;
#endif
}
static void
reference_queue_mutex_init (void)
{
mono_coop_mutex_init_recursive (&reference_queue_mutex);
}
void
mono_gc_init (void)
{
mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init);
mono_coop_mutex_init_recursive (&finalizer_mutex);
mono_os_mutex_init_recursive (&finalizable_objects_hash_lock);
finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_counters_register ("Minor GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.minor_gc_count);
mono_counters_register ("Major GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.major_gc_count);
mono_counters_register ("Minor GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &mono_gc_stats.minor_gc_time);
mono_counters_register ("Major GC time", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &mono_gc_stats.major_gc_time);
mono_counters_register ("Major GC time concurrent", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &mono_gc_stats.major_gc_time_concurrent);
mono_gc_base_init ();
if (mono_gc_is_disabled ()) {
gc_disabled = TRUE;
return;
}
#ifdef TARGET_WIN32
pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
g_assert (pending_done_event);
#else
mono_coop_cond_init (&pending_done_cond);
mono_coop_mutex_init (&pending_done_mutex);
#endif
mono_coop_cond_init (&exited_cond);
mono_coop_sem_init (&finalizer_sem, 0);
#ifndef LAZY_GC_THREAD_CREATION
if (!mono_runtime_get_no_exec ())
init_finalizer_thread ();
#endif
}
gboolean
mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
{
return thread == gc_thread;
}
/**
* mono_gc_is_finalizer_thread:
* \param thread the thread to test.
*
* In Mono objects are finalized asynchronously on a separate thread.
* This routine tests whether the \p thread argument represents the
* finalization thread.
*
* \returns TRUE if \p thread is the finalization thread.
*/
gboolean
mono_gc_is_finalizer_thread (MonoThread *thread)
{
return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
}
#if defined(__MACH__)
static pthread_t mach_exception_thread;
void
mono_gc_register_mach_exception_thread (pthread_t thread)
{
mach_exception_thread = thread;
}
pthread_t
mono_gc_get_mach_exception_thread (void)
{
return mach_exception_thread;
}
#endif
static MonoReferenceQueue *ref_queues;
static void
ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
{
do {
/* Guard if head is changed concurrently. */
while (*prev != element)
prev = &(*prev)->next;
} while (prev && mono_atomic_cas_ptr ((volatile gpointer *)prev, element->next, element) != element);
}
static void
ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
{
RefQueueEntry *current;
do {
current = *head;
value->next = current;
STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
} while (mono_atomic_cas_ptr ((volatile gpointer *)head, value, current) != current);
}
static void
reference_queue_proccess (MonoReferenceQueue *queue)
{
RefQueueEntry **iter = &queue->queue;
RefQueueEntry *entry;
while ((entry = *iter)) {
if (queue->should_be_deleted || !mono_gchandle_get_target_internal (entry->gchandle)) {
mono_gchandle_free_internal (entry->gchandle);
ref_list_remove_element (iter, entry);
queue->callback (entry->user_data);
g_free (entry);
} else {
iter = &entry->next;
}
}
}
static void
reference_queue_proccess_all (void)
{
MonoReferenceQueue **iter;
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next)
reference_queue_proccess (queue);
restart:
mono_coop_mutex_lock (&reference_queue_mutex);
for (iter = &ref_queues; *iter;) {
queue = *iter;
if (!queue->should_be_deleted) {
iter = &queue->next;
continue;
}
if (queue->queue) {
mono_coop_mutex_unlock (&reference_queue_mutex);
reference_queue_proccess (queue);
goto restart;
}
*iter = queue->next;
g_free (queue);
}
mono_coop_mutex_unlock (&reference_queue_mutex);
}
static void
mono_reference_queue_cleanup (void)
{
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next)
queue->should_be_deleted = TRUE;
reference_queue_proccess_all ();
}
static void
reference_queue_clear_for_domain (MonoDomain *domain)
{
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next) {
RefQueueEntry **iter = &queue->queue;
RefQueueEntry *entry;
while ((entry = *iter)) {
if (entry->domain == domain) {
mono_gchandle_free_internal (entry->gchandle);
ref_list_remove_element (iter, entry);
queue->callback (entry->user_data);
g_free (entry);
} else {
iter = &entry->next;
}
}
}
}
/**
* mono_gc_reference_queue_new:
* \param callback callback used when processing collected entries.
*
* Create a new reference queue used to process collected objects.
* A reference queue let you add a pair of (managed object, user data)
* using the \c mono_gc_reference_queue_add method.
*
* Once the managed object is collected \p callback will be called
* in the finalizer thread with 'user data' as argument.
*
* The callback is called from the finalizer thread without any locks held.
* When an AppDomain is unloaded, all callbacks for objects belonging to it
* will be invoked.
*
* \returns the new queue.
*/
MonoReferenceQueue*
mono_gc_reference_queue_new (mono_reference_queue_callback callback)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoReferenceQueue*, mono_gc_reference_queue_new_internal (callback));
}
MonoReferenceQueue*
mono_gc_reference_queue_new_internal (mono_reference_queue_callback callback)
{
MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
res->callback = callback;
mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init);
mono_coop_mutex_lock (&reference_queue_mutex);
res->next = ref_queues;
ref_queues = res;
mono_coop_mutex_unlock (&reference_queue_mutex);
return res;
}
/**
* mono_gc_reference_queue_add:
* \param queue the queue to add the reference to.
* \param obj the object to be watched for collection
* \param user_data parameter to be passed to the queue callback
*
* Queue an object to be watched for collection, when the \p obj is
* collected, the callback that was registered for the \p queue will
* be invoked with \p user_data as argument.
*
* \returns FALSE if the queue is scheduled to be freed.
*/
gboolean
mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (gboolean, mono_gc_reference_queue_add_internal (queue, obj, user_data));
}
gboolean
mono_gc_reference_queue_add_internal (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
{
RefQueueEntry *entry;
if (queue->should_be_deleted)
return FALSE;
g_assert (obj != NULL);
entry = g_new0 (RefQueueEntry, 1);
entry->user_data = user_data;
entry->domain = mono_object_domain (obj);
entry->gchandle = mono_gchandle_new_weakref_internal (obj, TRUE);
#ifndef HAVE_SGEN_GC
mono_object_register_finalizer (obj);
#endif
ref_list_push (&queue->queue, entry);
return TRUE;
}
/**
* mono_gc_reference_queue_free:
* \param queue the queue that should be freed.
*
* This operation signals that \p queue should be freed. This operation is deferred
* as it happens on the finalizer thread.
*
* After this call, no further objects can be queued. It's the responsibility of the
* caller to make sure that no further attempt to access queue will be made.
*/
void
mono_gc_reference_queue_free (MonoReferenceQueue *queue)
{
queue->should_be_deleted = TRUE;
}
MonoObjectHandle
mono_gc_alloc_handle_pinned_obj (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_pinned_obj (vtable, size));
}
MonoObjectHandle
mono_gc_alloc_handle_obj (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_obj (vtable, size));
}
MonoArrayHandle
mono_gc_alloc_handle_vector (MonoVTable *vtable, gsize size, gsize max_length)
{
return MONO_HANDLE_NEW (MonoArray, mono_gc_alloc_vector (vtable, size, max_length));
}
MonoArrayHandle
mono_gc_alloc_handle_array (MonoVTable *vtable, gsize size, gsize max_length, gsize bounds_size)
{
return MONO_HANDLE_NEW (MonoArray, mono_gc_alloc_array (vtable, size, max_length, bounds_size));
}
MonoStringHandle
mono_gc_alloc_handle_string (MonoVTable *vtable, gsize size, gint32 len)
{
return MONO_HANDLE_NEW (MonoString, mono_gc_alloc_string (vtable, size, len));
}
MonoObjectHandle
mono_gc_alloc_handle_mature (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_mature (vtable, size));
}
void
mono_gc_register_object_with_weak_fields (MonoObjectHandle obj)
{
mono_gc_register_obj_with_weak_fields (MONO_HANDLE_RAW (obj));
}
/**
* mono_gc_wbarrier_object_copy_handle:
*
* Write barrier to call when \p obj is the result of a clone or copy of an object.
*/
void
mono_gc_wbarrier_object_copy_handle (MonoObjectHandle obj, MonoObjectHandle src)
{
mono_gc_wbarrier_object_copy_internal (MONO_HANDLE_RAW (obj), MONO_HANDLE_RAW (src));
}
| /**
* \file
* GC icalls.
*
* Author: Paolo Molaro <[email protected]>
*
* Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2012 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 <glib.h>
#include <string.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/domain-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/threads-types.h>
#include <mono/sgen/sgen-conf.h>
#include <mono/sgen/sgen-gc.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
#include <mono/utils/mono-os-semaphore.h>
#include <mono/utils/mono-memory-model.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/dtrace.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-coop.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-coop-semaphore.h>
#include <mono/utils/hazard-pointer.h>
#include <mono/utils/w32api.h>
#include <mono/utils/unlocked.h>
#include <mono/utils/mono-os-wait.h>
#include <mono/utils/mono-lazy-init.h>
#ifndef HOST_WIN32
#include <pthread.h>
#endif
#include "external-only.h"
#include "icall-decl.h"
#if _MSC_VER
#pragma warning(disable:4312) // FIXME pointer cast to different size
#endif
typedef struct DomainFinalizationReq {
gint32 ref;
MonoDomain *domain;
MonoCoopSem done;
} DomainFinalizationReq;
static gboolean gc_disabled;
static gboolean finalizing_root_domain;
gboolean mono_log_finalizers;
gboolean mono_do_not_finalize;
static volatile gboolean suspend_finalizers;
gchar **mono_do_not_finalize_class_names ;
#define mono_finalizer_lock() mono_coop_mutex_lock (&finalizer_mutex)
#define mono_finalizer_unlock() mono_coop_mutex_unlock (&finalizer_mutex)
static MonoCoopMutex finalizer_mutex;
static MonoCoopMutex reference_queue_mutex;
static mono_lazy_init_t reference_queue_mutex_inited = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
static GSList *domains_to_finalize;
static gboolean finalizer_thread_exited;
/* Uses finalizer_mutex */
static MonoCoopCond exited_cond;
static MonoInternalThread *gc_thread;
#ifndef HOST_WASM
static RuntimeInvokeFunction finalize_runtime_invoke;
#endif
/*
* This must be a GHashTable, since these objects can't be finalized
* if the hashtable contains a GC visible reference to them.
*/
static GHashTable *finalizable_objects_hash;
static mono_mutex_t finalizable_objects_hash_lock;
#ifdef TARGET_WIN32
static HANDLE pending_done_event;
#else
static gboolean pending_done;
static MonoCoopCond pending_done_cond;
static MonoCoopMutex pending_done_mutex;
#endif
#define finalizers_lock() mono_os_mutex_lock (&finalizable_objects_hash_lock);
#define finalizers_unlock() mono_os_mutex_unlock (&finalizable_objects_hash_lock);
static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
static void reference_queue_proccess_all (void);
static void mono_reference_queue_cleanup (void);
static void reference_queue_clear_for_domain (MonoDomain *domain);
static void mono_runtime_do_background_work (void);
static MonoThreadInfoWaitRet
guarded_wait (MonoThreadHandle *thread_handle, guint32 timeout, gboolean alertable)
{
MonoThreadInfoWaitRet result;
MONO_ENTER_GC_SAFE;
result = mono_thread_info_wait_one_handle (thread_handle, timeout, alertable);
MONO_EXIT_GC_SAFE;
return result;
}
typedef struct {
MonoCoopCond *cond;
MonoCoopMutex *mutex;
} BreakCoopAlertableWaitUD;
static void
break_coop_alertable_wait (gpointer user_data)
{
BreakCoopAlertableWaitUD *ud = (BreakCoopAlertableWaitUD*)user_data;
mono_coop_mutex_lock (ud->mutex);
mono_coop_cond_signal (ud->cond);
mono_coop_mutex_unlock (ud->mutex);
g_free (ud);
}
/*
* coop_cond_timedwait_alertable:
*
* Wait on COND/MUTEX. If ALERTABLE is non-null, the wait can be interrupted.
* In that case, *ALERTABLE will be set to TRUE, and 0 is returned.
*/
static gint
coop_cond_timedwait_alertable (MonoCoopCond *cond, MonoCoopMutex *mutex, guint32 timeout_ms, gboolean *alertable)
{
BreakCoopAlertableWaitUD *ud;
int res;
if (alertable) {
ud = g_new0 (BreakCoopAlertableWaitUD, 1);
ud->cond = cond;
ud->mutex = mutex;
mono_thread_info_install_interrupt (break_coop_alertable_wait, ud, alertable);
if (*alertable) {
g_free (ud);
return 0;
}
}
res = mono_coop_cond_timedwait (cond, mutex, timeout_ms);
if (alertable) {
mono_thread_info_uninstall_interrupt (alertable);
if (*alertable)
return 0;
else {
/* the interrupt token has not been taken by another
* thread, so it's our responsability to free it up. */
g_free (ud);
}
}
return res;
}
/*
* actually, we might want to queue the finalize requests in a separate thread,
* but we need to be careful about the execution domain of the thread...
*/
void
mono_gc_run_finalize (void *obj, void *data)
{
ERROR_DECL (error);
MonoObject *exc = NULL;
MonoObject *o;
#ifndef HAVE_SGEN_GC
MonoObject *o2;
#endif
MonoMethod* finalizer = NULL;
MonoDomain *caller_domain = mono_domain_get ();
// This function is called from the innards of the GC, so our best alternative for now is to do polling here
mono_threads_safepoint ();
o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
const char *o_ns = m_class_get_name_space (mono_object_class (o));
const char *o_name = m_class_get_name (mono_object_class (o));
if (mono_do_not_finalize) {
if (!mono_do_not_finalize_class_names)
return;
size_t namespace_len = strlen (o_ns);
for (int i = 0; mono_do_not_finalize_class_names [i]; ++i) {
const char *name = mono_do_not_finalize_class_names [i];
if (strncmp (name, o_ns, namespace_len))
break;
if (name [namespace_len] != '.')
break;
if (strcmp (name + namespace_len + 1, o_name))
break;
return;
}
}
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_DEBUG, "<%s at %p> Starting finalizer checks.", o_name, o);
if (suspend_finalizers)
return;
#ifndef HAVE_SGEN_GC
finalizers_lock ();
o2 = (MonoObject *)g_hash_table_lookup (finalizable_objects_hash, o);
finalizers_unlock ();
if (!o2)
/* Already finalized somehow */
return;
#endif
/* make sure the finalizer is not called again if the object is resurrected */
object_register_finalizer ((MonoObject *)obj, NULL);
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Registered finalizer as processed.", o_name, o);
if (o->vtable->klass == mono_defaults.internal_thread_class) {
MonoInternalThread *t = (MonoInternalThread*)o;
if (mono_gc_is_finalizer_internal_thread (t))
/* Avoid finalizing ourselves */
return;
}
if (m_class_get_image (mono_object_class (o)) == mono_defaults.corlib && !strcmp (o_name, "DynamicMethod") && finalizing_root_domain) {
/*
* These can't be finalized during unloading/shutdown, since that would
* free the native code which can still be referenced by other
* finalizers.
* FIXME: This is not perfect, objects dying at the same time as
* dynamic methods can still reference them even when !shutdown.
*/
return;
}
if (mono_runtime_get_no_exec ())
return;
/* speedup later... and use a timeout */
/* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
/* Use _internal here, since this thread can enter a doomed appdomain */
mono_domain_set_internal_with_options (mono_object_domain (o), TRUE);
/* delegates that have a native function pointer allocated are
* registered for finalization, but they don't have a Finalize
* method, because in most cases it's not needed and it's just a waste.
*/
if (m_class_is_delegate (mono_object_class (o))) {
MonoDelegate* del = (MonoDelegate*)o;
if (del->delegate_trampoline)
mono_delegate_free_ftnptr ((MonoDelegate*)o);
mono_domain_set_internal_with_options (caller_domain, TRUE);
return;
}
finalizer = mono_class_get_finalizer (o->vtable->klass);
/* If object has a CCW but has no finalizer, it was only
* registered for finalization in order to free the CCW.
* Else it needs the regular finalizer run.
* FIXME: what to do about ressurection and suppression
* of finalizer on object with CCW.
*/
if (mono_marshal_free_ccw (o) && !finalizer) {
mono_domain_set_internal_with_options (caller_domain, TRUE);
return;
}
/*
* To avoid the locking plus the other overhead of mono_runtime_invoke_checked (),
* create and precompile a wrapper which calls the finalize method using
* a CALLVIRT.
*/
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Compiling finalizer.", o_name, o);
#ifndef HOST_WASM
if (!finalize_runtime_invoke) {
MonoMethod *finalize_method = mono_class_get_method_from_name_checked (mono_defaults.object_class, "Finalize", 0, 0, error);
mono_error_assert_ok (error);
MonoMethod *invoke = mono_marshal_get_runtime_invoke (finalize_method, TRUE);
finalize_runtime_invoke = (RuntimeInvokeFunction)mono_compile_method_checked (invoke, error);
mono_error_assert_ok (error); /* expect this not to fail */
}
RuntimeInvokeFunction runtime_invoke = finalize_runtime_invoke;
#endif
mono_runtime_class_init_full (o->vtable, error);
goto_if_nok (error, unhandled_error);
if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size_internal (o),
o_ns, o_name);
}
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Calling finalizer.", o_name, o);
MONO_PROFILER_RAISE (gc_finalizing_object, (o));
#ifdef HOST_WASM
if (finalizer) { // null finalizers work fine when using the vcall invoke as Object has an empty one
gpointer params [1];
params [0] = NULL;
mono_runtime_try_invoke (finalizer, o, params, &exc, error);
}
#else
runtime_invoke (o, NULL, &exc, NULL);
#endif
MONO_PROFILER_RAISE (gc_finalized_object, (o));
if (mono_log_finalizers)
g_log ("mono-gc-finalizers", G_LOG_LEVEL_MESSAGE, "<%s at %p> Returned from finalizer.", o_name, o);
unhandled_error:
if (!is_ok (error))
exc = (MonoObject*)mono_error_convert_to_exception (error);
if (exc)
mono_thread_internal_unhandled_exception (exc);
mono_domain_set_internal_with_options (caller_domain, TRUE);
}
/*
* Some of our objects may point to a different address than the address returned by GC_malloc()
* (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
* This also means that in the callback we need to adjust the pointer to get back the real
* MonoObject*.
* We also need to be consistent in the use of the GC_debug* variants of malloc and register_finalizer,
* since that, too, can cause the underlying pointer to be offset.
*/
static void
object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
{
g_assert (obj != NULL);
#if HAVE_BOEHM_GC
finalizers_lock ();
if (callback)
g_hash_table_insert (finalizable_objects_hash, obj, obj);
else
g_hash_table_remove (finalizable_objects_hash, obj);
finalizers_unlock ();
mono_gc_register_for_finalization (obj, callback);
#elif defined(HAVE_SGEN_GC)
mono_gc_register_for_finalization (obj, callback);
#endif
}
/**
* mono_object_register_finalizer:
* \param obj object to register
*
* Records that object \p obj has a finalizer, this will call the
* Finalize method when the garbage collector disposes the object.
*
*/
void
mono_object_register_finalizer_handle (MonoObjectHandle obj)
{
/* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_handle_class (obj)->name_space, mono_handle_class (obj)->name); */
object_register_finalizer (MONO_HANDLE_RAW (obj), mono_gc_run_finalize);
}
static void
mono_object_unregister_finalizer_handle (MonoObjectHandle obj)
{
/* g_print ("Unregistered finalizer on %p %s.%s\n", obj, mono_handle_class (obj)->name_space, mono_handle_class (obj)->name); */
object_register_finalizer (MONO_HANDLE_RAW (obj), NULL);
}
void
mono_object_register_finalizer (MonoObject *obj)
{
/* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
object_register_finalizer (obj, mono_gc_run_finalize);
}
/**
* mono_domain_finalize:
* \param domain the domain to finalize
* \param timeout msecs to wait for the finalization to complete, \c -1 to wait indefinitely
*
* Request finalization of all finalizable objects inside \p domain. Wait
* \p timeout msecs for the finalization to complete.
*
* \returns TRUE if succeeded, FALSE if there was a timeout
*/
gboolean
mono_domain_finalize (MonoDomain *domain, guint32 timeout)
{
DomainFinalizationReq *req;
MonoInternalThread *thread = mono_thread_internal_current ();
gint res;
gboolean ret;
gint64 start;
if (mono_thread_internal_current () == gc_thread)
/* We are called from inside a finalizer, not much we can do here */
return FALSE;
/*
* No need to create another thread 'cause the finalizer thread
* is still working and will take care of running the finalizers
*/
if (gc_disabled)
return TRUE;
/* We don't support domain finalization without a GC */
if (mono_gc_is_null ())
return FALSE;
mono_gc_collect (mono_gc_max_generation ());
req = g_new0 (DomainFinalizationReq, 1);
req->ref = 2;
req->domain = domain;
mono_coop_sem_init (&req->done, 0);
if (domain == mono_get_root_domain ())
finalizing_root_domain = TRUE;
mono_finalizer_lock ();
domains_to_finalize = g_slist_append (domains_to_finalize, req);
mono_finalizer_unlock ();
/* Tell the finalizer thread to finalize this appdomain */
mono_gc_finalize_notify ();
if (timeout == -1)
timeout = MONO_INFINITE_WAIT;
if (timeout != MONO_INFINITE_WAIT)
start = mono_msec_ticks ();
ret = TRUE;
for (;;) {
if (timeout == MONO_INFINITE_WAIT) {
res = mono_coop_sem_wait (&req->done, MONO_SEM_FLAGS_ALERTABLE);
} else {
gint64 elapsed = mono_msec_ticks () - start;
if (elapsed >= timeout) {
ret = FALSE;
break;
}
res = mono_coop_sem_timedwait (&req->done, timeout - elapsed, MONO_SEM_FLAGS_ALERTABLE);
}
if (res == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
break;
} else if (res == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
if ((thread->state & (ThreadState_AbortRequested | ThreadState_SuspendRequested)) != 0) {
ret = FALSE;
break;
}
} else if (res == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
ret = FALSE;
break;
} else {
g_error ("%s: unknown result %d", __func__, res);
}
}
if (!ret) {
/* Try removing the req from domains_to_finalize:
* - if it's not found: the domain is being finalized,
* so we the ref count is already decremented
* - if it's found: the domain is not yet being finalized,
* so we can safely decrement the ref */
gboolean found;
mono_finalizer_lock ();
found = g_slist_index (domains_to_finalize, req) != -1;
if (found)
domains_to_finalize = g_slist_remove (domains_to_finalize, req);
mono_finalizer_unlock ();
if (found) {
/* We have to decrement it wherever we
* remove it from domains_to_finalize */
if (mono_atomic_dec_i32 (&req->ref) != 1)
g_error ("%s: req->ref should be 1, as we are the first one to decrement it", __func__);
}
goto done;
}
done:
if (mono_atomic_dec_i32 (&req->ref) == 0) {
mono_coop_sem_destroy (&req->done);
g_free (req);
}
return ret;
}
void
ves_icall_System_GC_InternalCollect (int generation)
{
mono_gc_collect (generation);
}
gint64
ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
{
if (forceCollection)
mono_gc_collect (mono_gc_max_generation ());
return mono_gc_get_used_size ();
}
void
ves_icall_System_GC_GetGCMemoryInfo (
gint64 *high_memory_load_threshold_bytes,
gint64 *memory_load_bytes,
gint64 *total_available_memory_bytes,
gint64 *total_committed_bytes,
gint64 *heap_size_bytes,
gint64 *fragmented_bytes)
{
mono_gc_get_gcmemoryinfo (high_memory_load_threshold_bytes, memory_load_bytes, total_available_memory_bytes, total_committed_bytes, heap_size_bytes, fragmented_bytes);
}
void
ves_icall_System_GC_ReRegisterForFinalize (MonoObjectHandle obj, MonoError *error)
{
MONO_CHECK_ARG_NULL_HANDLE (obj,);
mono_object_register_finalizer_handle (obj);
}
void
ves_icall_System_GC_SuppressFinalize (MonoObjectHandle obj, MonoError *error)
{
MONO_CHECK_ARG_NULL_HANDLE (obj,);
/* delegates have no finalizers, but we register them to deal with the
* unmanaged->managed trampoline. We don't let the user suppress it
* otherwise we'd leak it.
*/
if (m_class_is_delegate (mono_handle_class (obj)))
return;
/* FIXME: Need to handle case where obj has COM Callable Wrapper
* generated for it that needs cleaned up, but user wants to suppress
* their derived object finalizer. */
mono_object_unregister_finalizer_handle (obj);
}
void
ves_icall_System_GC_WaitForPendingFinalizers (void)
{
if (mono_gc_is_null ())
return;
if (!mono_gc_pending_finalizers ())
return;
if (mono_thread_internal_current () == gc_thread)
/* Avoid deadlocks */
return;
/*
If the finalizer thread is not live, lets pretend no finalizers are pending since the current thread might
be the one responsible for starting it up.
*/
if (gc_thread == NULL)
return;
#ifdef TARGET_WIN32
ResetEvent (pending_done_event);
mono_gc_finalize_notify ();
/* g_print ("Waiting for pending finalizers....\n"); */
mono_coop_win32_wait_for_single_object_ex (pending_done_event, INFINITE, TRUE);
/* g_print ("Done pending....\n"); */
#else
gboolean alerted = FALSE;
mono_coop_mutex_lock (&pending_done_mutex);
pending_done = FALSE;
mono_gc_finalize_notify ();
while (!pending_done) {
coop_cond_timedwait_alertable (&pending_done_cond, &pending_done_mutex, MONO_INFINITE_WAIT, &alerted);
if (alerted)
break;
}
mono_coop_mutex_unlock (&pending_done_mutex);
#endif
}
void
ves_icall_System_GC_register_ephemeron_array (MonoObjectHandle array, MonoError *error)
{
if (!mono_gc_ephemeron_array_add (MONO_HANDLE_RAW (array)))
mono_error_set_out_of_memory (error, "");
}
MonoObjectHandle
ves_icall_System_GC_get_ephemeron_tombstone (MonoError *error)
{
return MONO_HANDLE_NEW (MonoObject, mono_domain_get ()->ephemeron_tombstone);
}
MonoGCHandle
ves_icall_System_GCHandle_InternalAlloc (MonoObjectHandle obj, gint32 type, MonoError *error)
{
MonoGCHandle handle = NULL;
switch (type) {
case HANDLE_WEAK:
handle = mono_gchandle_new_weakref_from_handle (obj);
break;
case HANDLE_WEAK_TRACK:
handle = mono_gchandle_new_weakref_from_handle_track_resurrection (obj);
break;
case HANDLE_NORMAL:
handle = mono_gchandle_from_handle (obj, FALSE);
break;
case HANDLE_PINNED:
handle = mono_gchandle_from_handle (obj, TRUE);
break;
default:
g_assert_not_reached ();
}
return handle;
}
void
ves_icall_System_GCHandle_InternalFree (MonoGCHandle handle, MonoError *error)
{
mono_gchandle_free_internal (handle);
}
MonoObjectHandle
ves_icall_System_GCHandle_InternalGet (MonoGCHandle handle, MonoError *error)
{
return mono_gchandle_get_target_handle (handle);
}
void
ves_icall_System_GCHandle_InternalSet (MonoGCHandle handle, MonoObjectHandle obj, MonoError *error)
{
mono_gchandle_set_target_handle (handle, obj);
}
static MonoCoopSem finalizer_sem;
static volatile gboolean finished;
/*
* mono_gc_finalize_notify:
*
* Notify the finalizer thread that finalizers etc.
* are available to be processed.
* This is async signal safe.
*/
void
mono_gc_finalize_notify (void)
{
#ifdef DEBUG
g_message ( "%s: prodding finalizer", __func__);
#endif
if (mono_gc_is_null ())
return;
#if defined(HOST_WASI)
// TODO: Schedule the background job on WASI. Threads aren't yet supported in this build.
#elif defined(HOST_WASM)
mono_threads_schedule_background_job (mono_runtime_do_background_work);
#else
mono_coop_sem_post (&finalizer_sem);
#endif
}
/*
This is the number of entries allowed in the hazard free queue before
we explicitly cycle the finalizer thread to trigger pumping the queue.
It was picked empirically by running the corlib test suite in a stress
scenario where all hazard entries are queued.
In this extreme scenario we double the number of times we cycle the finalizer
thread compared to just GC calls.
Entries are usually in the order of 100's of bytes each, so we're limiting
floating garbage to be in the order of a dozen kb.
*/
static gboolean finalizer_thread_pulsed;
#define HAZARD_QUEUE_OVERFLOW_SIZE 20
static void
hazard_free_queue_is_too_big (size_t size)
{
if (size < HAZARD_QUEUE_OVERFLOW_SIZE)
return;
if (finalizer_thread_pulsed || mono_atomic_cas_i32 (&finalizer_thread_pulsed, TRUE, FALSE))
return;
mono_gc_finalize_notify ();
}
static void
hazard_free_queue_pump (void)
{
mono_thread_hazardous_try_free_all ();
finalizer_thread_pulsed = FALSE;
}
#ifdef HAVE_BOEHM_GC
static void
collect_objects (gpointer key, gpointer value, gpointer user_data)
{
GPtrArray *arr = (GPtrArray*)user_data;
g_ptr_array_add (arr, key);
}
#endif
/*
* finalize_domain_objects:
*
* Run the finalizers of all finalizable objects in req->domain.
*/
static void
finalize_domain_objects (void)
{
DomainFinalizationReq *req = NULL;
MonoDomain *domain;
if (UnlockedReadPointer ((gpointer volatile*)&domains_to_finalize)) {
mono_finalizer_lock ();
if (domains_to_finalize) {
req = (DomainFinalizationReq *)domains_to_finalize->data;
domains_to_finalize = g_slist_remove (domains_to_finalize, req);
}
mono_finalizer_unlock ();
}
if (!req)
return;
domain = req->domain;
/* Process finalizers which are already in the queue */
mono_gc_invoke_finalizers ();
#ifdef HAVE_BOEHM_GC
while (g_hash_table_size (finalizable_objects_hash) > 0) {
int i;
GPtrArray *objs;
/*
* Since the domain is unloading, nobody is allowed to put
* new entries into the hash table. But finalize_object might
* remove entries from the hash table, so we make a copy.
*/
objs = g_ptr_array_new ();
g_hash_table_foreach (finalizable_objects_hash, collect_objects, objs);
/* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
for (i = 0; i < objs->len; ++i) {
MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
/* FIXME: Avoid finalizing threads, etc */
mono_gc_run_finalize (o, 0);
}
g_ptr_array_free (objs, TRUE);
}
#elif defined(HAVE_SGEN_GC)
mono_gc_finalize_domain (domain);
mono_gc_invoke_finalizers ();
#endif
/* cleanup the reference queue */
reference_queue_clear_for_domain (domain);
/* printf ("DONE.\n"); */
mono_coop_sem_post (&req->done);
if (mono_atomic_dec_i32 (&req->ref) == 0) {
/* mono_domain_finalize already returned, and
* doesn't hold a reference to req anymore. */
mono_coop_sem_destroy (&req->done);
g_free (req);
}
}
static void
mono_runtime_do_background_work (void)
{
mono_threads_perform_thread_dump ();
mono_threads_exiting ();
finalize_domain_objects ();
MONO_PROFILER_RAISE (gc_finalizing, ());
/* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
* before the domain is unloaded.
*/
mono_gc_invoke_finalizers ();
MONO_PROFILER_RAISE (gc_finalized, ());
mono_threads_join_threads ();
reference_queue_proccess_all ();
hazard_free_queue_pump ();
}
static gsize WINAPI
finalizer_thread (gpointer unused)
{
gboolean wait = TRUE;
gboolean did_init_from_native = FALSE;
mono_thread_set_name_constant_ignore_error (mono_thread_internal_current (), "Finalizer", MonoSetThreadNameFlag_None);
/* Register a hazard free queue pump callback */
mono_hazard_pointer_install_free_queue_size_callback (hazard_free_queue_is_too_big);
while (!finished) {
/* Wait to be notified that there's at least one
* finaliser to run
*/
g_assert (mono_domain_get () == mono_get_root_domain ());
mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NO_GC);
if (wait) {
/* An alertable wait is required so this thread can be suspended on windows */
mono_coop_sem_wait (&finalizer_sem, MONO_SEM_FLAGS_ALERTABLE);
}
wait = TRUE;
mono_thread_info_set_flags (MONO_THREAD_INFO_FLAGS_NONE);
/* The Finalizer thread doesn't initialize during creation because base managed
libraries may not be loaded yet. However, the first time the Finalizer is
to run managed finalizer, we can take this opportunity to initialize. */
if (!did_init_from_native) {
did_init_from_native = TRUE;
mono_thread_init_from_native ();
}
mono_runtime_do_background_work ();
/* Avoid posting the pending done event until there are pending finalizers */
if (mono_coop_sem_timedwait (&finalizer_sem, 0, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
/* Don't wait again at the start of the loop */
wait = FALSE;
} else {
#ifdef TARGET_WIN32
SetEvent (pending_done_event);
#else
mono_coop_mutex_lock (&pending_done_mutex);
pending_done = TRUE;
mono_coop_cond_signal (&pending_done_cond);
mono_coop_mutex_unlock (&pending_done_mutex);
#endif
}
}
/* If the initialization from native was done, do the clean up */
if (did_init_from_native) {
mono_thread_cleanup_from_native ();
}
mono_finalizer_lock ();
finalizer_thread_exited = TRUE;
mono_coop_cond_signal (&exited_cond);
mono_finalizer_unlock ();
return 0;
}
static void
init_finalizer_thread (void)
{
ERROR_DECL (error);
gc_thread = mono_thread_create_internal ((MonoThreadStart)finalizer_thread, NULL, MONO_THREAD_CREATE_FLAGS_NONE, error);
mono_error_assert_ok (error);
}
/**
* mono_gc_init_finalizer_thread:
*
* If the runtime is compiled with --with-lazy-gc-thread-creation, this
* function must be called by embedders to create the finalizer. Otherwise, the
* function does nothing and the runtime creates the finalizer thread
* automatically.
*/
void
mono_gc_init_finalizer_thread (void)
{
#ifndef LAZY_GC_THREAD_CREATION
/* do nothing */
#else
MONO_ENTER_GC_UNSAFE;
init_finalizer_thread ();
MONO_EXIT_GC_UNSAFE;
#endif
}
static void
reference_queue_mutex_init (void)
{
mono_coop_mutex_init_recursive (&reference_queue_mutex);
}
void
mono_gc_init (void)
{
mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init);
mono_coop_mutex_init_recursive (&finalizer_mutex);
mono_os_mutex_init_recursive (&finalizable_objects_hash_lock);
finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
mono_counters_register ("Minor GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.minor_gc_count);
mono_counters_register ("Major GC collections", MONO_COUNTER_GC | MONO_COUNTER_INT, &mono_gc_stats.major_gc_count);
mono_counters_register ("Minor GC time", MONO_COUNTER_GC | MONO_COUNTER_ULONG | MONO_COUNTER_TIME, &mono_gc_stats.minor_gc_time);
mono_counters_register ("Major GC time", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &mono_gc_stats.major_gc_time);
mono_counters_register ("Major GC time concurrent", MONO_COUNTER_GC | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &mono_gc_stats.major_gc_time_concurrent);
mono_gc_base_init ();
if (mono_gc_is_disabled ()) {
gc_disabled = TRUE;
return;
}
#ifdef TARGET_WIN32
pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
g_assert (pending_done_event);
#else
mono_coop_cond_init (&pending_done_cond);
mono_coop_mutex_init (&pending_done_mutex);
#endif
mono_coop_cond_init (&exited_cond);
mono_coop_sem_init (&finalizer_sem, 0);
#ifndef LAZY_GC_THREAD_CREATION
if (!mono_runtime_get_no_exec ())
init_finalizer_thread ();
#endif
}
gboolean
mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
{
return thread == gc_thread;
}
/**
* mono_gc_is_finalizer_thread:
* \param thread the thread to test.
*
* In Mono objects are finalized asynchronously on a separate thread.
* This routine tests whether the \p thread argument represents the
* finalization thread.
*
* \returns TRUE if \p thread is the finalization thread.
*/
gboolean
mono_gc_is_finalizer_thread (MonoThread *thread)
{
return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
}
#if defined(__MACH__)
static pthread_t mach_exception_thread;
void
mono_gc_register_mach_exception_thread (pthread_t thread)
{
mach_exception_thread = thread;
}
pthread_t
mono_gc_get_mach_exception_thread (void)
{
return mach_exception_thread;
}
#endif
static MonoReferenceQueue *ref_queues;
static void
ref_list_remove_element (RefQueueEntry **prev, RefQueueEntry *element)
{
do {
/* Guard if head is changed concurrently. */
while (*prev != element)
prev = &(*prev)->next;
} while (prev && mono_atomic_cas_ptr ((volatile gpointer *)prev, element->next, element) != element);
}
static void
ref_list_push (RefQueueEntry **head, RefQueueEntry *value)
{
RefQueueEntry *current;
do {
current = *head;
value->next = current;
STORE_STORE_FENCE; /*Must make sure the previous store is visible before the CAS. */
} while (mono_atomic_cas_ptr ((volatile gpointer *)head, value, current) != current);
}
static void
reference_queue_proccess (MonoReferenceQueue *queue)
{
RefQueueEntry **iter = &queue->queue;
RefQueueEntry *entry;
while ((entry = *iter)) {
if (queue->should_be_deleted || !mono_gchandle_get_target_internal (entry->gchandle)) {
mono_gchandle_free_internal (entry->gchandle);
ref_list_remove_element (iter, entry);
queue->callback (entry->user_data);
g_free (entry);
} else {
iter = &entry->next;
}
}
}
static void
reference_queue_proccess_all (void)
{
MonoReferenceQueue **iter;
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next)
reference_queue_proccess (queue);
restart:
mono_coop_mutex_lock (&reference_queue_mutex);
for (iter = &ref_queues; *iter;) {
queue = *iter;
if (!queue->should_be_deleted) {
iter = &queue->next;
continue;
}
if (queue->queue) {
mono_coop_mutex_unlock (&reference_queue_mutex);
reference_queue_proccess (queue);
goto restart;
}
*iter = queue->next;
g_free (queue);
}
mono_coop_mutex_unlock (&reference_queue_mutex);
}
static void
mono_reference_queue_cleanup (void)
{
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next)
queue->should_be_deleted = TRUE;
reference_queue_proccess_all ();
}
static void
reference_queue_clear_for_domain (MonoDomain *domain)
{
MonoReferenceQueue *queue = ref_queues;
for (; queue; queue = queue->next) {
RefQueueEntry **iter = &queue->queue;
RefQueueEntry *entry;
while ((entry = *iter)) {
if (entry->domain == domain) {
mono_gchandle_free_internal (entry->gchandle);
ref_list_remove_element (iter, entry);
queue->callback (entry->user_data);
g_free (entry);
} else {
iter = &entry->next;
}
}
}
}
/**
* mono_gc_reference_queue_new:
* \param callback callback used when processing collected entries.
*
* Create a new reference queue used to process collected objects.
* A reference queue let you add a pair of (managed object, user data)
* using the \c mono_gc_reference_queue_add method.
*
* Once the managed object is collected \p callback will be called
* in the finalizer thread with 'user data' as argument.
*
* The callback is called from the finalizer thread without any locks held.
* When an AppDomain is unloaded, all callbacks for objects belonging to it
* will be invoked.
*
* \returns the new queue.
*/
MonoReferenceQueue*
mono_gc_reference_queue_new (mono_reference_queue_callback callback)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (MonoReferenceQueue*, mono_gc_reference_queue_new_internal (callback));
}
MonoReferenceQueue*
mono_gc_reference_queue_new_internal (mono_reference_queue_callback callback)
{
MonoReferenceQueue *res = g_new0 (MonoReferenceQueue, 1);
res->callback = callback;
mono_lazy_initialize (&reference_queue_mutex_inited, reference_queue_mutex_init);
mono_coop_mutex_lock (&reference_queue_mutex);
res->next = ref_queues;
ref_queues = res;
mono_coop_mutex_unlock (&reference_queue_mutex);
return res;
}
/**
* mono_gc_reference_queue_add:
* \param queue the queue to add the reference to.
* \param obj the object to be watched for collection
* \param user_data parameter to be passed to the queue callback
*
* Queue an object to be watched for collection, when the \p obj is
* collected, the callback that was registered for the \p queue will
* be invoked with \p user_data as argument.
*
* \returns FALSE if the queue is scheduled to be freed.
*/
gboolean
mono_gc_reference_queue_add (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
{
MONO_EXTERNAL_ONLY_GC_UNSAFE (gboolean, mono_gc_reference_queue_add_internal (queue, obj, user_data));
}
gboolean
mono_gc_reference_queue_add_internal (MonoReferenceQueue *queue, MonoObject *obj, void *user_data)
{
RefQueueEntry *entry;
if (queue->should_be_deleted)
return FALSE;
g_assert (obj != NULL);
entry = g_new0 (RefQueueEntry, 1);
entry->user_data = user_data;
entry->domain = mono_object_domain (obj);
entry->gchandle = mono_gchandle_new_weakref_internal (obj, TRUE);
#ifndef HAVE_SGEN_GC
mono_object_register_finalizer (obj);
#endif
ref_list_push (&queue->queue, entry);
return TRUE;
}
/**
* mono_gc_reference_queue_free:
* \param queue the queue that should be freed.
*
* This operation signals that \p queue should be freed. This operation is deferred
* as it happens on the finalizer thread.
*
* After this call, no further objects can be queued. It's the responsibility of the
* caller to make sure that no further attempt to access queue will be made.
*/
void
mono_gc_reference_queue_free (MonoReferenceQueue *queue)
{
queue->should_be_deleted = TRUE;
}
MonoObjectHandle
mono_gc_alloc_handle_pinned_obj (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_pinned_obj (vtable, size));
}
MonoObjectHandle
mono_gc_alloc_handle_obj (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_obj (vtable, size));
}
MonoArrayHandle
mono_gc_alloc_handle_vector (MonoVTable *vtable, gsize size, gsize max_length)
{
return MONO_HANDLE_NEW (MonoArray, mono_gc_alloc_vector (vtable, size, max_length));
}
MonoArrayHandle
mono_gc_alloc_handle_array (MonoVTable *vtable, gsize size, gsize max_length, gsize bounds_size)
{
return MONO_HANDLE_NEW (MonoArray, mono_gc_alloc_array (vtable, size, max_length, bounds_size));
}
MonoStringHandle
mono_gc_alloc_handle_string (MonoVTable *vtable, gsize size, gint32 len)
{
return MONO_HANDLE_NEW (MonoString, mono_gc_alloc_string (vtable, size, len));
}
MonoObjectHandle
mono_gc_alloc_handle_mature (MonoVTable *vtable, gsize size)
{
return MONO_HANDLE_NEW (MonoObject, mono_gc_alloc_mature (vtable, size));
}
void
mono_gc_register_object_with_weak_fields (MonoObjectHandle obj)
{
mono_gc_register_obj_with_weak_fields (MONO_HANDLE_RAW (obj));
}
/**
* mono_gc_wbarrier_object_copy_handle:
*
* Write barrier to call when \p obj is the result of a clone or copy of an object.
*/
void
mono_gc_wbarrier_object_copy_handle (MonoObjectHandle obj, MonoObjectHandle src)
{
mono_gc_wbarrier_object_copy_internal (MONO_HANDLE_RAW (obj), MONO_HANDLE_RAW (src));
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/eglib/test/test.c | /*
* EGLib Unit Group/Test Runners
*
* Author:
* Aaron Bockover ([email protected])
*
* (C) 2006 Novell, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <glib.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef G_OS_WIN32
#include <winsock2.h>
#endif
#include "test.h"
extern gint global_passed, global_tests;
static gchar *last_result = NULL;
static gboolean
run_test(const Test *test, char **result_out)
{
gchar *result;
if((result = test->handler()) == NULL) {
*result_out = NULL;
return TRUE;
} else {
*result_out = result;
return FALSE;
}
}
gboolean
run_group(const Group *group, gint iterations, gboolean quiet,
gboolean time, const char *tests_to_run_s)
{
Test *tests = group->handler();
gint i, j, passed = 0, total = 0;
gdouble start_time_group, start_time_test;
gchar **tests_to_run = NULL;
if(!quiet) {
if(iterations > 1) {
printf("[%s] (%dx)\n", group->name, iterations);
} else {
printf("[%s]\n", group->name);
}
}
if(tests_to_run_s != NULL) {
tests_to_run = eg_strsplit(tests_to_run_s, ",", -1);
}
start_time_group = get_timestamp();
for(i = 0; tests[i].name != NULL; i++) {
gchar *result = (char*)"";
gboolean iter_pass, run;
iter_pass = FALSE;
if(tests_to_run != NULL) {
gint j;
run = FALSE;
for(j = 0; tests_to_run[j] != NULL; j++) {
if(strcmp(tests_to_run[j], tests[i].name) == 0) {
run = TRUE;
break;
}
}
} else {
run = TRUE;
}
if(!run) {
continue;
}
total++;
if(!quiet) {
printf(" %s: ", tests[i].name);
}
start_time_test = get_timestamp();
for(j = 0; j < iterations; j++) {
iter_pass = run_test(&(tests[i]), &result);
if(!iter_pass) {
break;
}
}
if(iter_pass) {
passed++;
if(!quiet) {
if(time) {
printf("OK (%g)\n", get_timestamp() - start_time_test);
} else {
printf("OK\n");
}
}
} else {
if(!quiet) {
printf("FAILED (%s)\n", result);
}
if(last_result == result) {
last_result = NULL;
g_free(result);
}
}
}
global_passed += passed;
global_tests += total;
if(!quiet) {
gdouble pass_percentage = ((gdouble)passed / (gdouble)total) * 100.0;
if(time) {
printf(" %d / %d (%g%%, %g)\n", passed, total,
pass_percentage, get_timestamp() - start_time_group);
} else {
printf(" %d / %d (%g%%)\n", passed, total, pass_percentage);
}
}
if(tests_to_run != NULL) {
eg_strfreev(tests_to_run);
}
return passed == total;
}
RESULT
FAILED(const gchar *format, ...)
{
gchar *ret;
va_list args;
gint n;
#if !defined(HAVE_VASPRINTF) && !defined(_EGLIB_MAJOR)
/* We are linked against the real glib, no vasprintf */
g_assert_not_reached ();
return NULL;
#else
va_start(args, format);
n = g_vasprintf(&ret, format, args);
va_end(args);
if(n == -1) {
last_result = NULL;
return NULL;
}
last_result = ret;
return ret;
#endif
}
gdouble
get_timestamp (void)
{
/* FIXME: We should use g_get_current_time here */
GTimeVal res;
g_get_current_time (&res);
return res.tv_sec + (1.e-6) * res.tv_usec;
}
/*
* Duplicating code here from EGlib to avoid g_strsplit skew between
* EGLib and GLib
*/
gchar **
eg_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens)
{
gchar *string_c;
gchar *strtok_save, **vector;
gchar *token, *token_c;
gint size = 1;
size_t token_length;
g_return_val_if_fail(string != NULL, NULL);
g_return_val_if_fail(delimiter != NULL, NULL);
g_return_val_if_fail(delimiter[0] != 0, NULL);
token_length = strlen(string);
string_c = (gchar *)g_malloc(token_length + 1);
memcpy(string_c, string, token_length);
string_c[token_length] = 0;
vector = NULL;
token = (gchar *)strtok_r(string_c, delimiter, &strtok_save);
while(token != NULL) {
token_length = strlen(token);
token_c = (gchar *)g_malloc(token_length + 1);
memcpy(token_c, token, token_length);
token_c[token_length] = 0;
vector = vector == NULL ?
(gchar **)g_malloc(2 * sizeof(vector)) :
(gchar **)g_realloc(vector, (size + 1) * sizeof(vector));
vector[size - 1] = token_c;
size++;
if(max_tokens > 0 && size >= max_tokens) {
if(size > max_tokens) {
break;
}
token = strtok_save;
} else {
token = (gchar *)strtok_r(NULL, delimiter, &strtok_save);
}
}
if(vector != NULL && size > 0) {
vector[size - 1] = NULL;
}
g_free(string_c);
string_c = NULL;
return vector;
}
void
eg_strfreev (gchar **str_array)
{
gchar **orig = str_array;
if (str_array == NULL)
return;
while (*str_array != NULL){
g_free (*str_array);
str_array++;
}
g_free (orig);
}
| /*
* EGLib Unit Group/Test Runners
*
* Author:
* Aaron Bockover ([email protected])
*
* (C) 2006 Novell, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <glib.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef G_OS_WIN32
#include <winsock2.h>
#endif
#include "test.h"
extern gint global_passed, global_tests;
static gchar *last_result = NULL;
static gboolean
run_test(const Test *test, char **result_out)
{
gchar *result;
if((result = test->handler()) == NULL) {
*result_out = NULL;
return TRUE;
} else {
*result_out = result;
return FALSE;
}
}
gboolean
run_group(const Group *group, gint iterations, gboolean quiet,
gboolean time, const char *tests_to_run_s)
{
Test *tests = group->handler();
gint i, j, passed = 0, total = 0;
gdouble start_time_group, start_time_test;
gchar **tests_to_run = NULL;
if(!quiet) {
if(iterations > 1) {
printf("[%s] (%dx)\n", group->name, iterations);
} else {
printf("[%s]\n", group->name);
}
}
if(tests_to_run_s != NULL) {
tests_to_run = eg_strsplit(tests_to_run_s, ",", -1);
}
start_time_group = get_timestamp();
for(i = 0; tests[i].name != NULL; i++) {
gchar *result = (char*)"";
gboolean iter_pass, run;
iter_pass = FALSE;
if(tests_to_run != NULL) {
gint j;
run = FALSE;
for(j = 0; tests_to_run[j] != NULL; j++) {
if(strcmp(tests_to_run[j], tests[i].name) == 0) {
run = TRUE;
break;
}
}
} else {
run = TRUE;
}
if(!run) {
continue;
}
total++;
if(!quiet) {
printf(" %s: ", tests[i].name);
}
start_time_test = get_timestamp();
for(j = 0; j < iterations; j++) {
iter_pass = run_test(&(tests[i]), &result);
if(!iter_pass) {
break;
}
}
if(iter_pass) {
passed++;
if(!quiet) {
if(time) {
printf("OK (%g)\n", get_timestamp() - start_time_test);
} else {
printf("OK\n");
}
}
} else {
if(!quiet) {
printf("FAILED (%s)\n", result);
}
if(last_result == result) {
last_result = NULL;
g_free(result);
}
}
}
global_passed += passed;
global_tests += total;
if(!quiet) {
gdouble pass_percentage = ((gdouble)passed / (gdouble)total) * 100.0;
if(time) {
printf(" %d / %d (%g%%, %g)\n", passed, total,
pass_percentage, get_timestamp() - start_time_group);
} else {
printf(" %d / %d (%g%%)\n", passed, total, pass_percentage);
}
}
if(tests_to_run != NULL) {
eg_strfreev(tests_to_run);
}
return passed == total;
}
RESULT
FAILED(const gchar *format, ...)
{
gchar *ret;
va_list args;
gint n;
#if !defined(HAVE_VASPRINTF) && !defined(_EGLIB_MAJOR)
/* We are linked against the real glib, no vasprintf */
g_assert_not_reached ();
return NULL;
#else
va_start(args, format);
n = g_vasprintf(&ret, format, args);
va_end(args);
if(n == -1) {
last_result = NULL;
return NULL;
}
last_result = ret;
return ret;
#endif
}
gdouble
get_timestamp (void)
{
/* FIXME: We should use g_get_current_time here */
GTimeVal res;
g_get_current_time (&res);
return res.tv_sec + (1.e-6) * res.tv_usec;
}
/*
* Duplicating code here from EGlib to avoid g_strsplit skew between
* EGLib and GLib
*/
gchar **
eg_strsplit (const gchar *string, const gchar *delimiter, gint max_tokens)
{
gchar *string_c;
gchar *strtok_save, **vector;
gchar *token, *token_c;
gint size = 1;
size_t token_length;
g_return_val_if_fail(string != NULL, NULL);
g_return_val_if_fail(delimiter != NULL, NULL);
g_return_val_if_fail(delimiter[0] != 0, NULL);
token_length = strlen(string);
string_c = (gchar *)g_malloc(token_length + 1);
memcpy(string_c, string, token_length);
string_c[token_length] = 0;
vector = NULL;
token = (gchar *)strtok_r(string_c, delimiter, &strtok_save);
while(token != NULL) {
token_length = strlen(token);
token_c = (gchar *)g_malloc(token_length + 1);
memcpy(token_c, token, token_length);
token_c[token_length] = 0;
vector = vector == NULL ?
(gchar **)g_malloc(2 * sizeof(vector)) :
(gchar **)g_realloc(vector, (size + 1) * sizeof(vector));
vector[size - 1] = token_c;
size++;
if(max_tokens > 0 && size >= max_tokens) {
if(size > max_tokens) {
break;
}
token = strtok_save;
} else {
token = (gchar *)strtok_r(NULL, delimiter, &strtok_save);
}
}
if(vector != NULL && size > 0) {
vector[size - 1] = NULL;
}
g_free(string_c);
string_c = NULL;
return vector;
}
void
eg_strfreev (gchar **str_array)
{
gchar **orig = str_array;
if (str_array == NULL)
return;
while (*str_array != NULL){
g_free (*str_array);
str_array++;
}
g_free (orig);
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/native/libs/System.Net.Security.Native/pal_gssapi.c | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_types.h"
#include "pal_utilities.h"
#include "pal_gssapi.h"
#include <minipal/utils.h>
#if HAVE_GSSFW_HEADERS
#include <GSS/GSS.h>
#else
#if HAVE_HEIMDAL_HEADERS
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_krb5.h>
#else
#include <gssapi/gssapi_ext.h>
#include <gssapi/gssapi_krb5.h>
#endif
#endif
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#if defined(GSS_SHIM)
#include <dlfcn.h>
#include "pal_atomic.h"
#endif
c_static_assert(PAL_GSS_C_DELEG_FLAG == GSS_C_DELEG_FLAG);
c_static_assert(PAL_GSS_C_MUTUAL_FLAG == GSS_C_MUTUAL_FLAG);
c_static_assert(PAL_GSS_C_REPLAY_FLAG == GSS_C_REPLAY_FLAG);
c_static_assert(PAL_GSS_C_SEQUENCE_FLAG == GSS_C_SEQUENCE_FLAG);
c_static_assert(PAL_GSS_C_CONF_FLAG == GSS_C_CONF_FLAG);
c_static_assert(PAL_GSS_C_INTEG_FLAG == GSS_C_INTEG_FLAG);
c_static_assert(PAL_GSS_C_ANON_FLAG == GSS_C_ANON_FLAG);
c_static_assert(PAL_GSS_C_PROT_READY_FLAG == GSS_C_PROT_READY_FLAG);
c_static_assert(PAL_GSS_C_TRANS_FLAG == GSS_C_TRANS_FLAG);
c_static_assert(PAL_GSS_C_DCE_STYLE == GSS_C_DCE_STYLE);
c_static_assert(PAL_GSS_C_IDENTIFY_FLAG == GSS_C_IDENTIFY_FLAG);
c_static_assert(PAL_GSS_C_EXTENDED_ERROR_FLAG == GSS_C_EXTENDED_ERROR_FLAG);
c_static_assert(PAL_GSS_C_DELEG_POLICY_FLAG == GSS_C_DELEG_POLICY_FLAG);
c_static_assert(PAL_GSS_COMPLETE == GSS_S_COMPLETE);
c_static_assert(PAL_GSS_CONTINUE_NEEDED == GSS_S_CONTINUE_NEEDED);
#if !HAVE_GSS_SPNEGO_MECHANISM
static char gss_spnego_oid_value[] = "\x2b\x06\x01\x05\x05\x02"; // Binary representation of SPNEGO Oid (RFC 4178)
static gss_OID_desc gss_mech_spnego_OID_desc = {.length = STRING_LENGTH(gss_spnego_oid_value),
.elements = gss_spnego_oid_value};
static char gss_ntlm_oid_value[] =
"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a"; // Binary representation of NTLM OID
// (https://msdn.microsoft.com/en-us/library/cc236636.aspx)
static gss_OID_desc gss_mech_ntlm_OID_desc = {.length = STRING_LENGTH(gss_ntlm_oid_value),
.elements = gss_ntlm_oid_value};
#endif
#if defined(GSS_SHIM)
#define FOR_ALL_GSS_FUNCTIONS \
PER_FUNCTION_BLOCK(gss_accept_sec_context) \
PER_FUNCTION_BLOCK(gss_acquire_cred) \
PER_FUNCTION_BLOCK(gss_acquire_cred_with_password) \
PER_FUNCTION_BLOCK(gss_delete_sec_context) \
PER_FUNCTION_BLOCK(gss_display_name) \
PER_FUNCTION_BLOCK(gss_display_status) \
PER_FUNCTION_BLOCK(gss_import_name) \
PER_FUNCTION_BLOCK(gss_indicate_mechs) \
PER_FUNCTION_BLOCK(gss_init_sec_context) \
PER_FUNCTION_BLOCK(gss_inquire_context) \
PER_FUNCTION_BLOCK(gss_mech_krb5) \
PER_FUNCTION_BLOCK(gss_oid_equal) \
PER_FUNCTION_BLOCK(gss_release_buffer) \
PER_FUNCTION_BLOCK(gss_release_cred) \
PER_FUNCTION_BLOCK(gss_release_name) \
PER_FUNCTION_BLOCK(gss_release_oid_set) \
PER_FUNCTION_BLOCK(gss_unwrap) \
PER_FUNCTION_BLOCK(gss_wrap) \
PER_FUNCTION_BLOCK(GSS_C_NT_USER_NAME) \
PER_FUNCTION_BLOCK(GSS_C_NT_HOSTBASED_SERVICE)
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define FOR_ALL_GSS_FUNCTIONS FOR_ALL_GSS_FUNCTIONS \
PER_FUNCTION_BLOCK(gss_set_cred_option)
#endif //HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
// define indirection pointers for all functions, like
// static TYPEOF(gss_accept_sec_context)* gss_accept_sec_context_ptr;
#define PER_FUNCTION_BLOCK(fn) \
static TYPEOF(fn)* fn##_ptr;
FOR_ALL_GSS_FUNCTIONS
#undef PER_FUNCTION_BLOCK
static void* volatile s_gssLib = NULL;
// remap gss function use to use indirection pointers
#define gss_accept_sec_context(...) gss_accept_sec_context_ptr(__VA_ARGS__)
#define gss_acquire_cred(...) gss_acquire_cred_ptr(__VA_ARGS__)
#define gss_acquire_cred_with_password(...) gss_acquire_cred_with_password_ptr(__VA_ARGS__)
#define gss_delete_sec_context(...) gss_delete_sec_context_ptr(__VA_ARGS__)
#define gss_display_name(...) gss_display_name_ptr(__VA_ARGS__)
#define gss_display_status(...) gss_display_status_ptr(__VA_ARGS__)
#define gss_import_name(...) gss_import_name_ptr(__VA_ARGS__)
#define gss_indicate_mechs(...) gss_indicate_mechs_ptr(__VA_ARGS__)
#define gss_init_sec_context(...) gss_init_sec_context_ptr(__VA_ARGS__)
#define gss_inquire_context(...) gss_inquire_context_ptr(__VA_ARGS__)
#define gss_oid_equal(...) gss_oid_equal_ptr(__VA_ARGS__)
#define gss_release_buffer(...) gss_release_buffer_ptr(__VA_ARGS__)
#define gss_release_cred(...) gss_release_cred_ptr(__VA_ARGS__)
#define gss_release_name(...) gss_release_name_ptr(__VA_ARGS__)
#define gss_release_oid_set(...) gss_release_oid_set_ptr(__VA_ARGS__)
#define gss_unwrap(...) gss_unwrap_ptr(__VA_ARGS__)
#define gss_wrap(...) gss_wrap_ptr(__VA_ARGS__)
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define gss_set_cred_option(...) gss_set_cred_option_ptr(__VA_ARGS__)
#endif //HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define GSS_C_NT_USER_NAME (*GSS_C_NT_USER_NAME_ptr)
#define GSS_C_NT_HOSTBASED_SERVICE (*GSS_C_NT_HOSTBASED_SERVICE_ptr)
#define gss_mech_krb5 (*gss_mech_krb5_ptr)
#define gss_lib_name "libgssapi_krb5.so.2"
static int32_t ensure_gss_shim_initialized()
{
void* lib = dlopen(gss_lib_name, RTLD_LAZY);
if (lib == NULL) { fprintf(stderr, "Cannot load library %s \nError: %s\n", gss_lib_name, dlerror()); return -1; }
// check is someone else has opened and published s_gssLib already
if (!pal_atomic_cas_ptr(&s_gssLib, lib, NULL))
{
dlclose(lib);
}
// initialize indirection pointers for all functions, like:
// gss_accept_sec_context_ptr = (TYPEOF(gss_accept_sec_context)*)dlsym(s_gssLib, "gss_accept_sec_context");
// if (gss_accept_sec_context_ptr == NULL) { fprintf(stderr, "Cannot get symbol %s from %s \nError: %s\n", "gss_accept_sec_context", gss_lib_name, dlerror()); return -1; }
#define PER_FUNCTION_BLOCK(fn) \
fn##_ptr = (TYPEOF(fn)*)dlsym(s_gssLib, #fn); \
if (fn##_ptr == NULL) { fprintf(stderr, "Cannot get symbol " #fn " from %s \nError: %s\n", gss_lib_name, dlerror()); return -1; }
FOR_ALL_GSS_FUNCTIONS
#undef PER_FUNCTION_BLOCK
return 0;
}
#endif // GSS_SHIM
// transfers ownership of the underlying data from gssBuffer to PAL_GssBuffer
static void NetSecurityNative_MoveBuffer(gss_buffer_t gssBuffer, PAL_GssBuffer* targetBuffer)
{
assert(gssBuffer != NULL);
assert(targetBuffer != NULL);
targetBuffer->length = (uint64_t)(gssBuffer->length);
targetBuffer->data = (uint8_t*)(gssBuffer->value);
}
static uint32_t AcquireCredSpNego(uint32_t* minorStatus,
GssName* desiredName,
gss_cred_usage_t credUsage,
GssCredId** outputCredHandle)
{
assert(minorStatus != NULL);
assert(desiredName != NULL);
assert(outputCredHandle != NULL);
assert(*outputCredHandle == NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = GSS_SPNEGO_MECHANISM};
#else
gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = &gss_mech_spnego_OID_desc};
#endif
uint32_t majorStatus = gss_acquire_cred(
minorStatus, desiredName, 0, &gss_mech_spnego_OID_set_desc, credUsage, outputCredHandle, NULL, NULL);
// call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer emptyBuffer = GSS_C_EMPTY_BUFFER;
majorStatus = gss_set_cred_option(minorStatus, outputCredHandle, GSS_KRB5_CRED_NO_CI_FLAGS_X, &emptyBuffer);
}
#endif
return majorStatus;
}
uint32_t
NetSecurityNative_InitiateCredSpNego(uint32_t* minorStatus, GssName* desiredName, GssCredId** outputCredHandle)
{
return AcquireCredSpNego(minorStatus, desiredName, GSS_C_INITIATE, outputCredHandle);
}
uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
return gss_delete_sec_context(minorStatus, contextHandle, GSS_C_NO_BUFFER);
}
static uint32_t NetSecurityNative_DisplayStatus(uint32_t* minorStatus,
uint32_t statusValue,
int statusType,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(outBuffer != NULL);
uint32_t messageContext = 0; // Must initialize to 0 before calling gss_display_status.
GssBuffer gssBuffer = {.length = 0, .value = NULL};
uint32_t majorStatus =
gss_display_status(minorStatus, statusValue, statusType, GSS_C_NO_OID, &messageContext, &gssBuffer);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t
NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer)
{
return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_MECH_CODE, outBuffer);
}
uint32_t
NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer)
{
return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_GSS_CODE, outBuffer);
}
uint32_t
NetSecurityNative_ImportUserName(uint32_t* minorStatus, char* inputName, uint32_t inputNameLen, GssName** outputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
assert(outputName != NULL);
assert(*outputName == NULL);
GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName};
return gss_import_name(minorStatus, &inputNameBuffer, GSS_C_NT_USER_NAME, outputName);
}
uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus,
char* inputName,
uint32_t inputNameLen,
GssName** outputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
assert(outputName != NULL);
assert(*outputName == NULL);
// Principal name will usually be in the form SERVICE/HOST. But SPNEGO protocol prefers
// GSS_C_NT_HOSTBASED_SERVICE format. That format uses '@' separator instead of '/' between
// service name and host name. So convert input string into that format.
char* ptrSlash = memchr(inputName, '/', inputNameLen);
char* inputNameCopy = NULL;
if (ptrSlash != NULL)
{
inputNameCopy = (char*) malloc(inputNameLen);
if (inputNameCopy != NULL)
{
memcpy(inputNameCopy, inputName, inputNameLen);
inputNameCopy[ptrSlash - inputName] = '@';
inputName = inputNameCopy;
}
else
{
*minorStatus = 0;
return GSS_S_BAD_NAME;
}
}
GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName};
uint32_t result = gss_import_name(minorStatus, &inputNameBuffer, GSS_C_NT_HOSTBASED_SERVICE, outputName);
if (inputNameCopy != NULL)
{
free(inputNameCopy);
}
return result;
}
uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus,
GssCredId* claimantCredHandle,
GssCtxId** contextHandle,
uint32_t isNtlm,
GssName* targetName,
uint32_t reqFlags,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
return NetSecurityNative_InitSecContextEx(minorStatus,
claimantCredHandle,
contextHandle,
isNtlm,
NULL,
0,
targetName,
reqFlags,
inputBytes,
inputLength,
outBuffer,
retFlags,
isNtlmUsed);
}
uint32_t NetSecurityNative_InitSecContextEx(uint32_t* minorStatus,
GssCredId* claimantCredHandle,
GssCtxId** contextHandle,
uint32_t isNtlm,
void* cbt,
int32_t cbtSize,
GssName* targetName,
uint32_t reqFlags,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(isNtlm == 0 || isNtlm == 1);
assert(targetName != NULL);
assert(inputBytes != NULL || inputLength == 0);
assert(outBuffer != NULL);
assert(retFlags != NULL);
assert(isNtlmUsed != NULL);
assert(cbt != NULL || cbtSize == 0);
// Note: claimantCredHandle can be null
// Note: *contextHandle is null only in the first call and non-null in the subsequent calls
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID krbMech = GSS_KRB5_MECHANISM;
gss_OID desiredMech;
if (isNtlm)
{
desiredMech = GSS_NTLM_MECHANISM;
}
else
{
desiredMech = GSS_SPNEGO_MECHANISM;
}
#else
gss_OID krbMech = (gss_OID)(unsigned long)gss_mech_krb5;
gss_OID_desc gss_mech_OID_desc;
if (isNtlm)
{
gss_mech_OID_desc = gss_mech_ntlm_OID_desc;
}
else
{
gss_mech_OID_desc = gss_mech_spnego_OID_desc;
}
gss_OID desiredMech = &gss_mech_OID_desc;
#endif
GssBuffer inputToken = {.length = inputLength, .value = inputBytes};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
gss_OID_desc* outmech;
struct gss_channel_bindings_struct gssCbt;
if (cbt != NULL)
{
memset(&gssCbt, 0, sizeof(struct gss_channel_bindings_struct));
gssCbt.application_data.length = (size_t)cbtSize;
gssCbt.application_data.value = cbt;
}
uint32_t majorStatus = gss_init_sec_context(minorStatus,
claimantCredHandle,
contextHandle,
targetName,
desiredMech,
reqFlags,
0,
(cbt != NULL) ? &gssCbt : GSS_C_NO_CHANNEL_BINDINGS,
&inputToken,
&outmech,
&gssBuffer,
retFlags,
NULL);
*isNtlmUsed = (isNtlm || majorStatus != GSS_S_COMPLETE || gss_oid_equal(outmech, krbMech) == 0) ? 1 : 0;
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus,
GssCredId* acceptorCredHandle,
GssCtxId** contextHandle,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
assert(minorStatus != NULL);
assert(acceptorCredHandle != NULL);
assert(contextHandle != NULL);
assert(inputBytes != NULL || inputLength == 0);
assert(outBuffer != NULL);
assert(isNtlmUsed != NULL);
// Note: *contextHandle is null only in the first call and non-null in the subsequent calls
GssBuffer inputToken = {.length = inputLength, .value = inputBytes};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
gss_OID mechType = GSS_C_NO_OID;
uint32_t majorStatus = gss_accept_sec_context(minorStatus,
contextHandle,
acceptorCredHandle,
&inputToken,
GSS_C_NO_CHANNEL_BINDINGS,
NULL,
&mechType,
&gssBuffer,
retFlags,
NULL,
NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID ntlmMech = GSS_NTLM_MECHANISM;
#else
gss_OID ntlmMech = &gss_mech_ntlm_OID_desc;
#endif
*isNtlmUsed = (gss_oid_equal(mechType, ntlmMech) != 0) ? 1 : 0;
// The gss_ntlmssp provider doesn't support impersonation or delegation but fails to set the GSS_C_IDENTIFY_FLAG
// flag. So, we'll set it here to keep the behavior consistent with Windows platform.
if (*isNtlmUsed == 1)
{
*retFlags |= GSS_C_IDENTIFY_FLAG;
}
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_GetUser(uint32_t* minorStatus,
GssCtxId* contextHandle,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(outBuffer != NULL);
gss_name_t srcName = GSS_C_NO_NAME;
uint32_t majorStatus = gss_inquire_context(minorStatus,
contextHandle,
&srcName,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL);
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer gssBuffer = {.length = 0, .value = NULL};
majorStatus = gss_display_name(minorStatus, srcName, &gssBuffer, NULL);
if (majorStatus == GSS_S_COMPLETE)
{
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
}
}
if (srcName != NULL)
{
majorStatus = gss_release_name(minorStatus, &srcName);
}
return majorStatus;
}
uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle)
{
assert(minorStatus != NULL);
assert(credHandle != NULL);
return gss_release_cred(minorStatus, credHandle);
}
void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length)
{
assert(buffer != NULL);
uint32_t minorStatus;
GssBuffer gssBuffer = {.length = (size_t)(length), .value = buffer};
gss_release_buffer(&minorStatus, &gssBuffer);
}
uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
return gss_release_name(minorStatus, inputName);
}
uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus,
GssCtxId* contextHandle,
int32_t isEncrypt,
uint8_t* inputBytes,
int32_t count,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(isEncrypt == 1 || isEncrypt == 0);
assert(inputBytes != NULL);
assert(count >= 0);
assert(outBuffer != NULL);
// count refers to the length of the input message. That is, number of bytes of inputBytes
// that need to be wrapped.
int confState;
GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes};
GssBuffer gssBuffer;
uint32_t majorStatus =
gss_wrap(minorStatus, contextHandle, isEncrypt, GSS_C_QOP_DEFAULT, &inputMessageBuffer, &confState, &gssBuffer);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus,
GssCtxId* contextHandle,
uint8_t* inputBytes,
int32_t offset,
int32_t count,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(inputBytes != NULL);
assert(offset >= 0);
assert(count >= 0);
assert(outBuffer != NULL);
// count refers to the length of the input message. That is, the number of bytes of inputBytes
// starting at offset that need to be wrapped.
GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes + offset};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
uint32_t majorStatus = gss_unwrap(minorStatus, contextHandle, &inputMessageBuffer, &gssBuffer, NULL, NULL);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
static uint32_t AcquireCredWithPassword(uint32_t* minorStatus,
int32_t isNtlm,
GssName* desiredName,
char* password,
uint32_t passwdLen,
gss_cred_usage_t credUsage,
GssCredId** outputCredHandle)
{
assert(minorStatus != NULL);
assert(isNtlm == 1 || isNtlm == 0);
assert(desiredName != NULL);
assert(password != NULL);
assert(outputCredHandle != NULL);
assert(*outputCredHandle == NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
(void)isNtlm; // unused
// Specifying GSS_SPNEGO_MECHANISM as a desiredMech on OSX fails.
gss_OID_set desiredMech = GSS_C_NO_OID_SET;
#else
gss_OID_desc gss_mech_OID_desc;
if (isNtlm)
{
gss_mech_OID_desc = gss_mech_ntlm_OID_desc;
}
else
{
gss_mech_OID_desc = gss_mech_spnego_OID_desc;
}
gss_OID_set_desc gss_mech_OID_set_desc = {.count = 1, .elements = &gss_mech_OID_desc};
gss_OID_set desiredMech = &gss_mech_OID_set_desc;
#endif
GssBuffer passwordBuffer = {.length = passwdLen, .value = password};
uint32_t majorStatus = gss_acquire_cred_with_password(
minorStatus, desiredName, &passwordBuffer, 0, desiredMech, credUsage, outputCredHandle, NULL, NULL);
// call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer emptyBuffer = GSS_C_EMPTY_BUFFER;
majorStatus = gss_set_cred_option(minorStatus, outputCredHandle, GSS_KRB5_CRED_NO_CI_FLAGS_X, &emptyBuffer);
}
#endif
return majorStatus;
}
uint32_t NetSecurityNative_AcquireAcceptorCred(uint32_t* minorStatus,
GssCredId** outputCredHandle)
{
return gss_acquire_cred(minorStatus,
GSS_C_NO_NAME,
GSS_C_INDEFINITE,
GSS_C_NO_OID_SET,
GSS_C_ACCEPT,
outputCredHandle,
NULL,
NULL);
}
uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus,
int32_t isNtlm,
GssName* desiredName,
char* password,
uint32_t passwdLen,
GssCredId** outputCredHandle)
{
return AcquireCredWithPassword(
minorStatus, isNtlm, desiredName, password, passwdLen, GSS_C_INITIATE, outputCredHandle);
}
uint32_t NetSecurityNative_IsNtlmInstalled()
{
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID ntlmOid = GSS_NTLM_MECHANISM;
#else
gss_OID ntlmOid = &gss_mech_ntlm_OID_desc;
#endif
uint32_t majorStatus;
uint32_t minorStatus;
gss_OID_set mechSet;
gss_OID_desc oid;
uint32_t foundNtlm = 0;
majorStatus = gss_indicate_mechs(&minorStatus, &mechSet);
if (majorStatus == GSS_S_COMPLETE)
{
for (size_t i = 0; i < mechSet->count; i++)
{
oid = mechSet->elements[i];
if ((oid.length == ntlmOid->length) && (memcmp(oid.elements, ntlmOid->elements, oid.length) == 0))
{
foundNtlm = 1;
break;
}
}
gss_release_oid_set(&minorStatus, &mechSet);
}
return foundNtlm;
}
int32_t NetSecurityNative_EnsureGssInitialized()
{
#if defined(GSS_SHIM)
return ensure_gss_shim_initialized();
#else
return 0;
#endif
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_types.h"
#include "pal_utilities.h"
#include "pal_gssapi.h"
#include <minipal/utils.h>
#if HAVE_GSSFW_HEADERS
#include <GSS/GSS.h>
#else
#if HAVE_HEIMDAL_HEADERS
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_krb5.h>
#else
#include <gssapi/gssapi_ext.h>
#include <gssapi/gssapi_krb5.h>
#endif
#endif
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#if defined(GSS_SHIM)
#include <dlfcn.h>
#include "pal_atomic.h"
#endif
c_static_assert(PAL_GSS_C_DELEG_FLAG == GSS_C_DELEG_FLAG);
c_static_assert(PAL_GSS_C_MUTUAL_FLAG == GSS_C_MUTUAL_FLAG);
c_static_assert(PAL_GSS_C_REPLAY_FLAG == GSS_C_REPLAY_FLAG);
c_static_assert(PAL_GSS_C_SEQUENCE_FLAG == GSS_C_SEQUENCE_FLAG);
c_static_assert(PAL_GSS_C_CONF_FLAG == GSS_C_CONF_FLAG);
c_static_assert(PAL_GSS_C_INTEG_FLAG == GSS_C_INTEG_FLAG);
c_static_assert(PAL_GSS_C_ANON_FLAG == GSS_C_ANON_FLAG);
c_static_assert(PAL_GSS_C_PROT_READY_FLAG == GSS_C_PROT_READY_FLAG);
c_static_assert(PAL_GSS_C_TRANS_FLAG == GSS_C_TRANS_FLAG);
c_static_assert(PAL_GSS_C_DCE_STYLE == GSS_C_DCE_STYLE);
c_static_assert(PAL_GSS_C_IDENTIFY_FLAG == GSS_C_IDENTIFY_FLAG);
c_static_assert(PAL_GSS_C_EXTENDED_ERROR_FLAG == GSS_C_EXTENDED_ERROR_FLAG);
c_static_assert(PAL_GSS_C_DELEG_POLICY_FLAG == GSS_C_DELEG_POLICY_FLAG);
c_static_assert(PAL_GSS_COMPLETE == GSS_S_COMPLETE);
c_static_assert(PAL_GSS_CONTINUE_NEEDED == GSS_S_CONTINUE_NEEDED);
#if !HAVE_GSS_SPNEGO_MECHANISM
static char gss_spnego_oid_value[] = "\x2b\x06\x01\x05\x05\x02"; // Binary representation of SPNEGO Oid (RFC 4178)
static gss_OID_desc gss_mech_spnego_OID_desc = {.length = STRING_LENGTH(gss_spnego_oid_value),
.elements = gss_spnego_oid_value};
static char gss_ntlm_oid_value[] =
"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a"; // Binary representation of NTLM OID
// (https://msdn.microsoft.com/en-us/library/cc236636.aspx)
static gss_OID_desc gss_mech_ntlm_OID_desc = {.length = STRING_LENGTH(gss_ntlm_oid_value),
.elements = gss_ntlm_oid_value};
#endif
#if defined(GSS_SHIM)
#define FOR_ALL_GSS_FUNCTIONS \
PER_FUNCTION_BLOCK(gss_accept_sec_context) \
PER_FUNCTION_BLOCK(gss_acquire_cred) \
PER_FUNCTION_BLOCK(gss_acquire_cred_with_password) \
PER_FUNCTION_BLOCK(gss_delete_sec_context) \
PER_FUNCTION_BLOCK(gss_display_name) \
PER_FUNCTION_BLOCK(gss_display_status) \
PER_FUNCTION_BLOCK(gss_import_name) \
PER_FUNCTION_BLOCK(gss_indicate_mechs) \
PER_FUNCTION_BLOCK(gss_init_sec_context) \
PER_FUNCTION_BLOCK(gss_inquire_context) \
PER_FUNCTION_BLOCK(gss_mech_krb5) \
PER_FUNCTION_BLOCK(gss_oid_equal) \
PER_FUNCTION_BLOCK(gss_release_buffer) \
PER_FUNCTION_BLOCK(gss_release_cred) \
PER_FUNCTION_BLOCK(gss_release_name) \
PER_FUNCTION_BLOCK(gss_release_oid_set) \
PER_FUNCTION_BLOCK(gss_unwrap) \
PER_FUNCTION_BLOCK(gss_wrap) \
PER_FUNCTION_BLOCK(GSS_C_NT_USER_NAME) \
PER_FUNCTION_BLOCK(GSS_C_NT_HOSTBASED_SERVICE)
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define FOR_ALL_GSS_FUNCTIONS FOR_ALL_GSS_FUNCTIONS \
PER_FUNCTION_BLOCK(gss_set_cred_option)
#endif //HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
// define indirection pointers for all functions, like
// static TYPEOF(gss_accept_sec_context)* gss_accept_sec_context_ptr;
#define PER_FUNCTION_BLOCK(fn) \
static TYPEOF(fn)* fn##_ptr;
FOR_ALL_GSS_FUNCTIONS
#undef PER_FUNCTION_BLOCK
static void* volatile s_gssLib = NULL;
// remap gss function use to use indirection pointers
#define gss_accept_sec_context(...) gss_accept_sec_context_ptr(__VA_ARGS__)
#define gss_acquire_cred(...) gss_acquire_cred_ptr(__VA_ARGS__)
#define gss_acquire_cred_with_password(...) gss_acquire_cred_with_password_ptr(__VA_ARGS__)
#define gss_delete_sec_context(...) gss_delete_sec_context_ptr(__VA_ARGS__)
#define gss_display_name(...) gss_display_name_ptr(__VA_ARGS__)
#define gss_display_status(...) gss_display_status_ptr(__VA_ARGS__)
#define gss_import_name(...) gss_import_name_ptr(__VA_ARGS__)
#define gss_indicate_mechs(...) gss_indicate_mechs_ptr(__VA_ARGS__)
#define gss_init_sec_context(...) gss_init_sec_context_ptr(__VA_ARGS__)
#define gss_inquire_context(...) gss_inquire_context_ptr(__VA_ARGS__)
#define gss_oid_equal(...) gss_oid_equal_ptr(__VA_ARGS__)
#define gss_release_buffer(...) gss_release_buffer_ptr(__VA_ARGS__)
#define gss_release_cred(...) gss_release_cred_ptr(__VA_ARGS__)
#define gss_release_name(...) gss_release_name_ptr(__VA_ARGS__)
#define gss_release_oid_set(...) gss_release_oid_set_ptr(__VA_ARGS__)
#define gss_unwrap(...) gss_unwrap_ptr(__VA_ARGS__)
#define gss_wrap(...) gss_wrap_ptr(__VA_ARGS__)
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define gss_set_cred_option(...) gss_set_cred_option_ptr(__VA_ARGS__)
#endif //HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
#define GSS_C_NT_USER_NAME (*GSS_C_NT_USER_NAME_ptr)
#define GSS_C_NT_HOSTBASED_SERVICE (*GSS_C_NT_HOSTBASED_SERVICE_ptr)
#define gss_mech_krb5 (*gss_mech_krb5_ptr)
#define gss_lib_name "libgssapi_krb5.so.2"
static int32_t ensure_gss_shim_initialized()
{
void* lib = dlopen(gss_lib_name, RTLD_LAZY);
if (lib == NULL) { fprintf(stderr, "Cannot load library %s \nError: %s\n", gss_lib_name, dlerror()); return -1; }
// check is someone else has opened and published s_gssLib already
if (!pal_atomic_cas_ptr(&s_gssLib, lib, NULL))
{
dlclose(lib);
}
// initialize indirection pointers for all functions, like:
// gss_accept_sec_context_ptr = (TYPEOF(gss_accept_sec_context)*)dlsym(s_gssLib, "gss_accept_sec_context");
// if (gss_accept_sec_context_ptr == NULL) { fprintf(stderr, "Cannot get symbol %s from %s \nError: %s\n", "gss_accept_sec_context", gss_lib_name, dlerror()); return -1; }
#define PER_FUNCTION_BLOCK(fn) \
fn##_ptr = (TYPEOF(fn)*)dlsym(s_gssLib, #fn); \
if (fn##_ptr == NULL) { fprintf(stderr, "Cannot get symbol " #fn " from %s \nError: %s\n", gss_lib_name, dlerror()); return -1; }
FOR_ALL_GSS_FUNCTIONS
#undef PER_FUNCTION_BLOCK
return 0;
}
#endif // GSS_SHIM
// transfers ownership of the underlying data from gssBuffer to PAL_GssBuffer
static void NetSecurityNative_MoveBuffer(gss_buffer_t gssBuffer, PAL_GssBuffer* targetBuffer)
{
assert(gssBuffer != NULL);
assert(targetBuffer != NULL);
targetBuffer->length = (uint64_t)(gssBuffer->length);
targetBuffer->data = (uint8_t*)(gssBuffer->value);
}
static uint32_t AcquireCredSpNego(uint32_t* minorStatus,
GssName* desiredName,
gss_cred_usage_t credUsage,
GssCredId** outputCredHandle)
{
assert(minorStatus != NULL);
assert(desiredName != NULL);
assert(outputCredHandle != NULL);
assert(*outputCredHandle == NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = GSS_SPNEGO_MECHANISM};
#else
gss_OID_set_desc gss_mech_spnego_OID_set_desc = {.count = 1, .elements = &gss_mech_spnego_OID_desc};
#endif
uint32_t majorStatus = gss_acquire_cred(
minorStatus, desiredName, 0, &gss_mech_spnego_OID_set_desc, credUsage, outputCredHandle, NULL, NULL);
// call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer emptyBuffer = GSS_C_EMPTY_BUFFER;
majorStatus = gss_set_cred_option(minorStatus, outputCredHandle, GSS_KRB5_CRED_NO_CI_FLAGS_X, &emptyBuffer);
}
#endif
return majorStatus;
}
uint32_t
NetSecurityNative_InitiateCredSpNego(uint32_t* minorStatus, GssName* desiredName, GssCredId** outputCredHandle)
{
return AcquireCredSpNego(minorStatus, desiredName, GSS_C_INITIATE, outputCredHandle);
}
uint32_t NetSecurityNative_DeleteSecContext(uint32_t* minorStatus, GssCtxId** contextHandle)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
return gss_delete_sec_context(minorStatus, contextHandle, GSS_C_NO_BUFFER);
}
static uint32_t NetSecurityNative_DisplayStatus(uint32_t* minorStatus,
uint32_t statusValue,
int statusType,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(outBuffer != NULL);
uint32_t messageContext = 0; // Must initialize to 0 before calling gss_display_status.
GssBuffer gssBuffer = {.length = 0, .value = NULL};
uint32_t majorStatus =
gss_display_status(minorStatus, statusValue, statusType, GSS_C_NO_OID, &messageContext, &gssBuffer);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t
NetSecurityNative_DisplayMinorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer)
{
return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_MECH_CODE, outBuffer);
}
uint32_t
NetSecurityNative_DisplayMajorStatus(uint32_t* minorStatus, uint32_t statusValue, PAL_GssBuffer* outBuffer)
{
return NetSecurityNative_DisplayStatus(minorStatus, statusValue, GSS_C_GSS_CODE, outBuffer);
}
uint32_t
NetSecurityNative_ImportUserName(uint32_t* minorStatus, char* inputName, uint32_t inputNameLen, GssName** outputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
assert(outputName != NULL);
assert(*outputName == NULL);
GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName};
return gss_import_name(minorStatus, &inputNameBuffer, GSS_C_NT_USER_NAME, outputName);
}
uint32_t NetSecurityNative_ImportPrincipalName(uint32_t* minorStatus,
char* inputName,
uint32_t inputNameLen,
GssName** outputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
assert(outputName != NULL);
assert(*outputName == NULL);
// Principal name will usually be in the form SERVICE/HOST. But SPNEGO protocol prefers
// GSS_C_NT_HOSTBASED_SERVICE format. That format uses '@' separator instead of '/' between
// service name and host name. So convert input string into that format.
char* ptrSlash = memchr(inputName, '/', inputNameLen);
char* inputNameCopy = NULL;
if (ptrSlash != NULL)
{
inputNameCopy = (char*) malloc(inputNameLen);
if (inputNameCopy != NULL)
{
memcpy(inputNameCopy, inputName, inputNameLen);
inputNameCopy[ptrSlash - inputName] = '@';
inputName = inputNameCopy;
}
else
{
*minorStatus = 0;
return GSS_S_BAD_NAME;
}
}
GssBuffer inputNameBuffer = {.length = inputNameLen, .value = inputName};
uint32_t result = gss_import_name(minorStatus, &inputNameBuffer, GSS_C_NT_HOSTBASED_SERVICE, outputName);
if (inputNameCopy != NULL)
{
free(inputNameCopy);
}
return result;
}
uint32_t NetSecurityNative_InitSecContext(uint32_t* minorStatus,
GssCredId* claimantCredHandle,
GssCtxId** contextHandle,
uint32_t isNtlm,
GssName* targetName,
uint32_t reqFlags,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
return NetSecurityNative_InitSecContextEx(minorStatus,
claimantCredHandle,
contextHandle,
isNtlm,
NULL,
0,
targetName,
reqFlags,
inputBytes,
inputLength,
outBuffer,
retFlags,
isNtlmUsed);
}
uint32_t NetSecurityNative_InitSecContextEx(uint32_t* minorStatus,
GssCredId* claimantCredHandle,
GssCtxId** contextHandle,
uint32_t isNtlm,
void* cbt,
int32_t cbtSize,
GssName* targetName,
uint32_t reqFlags,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(isNtlm == 0 || isNtlm == 1);
assert(targetName != NULL);
assert(inputBytes != NULL || inputLength == 0);
assert(outBuffer != NULL);
assert(retFlags != NULL);
assert(isNtlmUsed != NULL);
assert(cbt != NULL || cbtSize == 0);
// Note: claimantCredHandle can be null
// Note: *contextHandle is null only in the first call and non-null in the subsequent calls
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID krbMech = GSS_KRB5_MECHANISM;
gss_OID desiredMech;
if (isNtlm)
{
desiredMech = GSS_NTLM_MECHANISM;
}
else
{
desiredMech = GSS_SPNEGO_MECHANISM;
}
#else
gss_OID krbMech = (gss_OID)(unsigned long)gss_mech_krb5;
gss_OID_desc gss_mech_OID_desc;
if (isNtlm)
{
gss_mech_OID_desc = gss_mech_ntlm_OID_desc;
}
else
{
gss_mech_OID_desc = gss_mech_spnego_OID_desc;
}
gss_OID desiredMech = &gss_mech_OID_desc;
#endif
GssBuffer inputToken = {.length = inputLength, .value = inputBytes};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
gss_OID_desc* outmech;
struct gss_channel_bindings_struct gssCbt;
if (cbt != NULL)
{
memset(&gssCbt, 0, sizeof(struct gss_channel_bindings_struct));
gssCbt.application_data.length = (size_t)cbtSize;
gssCbt.application_data.value = cbt;
}
uint32_t majorStatus = gss_init_sec_context(minorStatus,
claimantCredHandle,
contextHandle,
targetName,
desiredMech,
reqFlags,
0,
(cbt != NULL) ? &gssCbt : GSS_C_NO_CHANNEL_BINDINGS,
&inputToken,
&outmech,
&gssBuffer,
retFlags,
NULL);
*isNtlmUsed = (isNtlm || majorStatus != GSS_S_COMPLETE || gss_oid_equal(outmech, krbMech) == 0) ? 1 : 0;
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_AcceptSecContext(uint32_t* minorStatus,
GssCredId* acceptorCredHandle,
GssCtxId** contextHandle,
uint8_t* inputBytes,
uint32_t inputLength,
PAL_GssBuffer* outBuffer,
uint32_t* retFlags,
int32_t* isNtlmUsed)
{
assert(minorStatus != NULL);
assert(acceptorCredHandle != NULL);
assert(contextHandle != NULL);
assert(inputBytes != NULL || inputLength == 0);
assert(outBuffer != NULL);
assert(isNtlmUsed != NULL);
// Note: *contextHandle is null only in the first call and non-null in the subsequent calls
GssBuffer inputToken = {.length = inputLength, .value = inputBytes};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
gss_OID mechType = GSS_C_NO_OID;
uint32_t majorStatus = gss_accept_sec_context(minorStatus,
contextHandle,
acceptorCredHandle,
&inputToken,
GSS_C_NO_CHANNEL_BINDINGS,
NULL,
&mechType,
&gssBuffer,
retFlags,
NULL,
NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID ntlmMech = GSS_NTLM_MECHANISM;
#else
gss_OID ntlmMech = &gss_mech_ntlm_OID_desc;
#endif
*isNtlmUsed = (gss_oid_equal(mechType, ntlmMech) != 0) ? 1 : 0;
// The gss_ntlmssp provider doesn't support impersonation or delegation but fails to set the GSS_C_IDENTIFY_FLAG
// flag. So, we'll set it here to keep the behavior consistent with Windows platform.
if (*isNtlmUsed == 1)
{
*retFlags |= GSS_C_IDENTIFY_FLAG;
}
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_GetUser(uint32_t* minorStatus,
GssCtxId* contextHandle,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(outBuffer != NULL);
gss_name_t srcName = GSS_C_NO_NAME;
uint32_t majorStatus = gss_inquire_context(minorStatus,
contextHandle,
&srcName,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL);
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer gssBuffer = {.length = 0, .value = NULL};
majorStatus = gss_display_name(minorStatus, srcName, &gssBuffer, NULL);
if (majorStatus == GSS_S_COMPLETE)
{
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
}
}
if (srcName != NULL)
{
majorStatus = gss_release_name(minorStatus, &srcName);
}
return majorStatus;
}
uint32_t NetSecurityNative_ReleaseCred(uint32_t* minorStatus, GssCredId** credHandle)
{
assert(minorStatus != NULL);
assert(credHandle != NULL);
return gss_release_cred(minorStatus, credHandle);
}
void NetSecurityNative_ReleaseGssBuffer(void* buffer, uint64_t length)
{
assert(buffer != NULL);
uint32_t minorStatus;
GssBuffer gssBuffer = {.length = (size_t)(length), .value = buffer};
gss_release_buffer(&minorStatus, &gssBuffer);
}
uint32_t NetSecurityNative_ReleaseName(uint32_t* minorStatus, GssName** inputName)
{
assert(minorStatus != NULL);
assert(inputName != NULL);
return gss_release_name(minorStatus, inputName);
}
uint32_t NetSecurityNative_Wrap(uint32_t* minorStatus,
GssCtxId* contextHandle,
int32_t isEncrypt,
uint8_t* inputBytes,
int32_t count,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(isEncrypt == 1 || isEncrypt == 0);
assert(inputBytes != NULL);
assert(count >= 0);
assert(outBuffer != NULL);
// count refers to the length of the input message. That is, number of bytes of inputBytes
// that need to be wrapped.
int confState;
GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes};
GssBuffer gssBuffer;
uint32_t majorStatus =
gss_wrap(minorStatus, contextHandle, isEncrypt, GSS_C_QOP_DEFAULT, &inputMessageBuffer, &confState, &gssBuffer);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
uint32_t NetSecurityNative_Unwrap(uint32_t* minorStatus,
GssCtxId* contextHandle,
uint8_t* inputBytes,
int32_t offset,
int32_t count,
PAL_GssBuffer* outBuffer)
{
assert(minorStatus != NULL);
assert(contextHandle != NULL);
assert(inputBytes != NULL);
assert(offset >= 0);
assert(count >= 0);
assert(outBuffer != NULL);
// count refers to the length of the input message. That is, the number of bytes of inputBytes
// starting at offset that need to be wrapped.
GssBuffer inputMessageBuffer = {.length = (size_t)count, .value = inputBytes + offset};
GssBuffer gssBuffer = {.length = 0, .value = NULL};
uint32_t majorStatus = gss_unwrap(minorStatus, contextHandle, &inputMessageBuffer, &gssBuffer, NULL, NULL);
NetSecurityNative_MoveBuffer(&gssBuffer, outBuffer);
return majorStatus;
}
static uint32_t AcquireCredWithPassword(uint32_t* minorStatus,
int32_t isNtlm,
GssName* desiredName,
char* password,
uint32_t passwdLen,
gss_cred_usage_t credUsage,
GssCredId** outputCredHandle)
{
assert(minorStatus != NULL);
assert(isNtlm == 1 || isNtlm == 0);
assert(desiredName != NULL);
assert(password != NULL);
assert(outputCredHandle != NULL);
assert(*outputCredHandle == NULL);
#if HAVE_GSS_SPNEGO_MECHANISM
(void)isNtlm; // unused
// Specifying GSS_SPNEGO_MECHANISM as a desiredMech on OSX fails.
gss_OID_set desiredMech = GSS_C_NO_OID_SET;
#else
gss_OID_desc gss_mech_OID_desc;
if (isNtlm)
{
gss_mech_OID_desc = gss_mech_ntlm_OID_desc;
}
else
{
gss_mech_OID_desc = gss_mech_spnego_OID_desc;
}
gss_OID_set_desc gss_mech_OID_set_desc = {.count = 1, .elements = &gss_mech_OID_desc};
gss_OID_set desiredMech = &gss_mech_OID_set_desc;
#endif
GssBuffer passwordBuffer = {.length = passwdLen, .value = password};
uint32_t majorStatus = gss_acquire_cred_with_password(
minorStatus, desiredName, &passwordBuffer, 0, desiredMech, credUsage, outputCredHandle, NULL, NULL);
// call gss_set_cred_option with GSS_KRB5_CRED_NO_CI_FLAGS_X to support Kerberos Sign Only option from *nix client against a windows server
#if HAVE_GSS_KRB5_CRED_NO_CI_FLAGS_X
if (majorStatus == GSS_S_COMPLETE)
{
GssBuffer emptyBuffer = GSS_C_EMPTY_BUFFER;
majorStatus = gss_set_cred_option(minorStatus, outputCredHandle, GSS_KRB5_CRED_NO_CI_FLAGS_X, &emptyBuffer);
}
#endif
return majorStatus;
}
uint32_t NetSecurityNative_AcquireAcceptorCred(uint32_t* minorStatus,
GssCredId** outputCredHandle)
{
return gss_acquire_cred(minorStatus,
GSS_C_NO_NAME,
GSS_C_INDEFINITE,
GSS_C_NO_OID_SET,
GSS_C_ACCEPT,
outputCredHandle,
NULL,
NULL);
}
uint32_t NetSecurityNative_InitiateCredWithPassword(uint32_t* minorStatus,
int32_t isNtlm,
GssName* desiredName,
char* password,
uint32_t passwdLen,
GssCredId** outputCredHandle)
{
return AcquireCredWithPassword(
minorStatus, isNtlm, desiredName, password, passwdLen, GSS_C_INITIATE, outputCredHandle);
}
uint32_t NetSecurityNative_IsNtlmInstalled()
{
#if HAVE_GSS_SPNEGO_MECHANISM
gss_OID ntlmOid = GSS_NTLM_MECHANISM;
#else
gss_OID ntlmOid = &gss_mech_ntlm_OID_desc;
#endif
uint32_t majorStatus;
uint32_t minorStatus;
gss_OID_set mechSet;
gss_OID_desc oid;
uint32_t foundNtlm = 0;
majorStatus = gss_indicate_mechs(&minorStatus, &mechSet);
if (majorStatus == GSS_S_COMPLETE)
{
for (size_t i = 0; i < mechSet->count; i++)
{
oid = mechSet->elements[i];
if ((oid.length == ntlmOid->length) && (memcmp(oid.elements, ntlmOid->elements, oid.length) == 0))
{
foundNtlm = 1;
break;
}
}
gss_release_oid_set(&minorStatus, &mechSet);
}
return foundNtlm;
}
int32_t NetSecurityNative_EnsureGssInitialized()
{
#if defined(GSS_SHIM)
return ensure_gss_shim_initialized();
#else
return 0;
#endif
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/nativeaot/Runtime/RhConfigValues.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// Definitions of each configuration value used by the RhConfig class.
//
// Each variable is lazily inspected on first query and the resulting value cached for future use. To keep
// things simple we support reading only 32-bit hex quantities and a zero value is considered equivalent to
// the environment variable not being defined. We can get more sophisticated if needs be, but the hope is that
// very few configuration values are exposed in this manner.
//
// By default, print assert to console and break in the debugger, if attached. Set to 0 for a pop-up dialog on assert.
DEBUG_CONFIG_VALUE_WITH_DEFAULT(BreakOnAssert, 1)
RETAIL_CONFIG_VALUE(StressLogLevel)
RETAIL_CONFIG_VALUE(TotalStressLogSize)
RETAIL_CONFIG_VALUE(gcServer)
DEBUG_CONFIG_VALUE(GcStressThrottleMode) // gcstm_TriggerAlways / gcstm_TriggerOnFirstHit / gcstm_TriggerRandom
DEBUG_CONFIG_VALUE(GcStressFreqCallsite) // Number of times to force GC out of GcStressFreqDenom (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressFreqLoop) // Number of times to force GC out of GcStressFreqDenom (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressFreqDenom) // Denominator defining frequencies above, 10,000 used when left unspecified (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressSeed) // Specify Seed for random generator (for GCSTM_RANDOM)
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// Definitions of each configuration value used by the RhConfig class.
//
// Each variable is lazily inspected on first query and the resulting value cached for future use. To keep
// things simple we support reading only 32-bit hex quantities and a zero value is considered equivalent to
// the environment variable not being defined. We can get more sophisticated if needs be, but the hope is that
// very few configuration values are exposed in this manner.
//
// By default, print assert to console and break in the debugger, if attached. Set to 0 for a pop-up dialog on assert.
DEBUG_CONFIG_VALUE_WITH_DEFAULT(BreakOnAssert, 1)
RETAIL_CONFIG_VALUE(StressLogLevel)
RETAIL_CONFIG_VALUE(TotalStressLogSize)
RETAIL_CONFIG_VALUE(gcServer)
DEBUG_CONFIG_VALUE(GcStressThrottleMode) // gcstm_TriggerAlways / gcstm_TriggerOnFirstHit / gcstm_TriggerRandom
DEBUG_CONFIG_VALUE(GcStressFreqCallsite) // Number of times to force GC out of GcStressFreqDenom (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressFreqLoop) // Number of times to force GC out of GcStressFreqDenom (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressFreqDenom) // Denominator defining frequencies above, 10,000 used when left unspecified (for GCSTM_RANDOM)
DEBUG_CONFIG_VALUE(GcStressSeed) // Specify Seed for random generator (for GCSTM_RANDOM)
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/vm/runtimeexceptionkind.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// RuntimeExceptionKind.h
//
#ifndef __runtimeexceptionkind_h__
#define __runtimeexceptionkind_h__
//==========================================================================
// Identifies commonly-used exception classes for COMPlusThrowable().
//==========================================================================
enum RuntimeExceptionKind {
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) k##reKind,
#include "rexcep.h"
kLastException
};
#endif // __runtimeexceptionkind_h__
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// RuntimeExceptionKind.h
//
#ifndef __runtimeexceptionkind_h__
#define __runtimeexceptionkind_h__
//==========================================================================
// Identifies commonly-used exception classes for COMPlusThrowable().
//==========================================================================
enum RuntimeExceptionKind {
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) k##reKind,
#include "rexcep.h"
kLastException
};
#endif // __runtimeexceptionkind_h__
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/native/libs/System.Native/pal_random.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_compiler.h"
#include "pal_types.h"
PALEXPORT void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength);
PALEXPORT int32_t SystemNative_GetCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength);
| // 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_compiler.h"
#include "pal_types.h"
PALEXPORT void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength);
PALEXPORT int32_t SystemNative_GetCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength);
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/pal/src/libunwind/src/ia64/Linit_remote.c | #define UNW_LOCAL_ONLY
#include <libunwind.h>
#if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY)
#include "Ginit_remote.c"
#endif
| #define UNW_LOCAL_ONLY
#include <libunwind.h>
#if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY)
#include "Ginit_remote.c"
#endif
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/sgen/sgen-protocol.h | /**
* \file
* Binary protocol of internal activity, to aid debugging.
*
* Copyright 2001-2003 Ximian, Inc
* Copyright 2003-2010 Novell, Inc.
* Copyright (C) 2012 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_SGENPROTOCOL_H__
#define __MONO_SGENPROTOCOL_H__
#include "sgen-gc.h"
#ifndef DISABLE_SGEN_BINARY_PROTOCOL
#define PROTOCOL_HEADER_CHECK 0xde7ec7ab1ec0de
/*
* The version needs to be bumped every time we introduce breaking changes (like
* adding new protocol entries or various format changes). The latest protocol grepper
* should be able to handle all the previous versions, while an old grepper will
* be able to tell if it cannot handle the format.
*/
#define PROTOCOL_HEADER_VERSION 2
/* Special indices returned by MATCH_INDEX. */
#define BINARY_PROTOCOL_NO_MATCH (-1)
#define BINARY_PROTOCOL_MATCH (-2)
#define PROTOCOL_ID(method) method ## _id
#define PROTOCOL_STRUCT(method) method ## _struct
#define CLIENT_PROTOCOL_NAME(method) sgen_client_ ## method
#ifndef TYPE_INT
#define TYPE_INT int
#endif
#ifndef TYPE_LONGLONG
#define TYPE_LONGLONG long long
#endif
#ifndef TYPE_SIZE
#define TYPE_SIZE size_t
#endif
#ifndef TYPE_POINTER
#define TYPE_POINTER gpointer
#endif
#ifndef TYPE_BOOL
#define TYPE_BOOL gboolean
#endif
enum {
#define BEGIN_PROTOCOL_ENTRY0(method) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) PROTOCOL_ID(method),
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
};
/* We pack all protocol structs by default unless specified otherwise */
#ifndef PROTOCOL_STRUCT_ATTR
#define PROTOCOL_PACK_STRUCTS
#if defined(__GNUC__)
#define PROTOCOL_STRUCT_ATTR __attribute__ ((__packed__))
#else
#define PROTOCOL_STRUCT_ATTR
#endif
#endif
#define BEGIN_PROTOCOL_ENTRY0(method)
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
t5 f5; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
t5 f5; \
t6 f6; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
BEGIN_PROTOCOL_ENTRY0 (method)
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
BEGIN_PROTOCOL_ENTRY1 (method,t1,f1)
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
BEGIN_PROTOCOL_ENTRY2 (method,t1,f1,t2,f2)
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
BEGIN_PROTOCOL_ENTRY3 (method,t1,f1,t2,f2,t3,f3)
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
BEGIN_PROTOCOL_ENTRY4 (method,t1,f1,t2,f2,t3,f3,t4,f4)
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
BEGIN_PROTOCOL_ENTRY5 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5)
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
BEGIN_PROTOCOL_ENTRY6 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6)
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#if defined(_MSC_VER) && defined(PROTOCOL_PACK_STRUCTS)
#pragma pack(push)
#pragma pack(1)
#endif
#include "sgen-protocol-def.h"
#if defined(_MSC_VER) && defined(PROTOCOL_PACK_STRUCTS)
#pragma pack(pop)
#undef PROTOCOL_PACK_STRUCTS
#endif
/* missing: finalizers, roots, non-store wbarriers */
void sgen_binary_protocol_init (const char *filename, long long limit);
gboolean sgen_binary_protocol_is_enabled (void);
gboolean sgen_binary_protocol_flush_buffers (gboolean force);
#define BEGIN_PROTOCOL_ENTRY0(method) \
void sgen_ ## method (void);
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
void sgen_ ## method (t1 f1);
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
void sgen_ ## method (t1 f1, t2 f2);
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3);
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4);
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5);
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6);
#ifdef SGEN_HEAVY_BINARY_PROTOCOL
#define sgen_binary_protocol_is_heavy_enabled() sgen_binary_protocol_is_enabled ()
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
BEGIN_PROTOCOL_ENTRY0 (method)
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
BEGIN_PROTOCOL_ENTRY1 (method,t1,f1)
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
BEGIN_PROTOCOL_ENTRY2 (method,t1,f1,t2,f2)
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
BEGIN_PROTOCOL_ENTRY3 (method,t1,f1,t2,f2,t3,f3)
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
BEGIN_PROTOCOL_ENTRY4 (method,t1,f1,t2,f2,t3,f3,t4,f4)
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
BEGIN_PROTOCOL_ENTRY5 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5)
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
BEGIN_PROTOCOL_ENTRY6 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6)
#else
#define sgen_binary_protocol_is_heavy_enabled() FALSE
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#endif
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
#undef TYPE_INT
#undef TYPE_LONGLONG
#undef TYPE_SIZE
#undef TYPE_POINTER
#undef TYPE_BOOL
#else
#ifndef TYPE_INT
#define TYPE_INT int
#endif
#ifndef TYPE_LONGLONG
#define TYPE_LONGLONG long long
#endif
#ifndef TYPE_SIZE
#define TYPE_SIZE size_t
#endif
#ifndef TYPE_POINTER
#define TYPE_POINTER gpointer
#endif
#ifndef TYPE_BOOL
#define TYPE_BOOL gboolean
#endif
#define BEGIN_PROTOCOL_ENTRY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
static inline void sgen_binary_protocol_init (const char *filename, long long limit) {}
static inline gboolean sgen_binary_protocol_is_enabled (void) { return FALSE; }
static inline gboolean sgen_binary_protocol_flush_buffers (gboolean force) { return FALSE; }
static inline gboolean sgen_binary_protocol_is_heavy_enabled () { return FALSE; }
#endif
#endif
| /**
* \file
* Binary protocol of internal activity, to aid debugging.
*
* Copyright 2001-2003 Ximian, Inc
* Copyright 2003-2010 Novell, Inc.
* Copyright (C) 2012 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_SGENPROTOCOL_H__
#define __MONO_SGENPROTOCOL_H__
#include "sgen-gc.h"
#ifndef DISABLE_SGEN_BINARY_PROTOCOL
#define PROTOCOL_HEADER_CHECK 0xde7ec7ab1ec0de
/*
* The version needs to be bumped every time we introduce breaking changes (like
* adding new protocol entries or various format changes). The latest protocol grepper
* should be able to handle all the previous versions, while an old grepper will
* be able to tell if it cannot handle the format.
*/
#define PROTOCOL_HEADER_VERSION 2
/* Special indices returned by MATCH_INDEX. */
#define BINARY_PROTOCOL_NO_MATCH (-1)
#define BINARY_PROTOCOL_MATCH (-2)
#define PROTOCOL_ID(method) method ## _id
#define PROTOCOL_STRUCT(method) method ## _struct
#define CLIENT_PROTOCOL_NAME(method) sgen_client_ ## method
#ifndef TYPE_INT
#define TYPE_INT int
#endif
#ifndef TYPE_LONGLONG
#define TYPE_LONGLONG long long
#endif
#ifndef TYPE_SIZE
#define TYPE_SIZE size_t
#endif
#ifndef TYPE_POINTER
#define TYPE_POINTER gpointer
#endif
#ifndef TYPE_BOOL
#define TYPE_BOOL gboolean
#endif
enum {
#define BEGIN_PROTOCOL_ENTRY0(method) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) PROTOCOL_ID(method),
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) PROTOCOL_ID(method),
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
};
/* We pack all protocol structs by default unless specified otherwise */
#ifndef PROTOCOL_STRUCT_ATTR
#define PROTOCOL_PACK_STRUCTS
#if defined(__GNUC__)
#define PROTOCOL_STRUCT_ATTR __attribute__ ((__packed__))
#else
#define PROTOCOL_STRUCT_ATTR
#endif
#endif
#define BEGIN_PROTOCOL_ENTRY0(method)
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
t5 f5; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
typedef struct PROTOCOL_STRUCT_ATTR { \
t1 f1; \
t2 f2; \
t3 f3; \
t4 f4; \
t5 f5; \
t6 f6; \
} PROTOCOL_STRUCT(method);
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
BEGIN_PROTOCOL_ENTRY0 (method)
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
BEGIN_PROTOCOL_ENTRY1 (method,t1,f1)
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
BEGIN_PROTOCOL_ENTRY2 (method,t1,f1,t2,f2)
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
BEGIN_PROTOCOL_ENTRY3 (method,t1,f1,t2,f2,t3,f3)
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
BEGIN_PROTOCOL_ENTRY4 (method,t1,f1,t2,f2,t3,f3,t4,f4)
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
BEGIN_PROTOCOL_ENTRY5 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5)
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
BEGIN_PROTOCOL_ENTRY6 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6)
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#if defined(_MSC_VER) && defined(PROTOCOL_PACK_STRUCTS)
#pragma pack(push)
#pragma pack(1)
#endif
#include "sgen-protocol-def.h"
#if defined(_MSC_VER) && defined(PROTOCOL_PACK_STRUCTS)
#pragma pack(pop)
#undef PROTOCOL_PACK_STRUCTS
#endif
/* missing: finalizers, roots, non-store wbarriers */
void sgen_binary_protocol_init (const char *filename, long long limit);
gboolean sgen_binary_protocol_is_enabled (void);
gboolean sgen_binary_protocol_flush_buffers (gboolean force);
#define BEGIN_PROTOCOL_ENTRY0(method) \
void sgen_ ## method (void);
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
void sgen_ ## method (t1 f1);
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
void sgen_ ## method (t1 f1, t2 f2);
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3);
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4);
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5);
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6);
#ifdef SGEN_HEAVY_BINARY_PROTOCOL
#define sgen_binary_protocol_is_heavy_enabled() sgen_binary_protocol_is_enabled ()
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
BEGIN_PROTOCOL_ENTRY0 (method)
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
BEGIN_PROTOCOL_ENTRY1 (method,t1,f1)
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
BEGIN_PROTOCOL_ENTRY2 (method,t1,f1,t2,f2)
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
BEGIN_PROTOCOL_ENTRY3 (method,t1,f1,t2,f2,t3,f3)
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
BEGIN_PROTOCOL_ENTRY4 (method,t1,f1,t2,f2,t3,f3,t4,f4)
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
BEGIN_PROTOCOL_ENTRY5 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5)
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
BEGIN_PROTOCOL_ENTRY6 (method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6)
#else
#define sgen_binary_protocol_is_heavy_enabled() FALSE
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#endif
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
#undef TYPE_INT
#undef TYPE_LONGLONG
#undef TYPE_SIZE
#undef TYPE_POINTER
#undef TYPE_BOOL
#else
#ifndef TYPE_INT
#define TYPE_INT int
#endif
#ifndef TYPE_LONGLONG
#define TYPE_LONGLONG long long
#endif
#ifndef TYPE_SIZE
#define TYPE_SIZE size_t
#endif
#ifndef TYPE_POINTER
#define TYPE_POINTER gpointer
#endif
#ifndef TYPE_BOOL
#define TYPE_BOOL gboolean
#endif
#define BEGIN_PROTOCOL_ENTRY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY0(method) \
static inline void sgen_ ## method (void) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY1(method,t1,f1) \
static inline void sgen_ ## method (t1 f1) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY2(method,t1,f1,t2,f2) \
static inline void sgen_ ## method (t1 f1, t2 f2) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY3(method,t1,f1,t2,f2,t3,f3) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY4(method,t1,f1,t2,f2,t3,f3,t4,f4) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY5(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5) {}
#define BEGIN_PROTOCOL_ENTRY_HEAVY6(method,t1,f1,t2,f2,t3,f3,t4,f4,t5,f5,t6,f6) \
static inline void sgen_ ## method (t1 f1, t2 f2, t3 f3, t4 f4, t5 f5, t6 f6) {}
#define DEFAULT_PRINT()
#define CUSTOM_PRINT(_)
#define IS_ALWAYS_MATCH(_)
#define MATCH_INDEX(_)
#define IS_VTABLE_MATCH(_)
#define END_PROTOCOL_ENTRY
#define END_PROTOCOL_ENTRY_FLUSH
#define END_PROTOCOL_ENTRY_HEAVY
#include "sgen-protocol-def.h"
static inline void sgen_binary_protocol_init (const char *filename, long long limit) {}
static inline gboolean sgen_binary_protocol_is_enabled (void) { return FALSE; }
static inline gboolean sgen_binary_protocol_flush_buffers (gboolean force) { return FALSE; }
static inline gboolean sgen_binary_protocol_is_heavy_enabled () { return FALSE; }
#endif
#endif
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/tests/Interop/COM/NativeServer/Servers.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 <xplatform.h>
#include <cassert>
#include <Server.Contracts.h>
// Forward declare servers so COM clients can reference the CLSIDs
class DECLSPEC_UUID("53169A33-E85D-4E3C-B668-24E438D0929B") NumericTesting;
class DECLSPEC_UUID("B99ABE6A-DFF6-440F-BFB6-55179B8FE18E") ArrayTesting;
class DECLSPEC_UUID("C73C83E8-51A2-47F8-9B5C-4284458E47A6") StringTesting;
class DECLSPEC_UUID("71CF5C45-106C-4B32-B418-43A463C6041F") ErrorMarshalTesting;
class DECLSPEC_UUID("0F8ACD0C-ECE0-4F2A-BD1B-6BFCA93A0726") DispatchTesting;
class DECLSPEC_UUID("4DBD9B61-E372-499F-84DE-EFC70AA8A009") EventTesting;
class DECLSPEC_UUID("4CEFE36D-F377-4B6E-8C34-819A8BB9CB04") AggregationTesting;
class DECLSPEC_UUID("C222F472-DA5A-4FC6-9321-92F4F7053A65") ColorTesting;
class DECLSPEC_UUID("66DB7882-E2B0-471D-92C7-B2B52A0EA535") LicenseTesting;
class DECLSPEC_UUID("FAEF42AE-C1A4-419F-A912-B768AC2679EA") DefaultInterfaceTesting;
class DECLSPEC_UUID("CE137261-6F19-44F5-A449-EF963B3F987E") InspectableTesting;
class DECLSPEC_UUID("4F54231D-9E11-4C0B-8E0B-2EBD8B0E5811") TrackMyLifetimeTesting;
#define CLSID_NumericTesting __uuidof(NumericTesting)
#define CLSID_ArrayTesting __uuidof(ArrayTesting)
#define CLSID_StringTesting __uuidof(StringTesting)
#define CLSID_ErrorMarshalTesting __uuidof(ErrorMarshalTesting)
#define CLSID_DispatchTesting __uuidof(DispatchTesting)
#define CLSID_EventTesting __uuidof(EventTesting)
#define CLSID_AggregationTesting __uuidof(AggregationTesting)
#define CLSID_ColorTesting __uuidof(ColorTesting)
#define CLSID_LicenseTesting __uuidof(LicenseTesting)
#define CLSID_DefaultInterfaceTesting __uuidof(DefaultInterfaceTesting)
#define CLSID_InspectableTesting __uuidof(InspectableTesting)
#define CLSID_TrackMyLifetimeTesting __uuidof(TrackMyLifetimeTesting)
#define IID_INumericTesting __uuidof(INumericTesting)
#define IID_IArrayTesting __uuidof(IArrayTesting)
#define IID_IStringTesting __uuidof(IStringTesting)
#define IID_IErrorMarshalTesting __uuidof(IErrorMarshalTesting)
#define IID_IDispatchTesting __uuidof(IDispatchTesting)
#define IID_TestingEvents __uuidof(TestingEvents)
#define IID_IEventTesting __uuidof(IEventTesting)
#define IID_IAggregationTesting __uuidof(IAggregationTesting)
#define IID_IColorTesting __uuidof(IColorTesting)
#define IID_ILicenseTesting __uuidof(ILicenseTesting)
#define IID_IDefaultInterfaceTesting __uuidof(IDefaultInterfaceTesting)
#define IID_IDefaultInterfaceTesting2 __uuidof(IDefaultInterfaceTesting2)
#define IID_IInspectableTesting __uuidof(IInspectableTesting)
#define IID_IInspectableTesting2 __uuidof(IInspectableTesting2)
#define IID_ITrackMyLifetimeTesting __uuidof(ITrackMyLifetimeTesting)
// Class used for COM activation when using CoreShim
struct CoreShimComActivation
{
CoreShimComActivation(_In_z_ const WCHAR *assemblyName, _In_z_ const WCHAR *typeName)
{
assert(assemblyName && typeName);
Set(assemblyName, typeName);
}
~CoreShimComActivation()
{
Set(nullptr, nullptr);
}
private:
void Set(_In_opt_z_ const WCHAR *assemblyName, _In_opt_z_ const WCHAR *typeName)
{
// See CoreShim.h for usage of environment variables
::SetEnvironmentVariableW(W("CORESHIM_COMACT_ASSEMBLYNAME"), assemblyName);
::SetEnvironmentVariableW(W("CORESHIM_COMACT_TYPENAME"), typeName);
}
};
#include <ComHelpers.h>
#ifndef COM_CLIENT
#define DEF_FUNC(n) virtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODCALLTYPE n
#include "NumericTesting.h"
#include "ArrayTesting.h"
#include "StringTesting.h"
#include "ErrorMarshalTesting.h"
#include "DispatchTesting.h"
#include "EventTesting.h"
#include "AggregationTesting.h"
#include "ColorTesting.h"
#include "LicenseTesting.h"
#include "InspectableTesting.h"
#include "TrackMyLifetimeTesting.h"
#endif
| // 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 <xplatform.h>
#include <cassert>
#include <Server.Contracts.h>
// Forward declare servers so COM clients can reference the CLSIDs
class DECLSPEC_UUID("53169A33-E85D-4E3C-B668-24E438D0929B") NumericTesting;
class DECLSPEC_UUID("B99ABE6A-DFF6-440F-BFB6-55179B8FE18E") ArrayTesting;
class DECLSPEC_UUID("C73C83E8-51A2-47F8-9B5C-4284458E47A6") StringTesting;
class DECLSPEC_UUID("71CF5C45-106C-4B32-B418-43A463C6041F") ErrorMarshalTesting;
class DECLSPEC_UUID("0F8ACD0C-ECE0-4F2A-BD1B-6BFCA93A0726") DispatchTesting;
class DECLSPEC_UUID("4DBD9B61-E372-499F-84DE-EFC70AA8A009") EventTesting;
class DECLSPEC_UUID("4CEFE36D-F377-4B6E-8C34-819A8BB9CB04") AggregationTesting;
class DECLSPEC_UUID("C222F472-DA5A-4FC6-9321-92F4F7053A65") ColorTesting;
class DECLSPEC_UUID("66DB7882-E2B0-471D-92C7-B2B52A0EA535") LicenseTesting;
class DECLSPEC_UUID("FAEF42AE-C1A4-419F-A912-B768AC2679EA") DefaultInterfaceTesting;
class DECLSPEC_UUID("CE137261-6F19-44F5-A449-EF963B3F987E") InspectableTesting;
class DECLSPEC_UUID("4F54231D-9E11-4C0B-8E0B-2EBD8B0E5811") TrackMyLifetimeTesting;
#define CLSID_NumericTesting __uuidof(NumericTesting)
#define CLSID_ArrayTesting __uuidof(ArrayTesting)
#define CLSID_StringTesting __uuidof(StringTesting)
#define CLSID_ErrorMarshalTesting __uuidof(ErrorMarshalTesting)
#define CLSID_DispatchTesting __uuidof(DispatchTesting)
#define CLSID_EventTesting __uuidof(EventTesting)
#define CLSID_AggregationTesting __uuidof(AggregationTesting)
#define CLSID_ColorTesting __uuidof(ColorTesting)
#define CLSID_LicenseTesting __uuidof(LicenseTesting)
#define CLSID_DefaultInterfaceTesting __uuidof(DefaultInterfaceTesting)
#define CLSID_InspectableTesting __uuidof(InspectableTesting)
#define CLSID_TrackMyLifetimeTesting __uuidof(TrackMyLifetimeTesting)
#define IID_INumericTesting __uuidof(INumericTesting)
#define IID_IArrayTesting __uuidof(IArrayTesting)
#define IID_IStringTesting __uuidof(IStringTesting)
#define IID_IErrorMarshalTesting __uuidof(IErrorMarshalTesting)
#define IID_IDispatchTesting __uuidof(IDispatchTesting)
#define IID_TestingEvents __uuidof(TestingEvents)
#define IID_IEventTesting __uuidof(IEventTesting)
#define IID_IAggregationTesting __uuidof(IAggregationTesting)
#define IID_IColorTesting __uuidof(IColorTesting)
#define IID_ILicenseTesting __uuidof(ILicenseTesting)
#define IID_IDefaultInterfaceTesting __uuidof(IDefaultInterfaceTesting)
#define IID_IDefaultInterfaceTesting2 __uuidof(IDefaultInterfaceTesting2)
#define IID_IInspectableTesting __uuidof(IInspectableTesting)
#define IID_IInspectableTesting2 __uuidof(IInspectableTesting2)
#define IID_ITrackMyLifetimeTesting __uuidof(ITrackMyLifetimeTesting)
// Class used for COM activation when using CoreShim
struct CoreShimComActivation
{
CoreShimComActivation(_In_z_ const WCHAR *assemblyName, _In_z_ const WCHAR *typeName)
{
assert(assemblyName && typeName);
Set(assemblyName, typeName);
}
~CoreShimComActivation()
{
Set(nullptr, nullptr);
}
private:
void Set(_In_opt_z_ const WCHAR *assemblyName, _In_opt_z_ const WCHAR *typeName)
{
// See CoreShim.h for usage of environment variables
::SetEnvironmentVariableW(W("CORESHIM_COMACT_ASSEMBLYNAME"), assemblyName);
::SetEnvironmentVariableW(W("CORESHIM_COMACT_TYPENAME"), typeName);
}
};
#include <ComHelpers.h>
#ifndef COM_CLIENT
#define DEF_FUNC(n) virtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODCALLTYPE n
#include "NumericTesting.h"
#include "ArrayTesting.h"
#include "StringTesting.h"
#include "ErrorMarshalTesting.h"
#include "DispatchTesting.h"
#include "EventTesting.h"
#include "AggregationTesting.h"
#include "ColorTesting.h"
#include "LicenseTesting.h"
#include "InspectableTesting.h"
#include "TrackMyLifetimeTesting.h"
#endif
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/tests/Interop/COM/NativeClients/Dispatch/ClientTests.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
#include <cassert>
#include <Server.Contracts.h>
#define COM_CLIENT
#include <Servers.h>
#define THROW_IF_FAILED(exp) { hr = exp; if (FAILED(hr)) { ::printf("FAILURE: 0x%08x = %s\n", hr, #exp); throw hr; } }
#define THROW_FAIL_IF_FALSE(exp) { if (!(exp)) { ::printf("FALSE: %s\n", #exp); throw E_FAIL; } }
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
#include <cassert>
#include <Server.Contracts.h>
#define COM_CLIENT
#include <Servers.h>
#define THROW_IF_FAILED(exp) { hr = exp; if (FAILED(hr)) { ::printf("FAILURE: 0x%08x = %s\n", hr, #exp); throw hr; } }
#define THROW_FAIL_IF_FALSE(exp) { if (!(exp)) { ::printf("FALSE: %s\n", #exp); throw E_FAIL; } }
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/utils/mono-digest.h | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/**
* \file
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to rpmMD5Init, call rpmMD5Update as
* needed on buffers full of bytes, and then call rpmMD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
/* parts of this file are :
* Written March 1993 by Branko Lankester
* Modified June 1993 by Colin Plumb for altered md5.c.
* Modified October 1995 by Erik Troan for RPM
*/
#ifndef __MONO_DIGEST_H__
#define __MONO_DIGEST_H__
#include <config.h>
#include <glib.h>
#include <mono/utils/mono-publib.h>
#if HAVE_COMMONCRYPTO_COMMONDIGEST_H
#include <CommonCrypto/CommonDigest.h>
#define MonoSHA1Context CC_SHA1_CTX
#define MonoMD5Context CC_MD5_CTX
#else
typedef struct {
guint32 buf[4];
guint32 bits[2];
guchar in[64];
gint doByteReverse;
} MonoMD5Context;
#endif
MONO_API void mono_md5_get_digest (const guchar *buffer, gint buffer_size, guchar digest[16]);
/* use this one when speed is needed */
/* for use in provider code only */
MONO_API void mono_md5_get_digest_from_file (const gchar *filename, guchar digest[16]);
/* raw routines */
MONO_API void mono_md5_init (MonoMD5Context *ctx);
MONO_API void mono_md5_update (MonoMD5Context *ctx, const guchar *buf, guint32 len);
MONO_API void mono_md5_final (MonoMD5Context *ctx, guchar digest[16]);
uint64_t
mono_md5_ctx_byte_length (MonoMD5Context *ctx);
#if !HAVE_COMMONCRYPTO_COMMONDIGEST_H
typedef struct {
guint32 state[5];
guint32 count[2];
unsigned char buffer[64];
} MonoSHA1Context;
#endif
MONO_API void mono_sha1_get_digest (const guchar *buffer, gint buffer_size, guchar digest [20]);
MONO_API void mono_sha1_get_digest_from_file (const gchar *filename, guchar digest [20]);
MONO_API void mono_sha1_init (MonoSHA1Context* context);
MONO_API void mono_sha1_update (MonoSHA1Context* context, const guchar* data, guint32 len);
MONO_API void mono_sha1_final (MonoSHA1Context* context, unsigned char digest[20]);
MONO_API void mono_digest_get_public_token (guchar* token, const guchar *pubkey, guint32 len);
#endif /* __MONO_DIGEST_H__ */
| /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/**
* \file
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to rpmMD5Init, call rpmMD5Update as
* needed on buffers full of bytes, and then call rpmMD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
/* parts of this file are :
* Written March 1993 by Branko Lankester
* Modified June 1993 by Colin Plumb for altered md5.c.
* Modified October 1995 by Erik Troan for RPM
*/
#ifndef __MONO_DIGEST_H__
#define __MONO_DIGEST_H__
#include <config.h>
#include <glib.h>
#include <mono/utils/mono-publib.h>
#if HAVE_COMMONCRYPTO_COMMONDIGEST_H
#include <CommonCrypto/CommonDigest.h>
#define MonoSHA1Context CC_SHA1_CTX
#define MonoMD5Context CC_MD5_CTX
#else
typedef struct {
guint32 buf[4];
guint32 bits[2];
guchar in[64];
gint doByteReverse;
} MonoMD5Context;
#endif
MONO_API void mono_md5_get_digest (const guchar *buffer, gint buffer_size, guchar digest[16]);
/* use this one when speed is needed */
/* for use in provider code only */
MONO_API void mono_md5_get_digest_from_file (const gchar *filename, guchar digest[16]);
/* raw routines */
MONO_API void mono_md5_init (MonoMD5Context *ctx);
MONO_API void mono_md5_update (MonoMD5Context *ctx, const guchar *buf, guint32 len);
MONO_API void mono_md5_final (MonoMD5Context *ctx, guchar digest[16]);
uint64_t
mono_md5_ctx_byte_length (MonoMD5Context *ctx);
#if !HAVE_COMMONCRYPTO_COMMONDIGEST_H
typedef struct {
guint32 state[5];
guint32 count[2];
unsigned char buffer[64];
} MonoSHA1Context;
#endif
MONO_API void mono_sha1_get_digest (const guchar *buffer, gint buffer_size, guchar digest [20]);
MONO_API void mono_sha1_get_digest_from_file (const gchar *filename, guchar digest [20]);
MONO_API void mono_sha1_init (MonoSHA1Context* context);
MONO_API void mono_sha1_update (MonoSHA1Context* context, const guchar* data, guint32 len);
MONO_API void mono_sha1_final (MonoSHA1Context* context, unsigned char digest[20]);
MONO_API void mono_digest_get_public_token (guchar* token, const guchar *pubkey, guint32 len);
#endif /* __MONO_DIGEST_H__ */
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/mono/mono/metadata/profiler.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 <mono/metadata/assembly.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mono-config-dirs.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/profiler-legacy.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/debug-internals.h>
#include <mono/utils/mono-dl.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/w32subset.h>
MonoProfilerState mono_profiler_state;
typedef void (*MonoProfilerInitializer) (const char *);
#define OLD_INITIALIZER_NAME "mono_profiler_startup"
#define NEW_INITIALIZER_NAME "mono_profiler_init"
static gboolean
load_profiler (MonoDl *module, const char *name, const char *desc)
{
g_assert (module);
char *err, *old_name = g_strdup_printf (OLD_INITIALIZER_NAME);
MonoProfilerInitializer func;
if (!(err = mono_dl_symbol (module, old_name, (gpointer*) &func))) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Found old-style startup symbol '%s' for the '%s' profiler; it has not been migrated to the new API.", old_name, name);
g_free (old_name);
return FALSE;
}
g_free (err);
g_free (old_name);
char *new_name = g_strdup_printf (NEW_INITIALIZER_NAME "_%s", name);
if ((err = mono_dl_symbol (module, new_name, (gpointer *) &func))) {
g_free (err);
g_free (new_name);
return FALSE;
}
g_free (new_name);
func (desc);
return TRUE;
}
static gboolean
load_profiler_from_executable (const char *name, const char *desc)
{
char *err;
/*
* Some profilers (such as ours) may need to call back into the runtime
* from their sampling callback (which is called in async-signal context).
* They need to be able to know that all references back to the runtime
* have been resolved; otherwise, calling runtime functions may result in
* invoking the dynamic linker which is not async-signal-safe. Passing
* MONO_DL_EAGER will ask the dynamic linker to resolve everything upfront.
*/
MonoDl *module = mono_dl_open (NULL, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open main executable: %s", err);
g_free (err);
return FALSE;
}
return load_profiler (module, name, desc);
}
static gboolean
load_profiler_from_directory (const char *directory, const char *libname, const char *name, const char *desc)
{
char *path, *err;
void *iter = NULL;
while ((path = mono_dl_build_path (directory, libname, &iter))) {
MonoDl *module = mono_dl_open (path, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open from directory \"%s\": %s", path, err);
g_free (err);
g_free (path);
continue;
}
g_free (path);
return load_profiler (module, name, desc);
}
return FALSE;
}
static gboolean
load_profiler_from_installation (const char *libname, const char *name, const char *desc)
{
char *err;
MonoDl *module = mono_dl_open_runtime_lib (libname, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open from installation: %s", err);
g_free (err);
return FALSE;
}
return load_profiler (module, name, desc);
}
/**
* mono_profiler_load:
*
* Loads a profiler module based on the specified description. \p desc can be
* of the form \c name:args or just \c name. For example, \c log:sample and
* \c log will both load \c libmono-profiler-log.so. The description is passed
* to the module after it has been loaded. If the specified module has already
* been loaded, this function has no effect.
*
* A module called \c foo should declare an entry point like so:
*
* \code
* void mono_profiler_init_foo (const char *desc)
* {
* }
* \endcode
*
* This function is \b not async safe.
*
* This function may \b only be called by embedders prior to running managed
* code.
*/
void
mono_profiler_load (const char *desc)
{
const char *col;
char *mname, *libname;
mname = libname = NULL;
if (!desc || !strcmp ("default", desc))
#if HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE && !defined (HOST_WIN32)
desc = "log:report";
#else
desc = "log";
#endif
if ((col = strchr (desc, ':')) != NULL) {
mname = (char *) g_memdup (desc, col - desc + 1);
mname [col - desc] = 0;
} else {
mname = g_strdup (desc);
}
if (load_profiler_from_executable (mname, desc))
goto done;
libname = g_strdup_printf ("mono-profiler-%s", mname);
if (load_profiler_from_installation (libname, mname, desc))
goto done;
if (mono_config_get_assemblies_dir () && load_profiler_from_directory (mono_assembly_getrootdir (), libname, mname, desc))
goto done;
if (load_profiler_from_directory (NULL, libname, mname, desc))
goto done;
mono_trace (G_LOG_LEVEL_CRITICAL, MONO_TRACE_PROFILER, "The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname);
done:
g_free (mname);
g_free (libname);
}
/**
* mono_profiler_create:
*
* Installs a profiler and returns a handle for it. The handle is used with the
* other functions in the profiler API (e.g. for setting up callbacks). The
* given structure pointer, \p prof, will be passed to all callbacks from the
* profiler API. It can be \c NULL.
*
* Example usage:
*
* \code
* struct _MonoProfiler {
* int my_stuff;
* // ...
* };
*
* MonoProfiler *prof = malloc (sizeof (MonoProfiler));
* prof->my_stuff = 42;
* MonoProfilerHandle handle = mono_profiler_create (prof);
* mono_profiler_set_shutdown_callback (handle, my_shutdown_cb);
* \endcode
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
MonoProfilerHandle
mono_profiler_create (MonoProfiler *prof)
{
MonoProfilerHandle handle = g_new0 (struct _MonoProfilerDesc, 1);
handle->prof = prof;
handle->next = mono_profiler_state.profilers;
mono_profiler_state.profilers = handle;
return handle;
}
/**
* mono_profiler_set_cleanup_callback:
*
* Sets a profiler cleanup function. This function will be invoked at shutdown
* when the profiler API is cleaning up its internal structures. It's mainly
* intended for a profiler to free the structure pointer that was passed to
* \c mono_profiler_create, if necessary.
*
* This function is async safe.
*/
void
mono_profiler_set_cleanup_callback (MonoProfilerHandle handle, MonoProfilerCleanupCallback cb)
{
mono_atomic_store_ptr (&handle->cleanup_callback, (gpointer) cb);
}
/**
* mono_profiler_enable_coverage:
*
* Enables support for code coverage instrumentation. At the moment, this means
* enabling the debug info subsystem. If this function is not called, it will
* not be possible to use \c mono_profiler_get_coverage_data. Returns \c TRUE
* if code coverage support was enabled, or \c FALSE if the function was called
* too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_coverage (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
mono_os_mutex_init (&mono_profiler_state.coverage_mutex);
mono_profiler_state.coverage_hash = g_hash_table_new (NULL, NULL);
if (!mono_debug_enabled ())
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
return mono_profiler_state.code_coverage = TRUE;
}
/**
* mono_profiler_set_coverage_filter_callback:
*
* Sets a code coverage filter function. The profiler API will invoke filter
* functions from all installed profilers. If any of them return \c TRUE, then
* the given method will be instrumented for coverage analysis. All filters are
* guaranteed to be called at least once per method, even if an earlier filter
* has already returned \c TRUE.
*
* Note that filter functions must be installed before a method is compiled in
* order to have any effect, i.e. a filter should be registered in a profiler's
* init function or prior to running managed code (if embedding).
*
* This function is async safe.
*/
void
mono_profiler_set_coverage_filter_callback (MonoProfilerHandle handle, MonoProfilerCoverageFilterCallback cb)
{
mono_atomic_store_ptr (&handle->coverage_filter, (gpointer) cb);
}
static void
coverage_lock (void)
{
mono_os_mutex_lock (&mono_profiler_state.coverage_mutex);
}
static void
coverage_unlock (void)
{
mono_os_mutex_unlock (&mono_profiler_state.coverage_mutex);
}
/**
* mono_profiler_get_coverage_data:
*
* Retrieves all coverage data for \p method and invokes \p cb for each entry.
* Source location information will only be filled out if \p method has debug
* info available. Returns \c TRUE if \p method was instrumented for code
* coverage; otherwise, \c FALSE.
*
* Please note that the structure passed to \p cb is only valid for the
* duration of the callback.
*
* This function is \b not async safe.
*/
mono_bool
mono_profiler_get_coverage_data (MonoProfilerHandle handle, MonoMethod *method, MonoProfilerCoverageCallback cb)
{
if (!mono_profiler_state.code_coverage)
return FALSE;
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;
coverage_lock ();
MonoProfilerCoverageInfo *info = (MonoProfilerCoverageInfo*)g_hash_table_lookup (mono_profiler_state.coverage_hash, method);
coverage_unlock ();
MonoMethodHeaderSummary header;
g_assert (mono_method_get_header_summary (method, &header));
guint32 size = header.code_size;
const unsigned char *start = header.code;
const unsigned char *end = start + size;
MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
if (!info) {
int i, n_il_offsets;
int *source_files;
GPtrArray *source_file_list;
MonoSymSeqPoint *sym_seq_points;
if (!minfo)
return TRUE;
/* Return 0 counts for all locations */
mono_debug_get_seq_points (minfo, NULL, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
for (i = 0; i < n_il_offsets; ++i) {
MonoSymSeqPoint *sp = &sym_seq_points [i];
const char *srcfile = "";
if (source_files [i] != -1) {
MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
srcfile = sinfo->source_file;
}
MonoProfilerCoverageData data;
memset (&data, 0, sizeof (data));
data.method = method;
data.il_offset = sp->il_offset;
data.counter = 0;
data.file_name = srcfile;
data.line = sp->line;
data.column = 0;
cb (handle->prof, &data);
}
g_free (source_files);
g_free (sym_seq_points);
g_ptr_array_free (source_file_list, TRUE);
return TRUE;
}
for (guint32 i = 0; i < info->entries; i++) {
guchar *cil_code = info->data [i].cil_code;
if (cil_code && cil_code >= start && cil_code < end) {
guint32 offset = cil_code - start;
MonoProfilerCoverageData data;
memset (&data, 0, sizeof (data));
data.method = method;
data.il_offset = offset;
data.counter = info->data [i].count;
data.line = 1;
data.column = 1;
if (minfo) {
MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, offset);
if (loc) {
data.file_name = g_strdup (loc->source_file);
data.line = loc->row;
data.column = loc->column;
mono_debug_free_source_location (loc);
}
}
cb (handle->prof, &data);
g_free ((char *) data.file_name);
}
}
return TRUE;
}
gboolean
mono_profiler_coverage_instrumentation_enabled (MonoMethod *method)
{
gboolean cover = FALSE;
for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
MonoProfilerCoverageFilterCallback cb = (MonoProfilerCoverageFilterCallback)handle->coverage_filter;
if (cb)
cover |= cb (handle->prof, method);
}
return cover;
}
MonoProfilerCoverageInfo *
mono_profiler_coverage_alloc (MonoMethod *method, guint32 entries)
{
if (!mono_profiler_state.code_coverage)
return NULL;
if (!mono_profiler_coverage_instrumentation_enabled (method))
return NULL;
coverage_lock ();
MonoProfilerCoverageInfo *info = g_malloc0 (sizeof (MonoProfilerCoverageInfo) + sizeof (MonoProfilerCoverageInfoEntry) * entries);
info->entries = entries;
g_hash_table_insert (mono_profiler_state.coverage_hash, method, info);
coverage_unlock ();
return info;
}
/**
* mono_profiler_enable_sampling:
*
* Enables the sampling thread. Users must call this function if they intend
* to use statistical sampling; \c mono_profiler_set_sample_mode will have no
* effect if this function has not been called. The first profiler to call this
* function will get ownership over sampling settings (mode and frequency) so
* that no other profiler can change those settings. Returns \c TRUE if the
* sampling thread was enabled, or \c FALSE if the function was called too late
* for this to be possible.
*
* Note that \c mono_profiler_set_sample_mode must still be called with a mode
* other than \c MONO_PROFILER_SAMPLE_MODE_NONE to actually start sampling.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_sampling (MonoProfilerHandle handle)
{
if (mono_profiler_state.startup_done)
return FALSE;
if (mono_profiler_state.sampling_owner)
return TRUE;
mono_profiler_state.sampling_owner = handle;
mono_profiler_state.sample_mode = MONO_PROFILER_SAMPLE_MODE_NONE;
mono_profiler_state.sample_freq = 100;
mono_os_sem_init (&mono_profiler_state.sampling_semaphore, 0);
return TRUE;
}
/**
* mono_profiler_set_sample_mode:
*
* Sets the sampling mode and frequency (in Hz). \p freq must be a positive
* number. If the calling profiler has ownership over sampling settings, the
* settings will be changed and this function will return \c TRUE; otherwise,
* it returns \c FALSE without changing any settings.
*
* This function is async safe.
*/
mono_bool
mono_profiler_set_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode mode, uint32_t freq)
{
if (handle != mono_profiler_state.sampling_owner)
return FALSE;
mono_profiler_state.sample_mode = mode;
mono_profiler_state.sample_freq = freq;
mono_profiler_sampling_thread_post ();
return TRUE;
}
/**
* mono_profiler_get_sample_mode:
*
* Retrieves the current sampling mode and/or frequency (in Hz). Returns
* \c TRUE if the calling profiler is allowed to change the sampling settings;
* otherwise, \c FALSE.
*
* This function is async safe.
*/
mono_bool
mono_profiler_get_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode *mode, uint32_t *freq)
{
if (mode)
*mode = mono_profiler_state.sample_mode;
if (freq)
*freq = mono_profiler_state.sample_freq;
return handle == mono_profiler_state.sampling_owner;
}
gboolean
mono_profiler_sampling_enabled (void)
{
return !!mono_profiler_state.sampling_owner;
}
void
mono_profiler_sampling_thread_post (void)
{
mono_os_sem_post (&mono_profiler_state.sampling_semaphore);
}
void
mono_profiler_sampling_thread_wait (void)
{
mono_os_sem_wait (&mono_profiler_state.sampling_semaphore, MONO_SEM_FLAGS_NONE);
}
/**
* mono_profiler_enable_allocations:
*
* Enables instrumentation of GC allocations. This is necessary so that managed
* allocators can be instrumented with a call into the profiler API.
* Allocations will not be reported unless this function is called. Returns
* \c TRUE if allocation instrumentation was enabled, or \c FALSE if the
* function was called too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_allocations (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
return mono_profiler_state.allocations = TRUE;
}
/**
* mono_profiler_enable_clauses:
*
* Enables instrumentation of exception clauses. This is necessary so that CIL
* \c leave instructions can be instrumented with a call into the profiler API.
* Exception clauses will not be reported unless this function is called.
* Returns \c TRUE if exception clause instrumentation was enabled, or \c FALSE
* if the function was called too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_clauses (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
return mono_profiler_state.clauses = TRUE;
}
gboolean
mono_component_profiler_clauses_enabled (void)
{
return mono_profiler_clauses_enabled ();
}
/**
* mono_profiler_set_call_instrumentation_filter_callback:
*
* Sets a call instrumentation filter function. The profiler API will invoke
* filter functions from all installed profilers. If any of them return flags
* other than \c MONO_PROFILER_CALL_INSTRUMENTATION_NONE, then the given method
* will be instrumented as requested. All filters are guaranteed to be called
* at least once per method, even if earlier filters have already specified all
* flags.
*
* Note that filter functions must be installed before a method is compiled in
* order to have any effect, i.e. a filter should be registered in a profiler's
* init function or prior to running managed code (if embedding). Also, to
* instrument a method that's going to be AOT-compiled, a filter must be
* installed at AOT time. This can be done in exactly the same way as one would
* normally, i.e. by passing the \c --profile option on the command line, by
* calling \c mono_profiler_load, or simply by using the profiler API as an
* embedder.
*
* Indiscriminate method instrumentation is extremely heavy and will slow down
* most applications to a crawl. Users should consider sampling as a possible
* alternative to such heavy-handed instrumentation.
*
* This function is async safe.
*/
void
mono_profiler_set_call_instrumentation_filter_callback (MonoProfilerHandle handle, MonoProfilerCallInstrumentationFilterCallback cb)
{
mono_atomic_store_ptr (&handle->call_instrumentation_filter, (gpointer) cb);
}
/**
* mono_profiler_enable_call_context_introspection:
*
* Enables support for retrieving stack frame data from a call context. At the
* moment, this means enabling the debug info subsystem. If this function is not
* called, it will not be possible to use the call context introspection
* functions (they will simply return \c NULL). Returns \c TRUE if call context
* introspection was enabled, or \c FALSE if the function was called too late for
* this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_call_context_introspection (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
mono_profiler_state.context_enable ();
return mono_profiler_state.call_contexts = TRUE;
}
/**
* mono_profiler_call_context_get_this:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the \c this reference for the method. Returns \c NULL if none exists (i.e.
* it's a static method) or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_this (MonoProfilerCallContext *context)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_this (context);
}
/**
* mono_profiler_call_context_get_argument:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the method argument at the given position. Returns \c NULL if \p position is
* out of bounds or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_argument (MonoProfilerCallContext *context, uint32_t position)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_argument (context, position);
}
/**
* mono_profiler_call_context_get_local:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the local variable at the given position. Returns \c NULL if \p position is
* out of bounds or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_local (MonoProfilerCallContext *context, uint32_t position)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_local (context, position);
}
/**
* mono_profiler_call_context_get_result:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* return value of a method. Returns \c NULL if the method has no return value
* (i.e. it returns \c void), if the leave event was the result of a tail call,
* if the function is called on a context from an enter event, or if call
* context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_result (MonoProfilerCallContext *context)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_result (context);
}
/**
* mono_profiler_call_context_free_buffer:
*
* Frees a buffer returned by one of the call context introspection functions.
* Passing a \c NULL value for \p buffer is allowed, which makes this function
* a no-op.
*
* This function is \b not async safe.
*/
void
mono_profiler_call_context_free_buffer (void *buffer)
{
mono_profiler_state.context_free_buffer (buffer);
}
G_ENUM_FUNCTIONS (MonoProfilerCallInstrumentationFlags)
MonoProfilerCallInstrumentationFlags
mono_profiler_get_call_instrumentation_flags (MonoMethod *method)
{
MonoProfilerCallInstrumentationFlags flags = MONO_PROFILER_CALL_INSTRUMENTATION_NONE;
for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
MonoProfilerCallInstrumentationFilterCallback cb = (MonoProfilerCallInstrumentationFilterCallback)handle->call_instrumentation_filter;
if (cb)
flags |= cb (handle->prof, method);
}
return flags;
}
void
mono_profiler_started (void)
{
mono_profiler_state.startup_done = TRUE;
}
static void
update_callback (volatile gpointer *location, gpointer new_, volatile gint32 *counter)
{
gpointer old;
do {
old = mono_atomic_load_ptr (location);
} while (mono_atomic_cas_ptr (location, new_, old) != old);
/*
* At this point, we could have installed a NULL callback while the counter
* is still non-zero, i.e. setting the callback and modifying the counter
* is not a single atomic operation. This is fine as we make sure callbacks
* are non-NULL before invoking them (see the code below that generates the
* raise functions), and besides, updating callbacks at runtime is an
* inherently racy operation.
*/
if (old)
mono_atomic_dec_i32 (counter);
if (new_)
mono_atomic_inc_i32 (counter);
}
#define _MONO_PROFILER_EVENT(name, type) \
void \
mono_profiler_set_ ## name ## _callback (MonoProfilerHandle handle, MonoProfiler ## type ## Callback cb) \
{ \
update_callback (&handle->name ## _cb, (gpointer) cb, &mono_profiler_state.name ## _count); \
}
#define MONO_PROFILER_EVENT_0(name, type) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_5(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name, arg5_type, arg5_name) \
_MONO_PROFILER_EVENT(name, type)
#include <mono/metadata/profiler-events.h>
#undef MONO_PROFILER_EVENT_0
#undef MONO_PROFILER_EVENT_1
#undef MONO_PROFILER_EVENT_2
#undef MONO_PROFILER_EVENT_3
#undef MONO_PROFILER_EVENT_4
#undef MONO_PROFILER_EVENT_5
#undef _MONO_PROFILER_EVENT
#define _MONO_PROFILER_EVENT(name, type, params, args) \
void \
mono_profiler_raise_ ## name params \
{ \
if (!mono_profiler_state.startup_done) return; \
for (MonoProfilerHandle h = mono_profiler_state.profilers; h; h = h->next) { \
MonoProfiler ## type ## Callback cb = (MonoProfiler ## type ## Callback)h->name ## _cb; \
if (cb) \
cb args; \
} \
}
#define MONO_PROFILER_EVENT_0(name, type) \
_MONO_PROFILER_EVENT(name, type, (void), (h->prof))
#define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name), (h->prof, arg1_name))
#define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name), (h->prof, arg1_name, arg2_name))
#define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name), (h->prof, arg1_name, arg2_name, arg3_name))
#define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name, arg4_type arg4_name), (h->prof, arg1_name, arg2_name, arg3_name, arg4_name))
#define MONO_PROFILER_EVENT_5(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name, arg5_type, arg5_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name, arg4_type arg4_name, arg5_type arg5_name), (h->prof, arg1_name, arg2_name, arg3_name, arg4_name, arg5_name))
#include <mono/metadata/profiler-events.h>
#undef MONO_PROFILER_EVENT_0
#undef MONO_PROFILER_EVENT_1
#undef MONO_PROFILER_EVENT_2
#undef MONO_PROFILER_EVENT_3
#undef MONO_PROFILER_EVENT_4
#undef MONO_PROFILER_EVENT_5
#undef _MONO_PROFILER_EVENT
struct _MonoProfiler {
MonoProfilerHandle handle;
MonoLegacyProfiler *profiler;
MonoLegacyProfileFunc shutdown_callback;
MonoLegacyProfileThreadFunc thread_start, thread_end;
MonoLegacyProfileGCFunc gc_event;
MonoLegacyProfileGCResizeFunc gc_heap_resize;
MonoLegacyProfileJitResult jit_end2;
MonoLegacyProfileAllocFunc allocation;
MonoLegacyProfileMethodFunc enter;
MonoLegacyProfileMethodFunc leave;
MonoLegacyProfileExceptionFunc throw_callback;
MonoLegacyProfileMethodFunc exc_method_leave;
MonoLegacyProfileExceptionClauseFunc clause_callback;
};
static MonoProfiler *current;
void
mono_profiler_install (MonoLegacyProfiler *prof, MonoLegacyProfileFunc callback)
{
current = g_new0 (MonoProfiler, 1);
current->handle = mono_profiler_create (current);
current->profiler = prof;
current->shutdown_callback = callback;
}
static void
thread_start_cb (MonoProfiler *prof, uintptr_t tid)
{
prof->thread_start (prof->profiler, tid);
}
static void
thread_stop_cb (MonoProfiler *prof, uintptr_t tid)
{
prof->thread_end (prof->profiler, tid);
}
void
mono_profiler_install_thread (MonoLegacyProfileThreadFunc start, MonoLegacyProfileThreadFunc end)
{
current->thread_start = start;
current->thread_end = end;
if (start)
mono_profiler_set_thread_started_callback (current->handle, thread_start_cb);
if (end)
mono_profiler_set_thread_stopped_callback (current->handle, thread_stop_cb);
}
static void
gc_event_cb (MonoProfiler *prof, MonoProfilerGCEvent event, uint32_t generation, gboolean is_serial)
{
prof->gc_event (prof->profiler, event, generation);
}
static void
gc_resize_cb (MonoProfiler *prof, uintptr_t size)
{
prof->gc_heap_resize (prof->profiler, size);
}
void
mono_profiler_install_gc (MonoLegacyProfileGCFunc callback, MonoLegacyProfileGCResizeFunc heap_resize_callback)
{
current->gc_event = callback;
current->gc_heap_resize = heap_resize_callback;
if (callback)
mono_profiler_set_gc_event_callback (current->handle, gc_event_cb);
if (heap_resize_callback)
mono_profiler_set_gc_resize_callback (current->handle, gc_resize_cb);
}
static void
jit_done_cb (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
{
prof->jit_end2 (prof->profiler, method, jinfo, 0);
}
static void
jit_failed_cb (MonoProfiler *prof, MonoMethod *method)
{
prof->jit_end2 (prof->profiler, method, NULL, 1);
}
void
mono_profiler_install_jit_end (MonoLegacyProfileJitResult end)
{
current->jit_end2 = end;
if (end) {
mono_profiler_set_jit_done_callback (current->handle, jit_done_cb);
mono_profiler_set_jit_failed_callback (current->handle, jit_failed_cb);
}
}
void
mono_profiler_set_events (int flags)
{
/* Do nothing. */
}
static void
allocation_cb (MonoProfiler *prof, MonoObject* object)
{
prof->allocation (prof->profiler, object, object->vtable->klass);
}
void
mono_profiler_install_allocation (MonoLegacyProfileAllocFunc callback)
{
current->allocation = callback;
if (callback)
mono_profiler_set_gc_allocation_callback (current->handle, allocation_cb);
}
static void
enter_cb (MonoProfiler *prof, MonoMethod *method, MonoProfilerCallContext *context)
{
prof->enter (prof->profiler, method);
}
static void
leave_cb (MonoProfiler *prof, MonoMethod *method, MonoProfilerCallContext *context)
{
prof->leave (prof->profiler, method);
}
static void
tail_call_cb (MonoProfiler *prof, MonoMethod *method, MonoMethod *target)
{
prof->leave (prof->profiler, method);
}
void
mono_profiler_install_enter_leave (MonoLegacyProfileMethodFunc enter, MonoLegacyProfileMethodFunc fleave)
{
current->enter = enter;
current->leave = fleave;
if (enter)
mono_profiler_set_method_enter_callback (current->handle, enter_cb);
if (fleave) {
mono_profiler_set_method_leave_callback (current->handle, leave_cb);
mono_profiler_set_method_tail_call_callback (current->handle, tail_call_cb);
}
}
static void
throw_callback_cb (MonoProfiler *prof, MonoObject *exception)
{
prof->throw_callback (prof->profiler, exception);
}
static void
exc_method_leave_cb (MonoProfiler *prof, MonoMethod *method, MonoObject *exception)
{
prof->exc_method_leave (prof->profiler, method);
}
static void
clause_callback_cb (MonoProfiler *prof, MonoMethod *method, uint32_t index, MonoExceptionEnum type, MonoObject *exception)
{
prof->clause_callback (prof->profiler, method, type, index);
}
void
mono_profiler_install_exception (MonoLegacyProfileExceptionFunc throw_callback, MonoLegacyProfileMethodFunc exc_method_leave, MonoLegacyProfileExceptionClauseFunc clause_callback)
{
current->throw_callback = throw_callback;
current->exc_method_leave = exc_method_leave;
current->clause_callback = clause_callback;
if (throw_callback)
mono_profiler_set_exception_throw_callback (current->handle, throw_callback_cb);
if (exc_method_leave)
mono_profiler_set_method_exception_leave_callback (current->handle, exc_method_leave_cb);
if (clause_callback)
mono_profiler_set_exception_clause_callback (current->handle, clause_callback_cb);
}
| /*
* 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 <mono/metadata/assembly.h>
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/mono-config-dirs.h>
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/profiler-legacy.h>
#include <mono/metadata/profiler-private.h>
#include <mono/metadata/debug-internals.h>
#include <mono/utils/mono-dl.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/w32subset.h>
MonoProfilerState mono_profiler_state;
typedef void (*MonoProfilerInitializer) (const char *);
#define OLD_INITIALIZER_NAME "mono_profiler_startup"
#define NEW_INITIALIZER_NAME "mono_profiler_init"
static gboolean
load_profiler (MonoDl *module, const char *name, const char *desc)
{
g_assert (module);
char *err, *old_name = g_strdup_printf (OLD_INITIALIZER_NAME);
MonoProfilerInitializer func;
if (!(err = mono_dl_symbol (module, old_name, (gpointer*) &func))) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Found old-style startup symbol '%s' for the '%s' profiler; it has not been migrated to the new API.", old_name, name);
g_free (old_name);
return FALSE;
}
g_free (err);
g_free (old_name);
char *new_name = g_strdup_printf (NEW_INITIALIZER_NAME "_%s", name);
if ((err = mono_dl_symbol (module, new_name, (gpointer *) &func))) {
g_free (err);
g_free (new_name);
return FALSE;
}
g_free (new_name);
func (desc);
return TRUE;
}
static gboolean
load_profiler_from_executable (const char *name, const char *desc)
{
char *err;
/*
* Some profilers (such as ours) may need to call back into the runtime
* from their sampling callback (which is called in async-signal context).
* They need to be able to know that all references back to the runtime
* have been resolved; otherwise, calling runtime functions may result in
* invoking the dynamic linker which is not async-signal-safe. Passing
* MONO_DL_EAGER will ask the dynamic linker to resolve everything upfront.
*/
MonoDl *module = mono_dl_open (NULL, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open main executable: %s", err);
g_free (err);
return FALSE;
}
return load_profiler (module, name, desc);
}
static gboolean
load_profiler_from_directory (const char *directory, const char *libname, const char *name, const char *desc)
{
char *path, *err;
void *iter = NULL;
while ((path = mono_dl_build_path (directory, libname, &iter))) {
MonoDl *module = mono_dl_open (path, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open from directory \"%s\": %s", path, err);
g_free (err);
g_free (path);
continue;
}
g_free (path);
return load_profiler (module, name, desc);
}
return FALSE;
}
static gboolean
load_profiler_from_installation (const char *libname, const char *name, const char *desc)
{
char *err;
MonoDl *module = mono_dl_open_runtime_lib (libname, MONO_DL_EAGER, &err);
if (!module) {
mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_PROFILER, "Could not open from installation: %s", err);
g_free (err);
return FALSE;
}
return load_profiler (module, name, desc);
}
/**
* mono_profiler_load:
*
* Loads a profiler module based on the specified description. \p desc can be
* of the form \c name:args or just \c name. For example, \c log:sample and
* \c log will both load \c libmono-profiler-log.so. The description is passed
* to the module after it has been loaded. If the specified module has already
* been loaded, this function has no effect.
*
* A module called \c foo should declare an entry point like so:
*
* \code
* void mono_profiler_init_foo (const char *desc)
* {
* }
* \endcode
*
* This function is \b not async safe.
*
* This function may \b only be called by embedders prior to running managed
* code.
*/
void
mono_profiler_load (const char *desc)
{
const char *col;
char *mname, *libname;
mname = libname = NULL;
if (!desc || !strcmp ("default", desc))
#if HAVE_API_SUPPORT_WIN32_PIPE_OPEN_CLOSE && !defined (HOST_WIN32)
desc = "log:report";
#else
desc = "log";
#endif
if ((col = strchr (desc, ':')) != NULL) {
mname = (char *) g_memdup (desc, col - desc + 1);
mname [col - desc] = 0;
} else {
mname = g_strdup (desc);
}
if (load_profiler_from_executable (mname, desc))
goto done;
libname = g_strdup_printf ("mono-profiler-%s", mname);
if (load_profiler_from_installation (libname, mname, desc))
goto done;
if (mono_config_get_assemblies_dir () && load_profiler_from_directory (mono_assembly_getrootdir (), libname, mname, desc))
goto done;
if (load_profiler_from_directory (NULL, libname, mname, desc))
goto done;
mono_trace (G_LOG_LEVEL_CRITICAL, MONO_TRACE_PROFILER, "The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname);
done:
g_free (mname);
g_free (libname);
}
/**
* mono_profiler_create:
*
* Installs a profiler and returns a handle for it. The handle is used with the
* other functions in the profiler API (e.g. for setting up callbacks). The
* given structure pointer, \p prof, will be passed to all callbacks from the
* profiler API. It can be \c NULL.
*
* Example usage:
*
* \code
* struct _MonoProfiler {
* int my_stuff;
* // ...
* };
*
* MonoProfiler *prof = malloc (sizeof (MonoProfiler));
* prof->my_stuff = 42;
* MonoProfilerHandle handle = mono_profiler_create (prof);
* mono_profiler_set_shutdown_callback (handle, my_shutdown_cb);
* \endcode
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
MonoProfilerHandle
mono_profiler_create (MonoProfiler *prof)
{
MonoProfilerHandle handle = g_new0 (struct _MonoProfilerDesc, 1);
handle->prof = prof;
handle->next = mono_profiler_state.profilers;
mono_profiler_state.profilers = handle;
return handle;
}
/**
* mono_profiler_set_cleanup_callback:
*
* Sets a profiler cleanup function. This function will be invoked at shutdown
* when the profiler API is cleaning up its internal structures. It's mainly
* intended for a profiler to free the structure pointer that was passed to
* \c mono_profiler_create, if necessary.
*
* This function is async safe.
*/
void
mono_profiler_set_cleanup_callback (MonoProfilerHandle handle, MonoProfilerCleanupCallback cb)
{
mono_atomic_store_ptr (&handle->cleanup_callback, (gpointer) cb);
}
/**
* mono_profiler_enable_coverage:
*
* Enables support for code coverage instrumentation. At the moment, this means
* enabling the debug info subsystem. If this function is not called, it will
* not be possible to use \c mono_profiler_get_coverage_data. Returns \c TRUE
* if code coverage support was enabled, or \c FALSE if the function was called
* too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_coverage (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
mono_os_mutex_init (&mono_profiler_state.coverage_mutex);
mono_profiler_state.coverage_hash = g_hash_table_new (NULL, NULL);
if (!mono_debug_enabled ())
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
return mono_profiler_state.code_coverage = TRUE;
}
/**
* mono_profiler_set_coverage_filter_callback:
*
* Sets a code coverage filter function. The profiler API will invoke filter
* functions from all installed profilers. If any of them return \c TRUE, then
* the given method will be instrumented for coverage analysis. All filters are
* guaranteed to be called at least once per method, even if an earlier filter
* has already returned \c TRUE.
*
* Note that filter functions must be installed before a method is compiled in
* order to have any effect, i.e. a filter should be registered in a profiler's
* init function or prior to running managed code (if embedding).
*
* This function is async safe.
*/
void
mono_profiler_set_coverage_filter_callback (MonoProfilerHandle handle, MonoProfilerCoverageFilterCallback cb)
{
mono_atomic_store_ptr (&handle->coverage_filter, (gpointer) cb);
}
static void
coverage_lock (void)
{
mono_os_mutex_lock (&mono_profiler_state.coverage_mutex);
}
static void
coverage_unlock (void)
{
mono_os_mutex_unlock (&mono_profiler_state.coverage_mutex);
}
/**
* mono_profiler_get_coverage_data:
*
* Retrieves all coverage data for \p method and invokes \p cb for each entry.
* Source location information will only be filled out if \p method has debug
* info available. Returns \c TRUE if \p method was instrumented for code
* coverage; otherwise, \c FALSE.
*
* Please note that the structure passed to \p cb is only valid for the
* duration of the callback.
*
* This function is \b not async safe.
*/
mono_bool
mono_profiler_get_coverage_data (MonoProfilerHandle handle, MonoMethod *method, MonoProfilerCoverageCallback cb)
{
if (!mono_profiler_state.code_coverage)
return FALSE;
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;
coverage_lock ();
MonoProfilerCoverageInfo *info = (MonoProfilerCoverageInfo*)g_hash_table_lookup (mono_profiler_state.coverage_hash, method);
coverage_unlock ();
MonoMethodHeaderSummary header;
g_assert (mono_method_get_header_summary (method, &header));
guint32 size = header.code_size;
const unsigned char *start = header.code;
const unsigned char *end = start + size;
MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
if (!info) {
int i, n_il_offsets;
int *source_files;
GPtrArray *source_file_list;
MonoSymSeqPoint *sym_seq_points;
if (!minfo)
return TRUE;
/* Return 0 counts for all locations */
mono_debug_get_seq_points (minfo, NULL, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
for (i = 0; i < n_il_offsets; ++i) {
MonoSymSeqPoint *sp = &sym_seq_points [i];
const char *srcfile = "";
if (source_files [i] != -1) {
MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
srcfile = sinfo->source_file;
}
MonoProfilerCoverageData data;
memset (&data, 0, sizeof (data));
data.method = method;
data.il_offset = sp->il_offset;
data.counter = 0;
data.file_name = srcfile;
data.line = sp->line;
data.column = 0;
cb (handle->prof, &data);
}
g_free (source_files);
g_free (sym_seq_points);
g_ptr_array_free (source_file_list, TRUE);
return TRUE;
}
for (guint32 i = 0; i < info->entries; i++) {
guchar *cil_code = info->data [i].cil_code;
if (cil_code && cil_code >= start && cil_code < end) {
guint32 offset = cil_code - start;
MonoProfilerCoverageData data;
memset (&data, 0, sizeof (data));
data.method = method;
data.il_offset = offset;
data.counter = info->data [i].count;
data.line = 1;
data.column = 1;
if (minfo) {
MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, offset);
if (loc) {
data.file_name = g_strdup (loc->source_file);
data.line = loc->row;
data.column = loc->column;
mono_debug_free_source_location (loc);
}
}
cb (handle->prof, &data);
g_free ((char *) data.file_name);
}
}
return TRUE;
}
gboolean
mono_profiler_coverage_instrumentation_enabled (MonoMethod *method)
{
gboolean cover = FALSE;
for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
MonoProfilerCoverageFilterCallback cb = (MonoProfilerCoverageFilterCallback)handle->coverage_filter;
if (cb)
cover |= cb (handle->prof, method);
}
return cover;
}
MonoProfilerCoverageInfo *
mono_profiler_coverage_alloc (MonoMethod *method, guint32 entries)
{
if (!mono_profiler_state.code_coverage)
return NULL;
if (!mono_profiler_coverage_instrumentation_enabled (method))
return NULL;
coverage_lock ();
MonoProfilerCoverageInfo *info = g_malloc0 (sizeof (MonoProfilerCoverageInfo) + sizeof (MonoProfilerCoverageInfoEntry) * entries);
info->entries = entries;
g_hash_table_insert (mono_profiler_state.coverage_hash, method, info);
coverage_unlock ();
return info;
}
/**
* mono_profiler_enable_sampling:
*
* Enables the sampling thread. Users must call this function if they intend
* to use statistical sampling; \c mono_profiler_set_sample_mode will have no
* effect if this function has not been called. The first profiler to call this
* function will get ownership over sampling settings (mode and frequency) so
* that no other profiler can change those settings. Returns \c TRUE if the
* sampling thread was enabled, or \c FALSE if the function was called too late
* for this to be possible.
*
* Note that \c mono_profiler_set_sample_mode must still be called with a mode
* other than \c MONO_PROFILER_SAMPLE_MODE_NONE to actually start sampling.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_sampling (MonoProfilerHandle handle)
{
if (mono_profiler_state.startup_done)
return FALSE;
if (mono_profiler_state.sampling_owner)
return TRUE;
mono_profiler_state.sampling_owner = handle;
mono_profiler_state.sample_mode = MONO_PROFILER_SAMPLE_MODE_NONE;
mono_profiler_state.sample_freq = 100;
mono_os_sem_init (&mono_profiler_state.sampling_semaphore, 0);
return TRUE;
}
/**
* mono_profiler_set_sample_mode:
*
* Sets the sampling mode and frequency (in Hz). \p freq must be a positive
* number. If the calling profiler has ownership over sampling settings, the
* settings will be changed and this function will return \c TRUE; otherwise,
* it returns \c FALSE without changing any settings.
*
* This function is async safe.
*/
mono_bool
mono_profiler_set_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode mode, uint32_t freq)
{
if (handle != mono_profiler_state.sampling_owner)
return FALSE;
mono_profiler_state.sample_mode = mode;
mono_profiler_state.sample_freq = freq;
mono_profiler_sampling_thread_post ();
return TRUE;
}
/**
* mono_profiler_get_sample_mode:
*
* Retrieves the current sampling mode and/or frequency (in Hz). Returns
* \c TRUE if the calling profiler is allowed to change the sampling settings;
* otherwise, \c FALSE.
*
* This function is async safe.
*/
mono_bool
mono_profiler_get_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode *mode, uint32_t *freq)
{
if (mode)
*mode = mono_profiler_state.sample_mode;
if (freq)
*freq = mono_profiler_state.sample_freq;
return handle == mono_profiler_state.sampling_owner;
}
gboolean
mono_profiler_sampling_enabled (void)
{
return !!mono_profiler_state.sampling_owner;
}
void
mono_profiler_sampling_thread_post (void)
{
mono_os_sem_post (&mono_profiler_state.sampling_semaphore);
}
void
mono_profiler_sampling_thread_wait (void)
{
mono_os_sem_wait (&mono_profiler_state.sampling_semaphore, MONO_SEM_FLAGS_NONE);
}
/**
* mono_profiler_enable_allocations:
*
* Enables instrumentation of GC allocations. This is necessary so that managed
* allocators can be instrumented with a call into the profiler API.
* Allocations will not be reported unless this function is called. Returns
* \c TRUE if allocation instrumentation was enabled, or \c FALSE if the
* function was called too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_allocations (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
return mono_profiler_state.allocations = TRUE;
}
/**
* mono_profiler_enable_clauses:
*
* Enables instrumentation of exception clauses. This is necessary so that CIL
* \c leave instructions can be instrumented with a call into the profiler API.
* Exception clauses will not be reported unless this function is called.
* Returns \c TRUE if exception clause instrumentation was enabled, or \c FALSE
* if the function was called too late for this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_clauses (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
return mono_profiler_state.clauses = TRUE;
}
gboolean
mono_component_profiler_clauses_enabled (void)
{
return mono_profiler_clauses_enabled ();
}
/**
* mono_profiler_set_call_instrumentation_filter_callback:
*
* Sets a call instrumentation filter function. The profiler API will invoke
* filter functions from all installed profilers. If any of them return flags
* other than \c MONO_PROFILER_CALL_INSTRUMENTATION_NONE, then the given method
* will be instrumented as requested. All filters are guaranteed to be called
* at least once per method, even if earlier filters have already specified all
* flags.
*
* Note that filter functions must be installed before a method is compiled in
* order to have any effect, i.e. a filter should be registered in a profiler's
* init function or prior to running managed code (if embedding). Also, to
* instrument a method that's going to be AOT-compiled, a filter must be
* installed at AOT time. This can be done in exactly the same way as one would
* normally, i.e. by passing the \c --profile option on the command line, by
* calling \c mono_profiler_load, or simply by using the profiler API as an
* embedder.
*
* Indiscriminate method instrumentation is extremely heavy and will slow down
* most applications to a crawl. Users should consider sampling as a possible
* alternative to such heavy-handed instrumentation.
*
* This function is async safe.
*/
void
mono_profiler_set_call_instrumentation_filter_callback (MonoProfilerHandle handle, MonoProfilerCallInstrumentationFilterCallback cb)
{
mono_atomic_store_ptr (&handle->call_instrumentation_filter, (gpointer) cb);
}
/**
* mono_profiler_enable_call_context_introspection:
*
* Enables support for retrieving stack frame data from a call context. At the
* moment, this means enabling the debug info subsystem. If this function is not
* called, it will not be possible to use the call context introspection
* functions (they will simply return \c NULL). Returns \c TRUE if call context
* introspection was enabled, or \c FALSE if the function was called too late for
* this to be possible.
*
* This function is \b not async safe.
*
* This function may \b only be called from a profiler's init function or prior
* to running managed code.
*/
mono_bool
mono_profiler_enable_call_context_introspection (void)
{
if (mono_profiler_state.startup_done)
return FALSE;
mono_profiler_state.context_enable ();
return mono_profiler_state.call_contexts = TRUE;
}
/**
* mono_profiler_call_context_get_this:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the \c this reference for the method. Returns \c NULL if none exists (i.e.
* it's a static method) or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_this (MonoProfilerCallContext *context)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_this (context);
}
/**
* mono_profiler_call_context_get_argument:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the method argument at the given position. Returns \c NULL if \p position is
* out of bounds or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_argument (MonoProfilerCallContext *context, uint32_t position)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_argument (context, position);
}
/**
* mono_profiler_call_context_get_local:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* the local variable at the given position. Returns \c NULL if \p position is
* out of bounds or if call context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_local (MonoProfilerCallContext *context, uint32_t position)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_local (context, position);
}
/**
* mono_profiler_call_context_get_result:
*
* Given a valid call context from an enter/leave event, retrieves a pointer to
* return value of a method. Returns \c NULL if the method has no return value
* (i.e. it returns \c void), if the leave event was the result of a tail call,
* if the function is called on a context from an enter event, or if call
* context introspection was not enabled.
*
* The buffer returned by this function must be freed with
* \c mono_profiler_call_context_free_buffer.
*
* Please note that a call context is only valid for the duration of the
* enter/leave callback it was passed to.
*
* This function is \b not async safe.
*/
void *
mono_profiler_call_context_get_result (MonoProfilerCallContext *context)
{
if (!mono_profiler_state.call_contexts)
return NULL;
return mono_profiler_state.context_get_result (context);
}
/**
* mono_profiler_call_context_free_buffer:
*
* Frees a buffer returned by one of the call context introspection functions.
* Passing a \c NULL value for \p buffer is allowed, which makes this function
* a no-op.
*
* This function is \b not async safe.
*/
void
mono_profiler_call_context_free_buffer (void *buffer)
{
mono_profiler_state.context_free_buffer (buffer);
}
G_ENUM_FUNCTIONS (MonoProfilerCallInstrumentationFlags)
MonoProfilerCallInstrumentationFlags
mono_profiler_get_call_instrumentation_flags (MonoMethod *method)
{
MonoProfilerCallInstrumentationFlags flags = MONO_PROFILER_CALL_INSTRUMENTATION_NONE;
for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
MonoProfilerCallInstrumentationFilterCallback cb = (MonoProfilerCallInstrumentationFilterCallback)handle->call_instrumentation_filter;
if (cb)
flags |= cb (handle->prof, method);
}
return flags;
}
void
mono_profiler_started (void)
{
mono_profiler_state.startup_done = TRUE;
}
static void
update_callback (volatile gpointer *location, gpointer new_, volatile gint32 *counter)
{
gpointer old;
do {
old = mono_atomic_load_ptr (location);
} while (mono_atomic_cas_ptr (location, new_, old) != old);
/*
* At this point, we could have installed a NULL callback while the counter
* is still non-zero, i.e. setting the callback and modifying the counter
* is not a single atomic operation. This is fine as we make sure callbacks
* are non-NULL before invoking them (see the code below that generates the
* raise functions), and besides, updating callbacks at runtime is an
* inherently racy operation.
*/
if (old)
mono_atomic_dec_i32 (counter);
if (new_)
mono_atomic_inc_i32 (counter);
}
#define _MONO_PROFILER_EVENT(name, type) \
void \
mono_profiler_set_ ## name ## _callback (MonoProfilerHandle handle, MonoProfiler ## type ## Callback cb) \
{ \
update_callback (&handle->name ## _cb, (gpointer) cb, &mono_profiler_state.name ## _count); \
}
#define MONO_PROFILER_EVENT_0(name, type) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
_MONO_PROFILER_EVENT(name, type)
#define MONO_PROFILER_EVENT_5(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name, arg5_type, arg5_name) \
_MONO_PROFILER_EVENT(name, type)
#include <mono/metadata/profiler-events.h>
#undef MONO_PROFILER_EVENT_0
#undef MONO_PROFILER_EVENT_1
#undef MONO_PROFILER_EVENT_2
#undef MONO_PROFILER_EVENT_3
#undef MONO_PROFILER_EVENT_4
#undef MONO_PROFILER_EVENT_5
#undef _MONO_PROFILER_EVENT
#define _MONO_PROFILER_EVENT(name, type, params, args) \
void \
mono_profiler_raise_ ## name params \
{ \
if (!mono_profiler_state.startup_done) return; \
for (MonoProfilerHandle h = mono_profiler_state.profilers; h; h = h->next) { \
MonoProfiler ## type ## Callback cb = (MonoProfiler ## type ## Callback)h->name ## _cb; \
if (cb) \
cb args; \
} \
}
#define MONO_PROFILER_EVENT_0(name, type) \
_MONO_PROFILER_EVENT(name, type, (void), (h->prof))
#define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name), (h->prof, arg1_name))
#define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name), (h->prof, arg1_name, arg2_name))
#define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name), (h->prof, arg1_name, arg2_name, arg3_name))
#define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name, arg4_type arg4_name), (h->prof, arg1_name, arg2_name, arg3_name, arg4_name))
#define MONO_PROFILER_EVENT_5(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name, arg5_type, arg5_name) \
_MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name, arg4_type arg4_name, arg5_type arg5_name), (h->prof, arg1_name, arg2_name, arg3_name, arg4_name, arg5_name))
#include <mono/metadata/profiler-events.h>
#undef MONO_PROFILER_EVENT_0
#undef MONO_PROFILER_EVENT_1
#undef MONO_PROFILER_EVENT_2
#undef MONO_PROFILER_EVENT_3
#undef MONO_PROFILER_EVENT_4
#undef MONO_PROFILER_EVENT_5
#undef _MONO_PROFILER_EVENT
struct _MonoProfiler {
MonoProfilerHandle handle;
MonoLegacyProfiler *profiler;
MonoLegacyProfileFunc shutdown_callback;
MonoLegacyProfileThreadFunc thread_start, thread_end;
MonoLegacyProfileGCFunc gc_event;
MonoLegacyProfileGCResizeFunc gc_heap_resize;
MonoLegacyProfileJitResult jit_end2;
MonoLegacyProfileAllocFunc allocation;
MonoLegacyProfileMethodFunc enter;
MonoLegacyProfileMethodFunc leave;
MonoLegacyProfileExceptionFunc throw_callback;
MonoLegacyProfileMethodFunc exc_method_leave;
MonoLegacyProfileExceptionClauseFunc clause_callback;
};
static MonoProfiler *current;
void
mono_profiler_install (MonoLegacyProfiler *prof, MonoLegacyProfileFunc callback)
{
current = g_new0 (MonoProfiler, 1);
current->handle = mono_profiler_create (current);
current->profiler = prof;
current->shutdown_callback = callback;
}
static void
thread_start_cb (MonoProfiler *prof, uintptr_t tid)
{
prof->thread_start (prof->profiler, tid);
}
static void
thread_stop_cb (MonoProfiler *prof, uintptr_t tid)
{
prof->thread_end (prof->profiler, tid);
}
void
mono_profiler_install_thread (MonoLegacyProfileThreadFunc start, MonoLegacyProfileThreadFunc end)
{
current->thread_start = start;
current->thread_end = end;
if (start)
mono_profiler_set_thread_started_callback (current->handle, thread_start_cb);
if (end)
mono_profiler_set_thread_stopped_callback (current->handle, thread_stop_cb);
}
static void
gc_event_cb (MonoProfiler *prof, MonoProfilerGCEvent event, uint32_t generation, gboolean is_serial)
{
prof->gc_event (prof->profiler, event, generation);
}
static void
gc_resize_cb (MonoProfiler *prof, uintptr_t size)
{
prof->gc_heap_resize (prof->profiler, size);
}
void
mono_profiler_install_gc (MonoLegacyProfileGCFunc callback, MonoLegacyProfileGCResizeFunc heap_resize_callback)
{
current->gc_event = callback;
current->gc_heap_resize = heap_resize_callback;
if (callback)
mono_profiler_set_gc_event_callback (current->handle, gc_event_cb);
if (heap_resize_callback)
mono_profiler_set_gc_resize_callback (current->handle, gc_resize_cb);
}
static void
jit_done_cb (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
{
prof->jit_end2 (prof->profiler, method, jinfo, 0);
}
static void
jit_failed_cb (MonoProfiler *prof, MonoMethod *method)
{
prof->jit_end2 (prof->profiler, method, NULL, 1);
}
void
mono_profiler_install_jit_end (MonoLegacyProfileJitResult end)
{
current->jit_end2 = end;
if (end) {
mono_profiler_set_jit_done_callback (current->handle, jit_done_cb);
mono_profiler_set_jit_failed_callback (current->handle, jit_failed_cb);
}
}
void
mono_profiler_set_events (int flags)
{
/* Do nothing. */
}
static void
allocation_cb (MonoProfiler *prof, MonoObject* object)
{
prof->allocation (prof->profiler, object, object->vtable->klass);
}
void
mono_profiler_install_allocation (MonoLegacyProfileAllocFunc callback)
{
current->allocation = callback;
if (callback)
mono_profiler_set_gc_allocation_callback (current->handle, allocation_cb);
}
static void
enter_cb (MonoProfiler *prof, MonoMethod *method, MonoProfilerCallContext *context)
{
prof->enter (prof->profiler, method);
}
static void
leave_cb (MonoProfiler *prof, MonoMethod *method, MonoProfilerCallContext *context)
{
prof->leave (prof->profiler, method);
}
static void
tail_call_cb (MonoProfiler *prof, MonoMethod *method, MonoMethod *target)
{
prof->leave (prof->profiler, method);
}
void
mono_profiler_install_enter_leave (MonoLegacyProfileMethodFunc enter, MonoLegacyProfileMethodFunc fleave)
{
current->enter = enter;
current->leave = fleave;
if (enter)
mono_profiler_set_method_enter_callback (current->handle, enter_cb);
if (fleave) {
mono_profiler_set_method_leave_callback (current->handle, leave_cb);
mono_profiler_set_method_tail_call_callback (current->handle, tail_call_cb);
}
}
static void
throw_callback_cb (MonoProfiler *prof, MonoObject *exception)
{
prof->throw_callback (prof->profiler, exception);
}
static void
exc_method_leave_cb (MonoProfiler *prof, MonoMethod *method, MonoObject *exception)
{
prof->exc_method_leave (prof->profiler, method);
}
static void
clause_callback_cb (MonoProfiler *prof, MonoMethod *method, uint32_t index, MonoExceptionEnum type, MonoObject *exception)
{
prof->clause_callback (prof->profiler, method, type, index);
}
void
mono_profiler_install_exception (MonoLegacyProfileExceptionFunc throw_callback, MonoLegacyProfileMethodFunc exc_method_leave, MonoLegacyProfileExceptionClauseFunc clause_callback)
{
current->throw_callback = throw_callback;
current->exc_method_leave = exc_method_leave;
current->clause_callback = clause_callback;
if (throw_callback)
mono_profiler_set_exception_throw_callback (current->handle, throw_callback_cb);
if (exc_method_leave)
mono_profiler_set_method_exception_leave_callback (current->handle, exc_method_leave_cb);
if (clause_callback)
mono_profiler_set_exception_clause_callback (current->handle, clause_callback_cb);
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/md/heaps/stringheap.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: StringHeap.h
//
//
// Classes code:MetaData::StringHeapRO and code:MetaData::StringHeapRW represent #String heap.
// The #String heap stores null-terminated UTF-8 strings (as defined in CLI ECMA specification). Elements
// are indexed by code:#StringHeapIndex.
//
//#StringHeapIndex
// String heap indexes are 0-based. They are stored the same way in the table columns (i.e. there is no
// 0-based vs. 1-based index difference as in table record indexes code:TableRecordStorage).
//
// ======================================================================================
#pragma once
#include "external.h"
namespace MetaData
{
// --------------------------------------------------------------------------------------
//
// This class represents read-only #String heap with all utility methods.
//
class StringHeapRO
{
friend class StringHeapRW;
private:
//
// Private data
//
// The storage of strings.
StgPoolReadOnly m_StringPool;
public:
//
// Initialization
//
__checkReturn
inline HRESULT Initialize(
DataBlob sourceData,
BOOL fCopyData)
{
_ASSERTE(!fCopyData);
return m_StringPool.InitOnMemReadOnly((void *)sourceData.GetDataPointer(), sourceData.GetSize());
}
inline void Delete()
{
return m_StringPool.Uninit();
}
public:
//
// Getters
//
__checkReturn
inline HRESULT GetString(
UINT32 nIndex,
_Outptr_result_z_ LPCSTR *pszString) const
{
return const_cast<StgPoolReadOnly &>(m_StringPool).GetStringReadOnly(
nIndex,
pszString);
}
// Gets raw size (in bytes) of the represented strings.
inline UINT32 GetUnalignedSize() const
{
return m_StringPool.GetPoolSize();
}
}; // class StringHeapRO
// --------------------------------------------------------------------------------------
//
// This class represents read-write #String heap with all utility methods.
//
class StringHeapRW
{
private:
//
// Private data
//
// The storage of strings.
StgStringPool m_StringPool;
public:
//
// Initialization
//
__checkReturn
inline HRESULT InitializeEmpty(
UINT32 cbAllocationSize
COMMA_INDEBUG_MD(BOOL debug_fIsReadWrite))
{
return m_StringPool.InitNew(cbAllocationSize, 0);
}
__checkReturn
inline HRESULT InitializeEmpty_WithItemsCount(
UINT32 cbAllocationSize,
UINT32 cItemsCount
COMMA_INDEBUG_MD(BOOL debug_fIsReadWrite))
{
return m_StringPool.InitNew(cbAllocationSize, cItemsCount);
}
__checkReturn
inline HRESULT Initialize(
DataBlob sourceData,
BOOL fCopyData)
{
return m_StringPool.InitOnMem((void *)sourceData.GetDataPointer(), sourceData.GetSize(), !fCopyData);
}
__checkReturn
inline HRESULT InitializeFromStringHeap(
const StringHeapRO *pSourceStringHeap,
BOOL fCopyData)
{
return m_StringPool.InitOnMem(
(void *)pSourceStringHeap->m_StringPool.GetSegData(),
pSourceStringHeap->m_StringPool.GetDataSize(),
!fCopyData);
}
__checkReturn
inline HRESULT InitializeFromStringHeap(
const StringHeapRW *pSourceStringHeap,
BOOL fCopyData)
{
return m_StringPool.InitOnMem(
(void *)pSourceStringHeap->m_StringPool.GetSegData(),
pSourceStringHeap->m_StringPool.GetDataSize(),
!fCopyData);
}
// Destroys the string heap and all its allocated data. Can run on uninitialized string heap.
inline void Delete()
{
return m_StringPool.Uninit();
}
public:
//
// Getters
//
__checkReturn
inline HRESULT GetString(
UINT32 nIndex,
_Outptr_result_z_ LPCSTR *pszString) const
{
return const_cast<StgStringPool &>(m_StringPool).GetString(
nIndex,
pszString);
}
// Gets raw size (in bytes) of the represented strings. Doesn't align the size as code:GetAlignedSize.
inline UINT32 GetUnalignedSize() const
{
return m_StringPool.GetRawSize();
}
// Gets size (in bytes) aligned up to 4-bytes of the represented strings.
// Fills *pcbSize with 0 on error.
__checkReturn
inline HRESULT GetAlignedSize(
_Out_ UINT32 *pcbSize) const
{
return m_StringPool.GetSaveSize(pcbSize);
}
// Returns TRUE if the string heap is empty (even if it contains only default empty string).
inline BOOL IsEmpty() const
{
return const_cast<StgStringPool &>(m_StringPool).IsEmpty();
}
// Returns TRUE if the string index (nIndex, see code:#StringHeapIndex) is valid (i.e. in the string
// heap).
inline BOOL IsValidIndex(UINT32 nIndex) const
{
return const_cast<StgStringPool &>(m_StringPool).IsValidCookie(nIndex);
}
__checkReturn
inline HRESULT SaveToStream_Aligned(
UINT32 nStartIndex,
_In_ IStream *pStream) const
{
if (nStartIndex == 0)
{
return const_cast<StgStringPool &>(m_StringPool).PersistToStream(pStream);
}
if (nStartIndex == m_StringPool.GetRawSize())
{
_ASSERTE(!m_StringPool.HaveEdits());
return S_OK;
}
_ASSERTE(m_StringPool.HaveEdits());
_ASSERTE(nStartIndex == m_StringPool.GetOffsetOfEdit());
return const_cast<StgStringPool &>(m_StringPool).PersistPartialToStream(pStream, nStartIndex);
}
public:
//
// Heap modifications
//
// Adds null-terminated UTF-8 string (szString) to the end of the heap (incl. its null-terminator).
// Returns S_OK and index of added string (*pnIndex).
// Returns error code otherwise (and fills *pnIndex with 0).
__checkReturn
inline HRESULT AddString(
_In_z_ LPCSTR szString,
_Out_ UINT32 *pnIndex)
{
return m_StringPool.AddString(szString, pnIndex);
}
// Adds null-terminated UTF-16 string (wszString) to the end of the heap (incl. its null-terminator).
// Returns S_OK and index of added string (*pnIndex).
// Returns error code otherwise (and fills *pnIndex with 0).
__checkReturn
inline HRESULT AddStringW(
_In_z_ LPCWSTR wszString,
_Out_ UINT32 *pnIndex)
{
return m_StringPool.AddStringW(wszString, pnIndex);
}
// Adds data from *pSourceStringHeap starting at index (nStartSourceIndex) to the string heap.
// Returns S_OK (even if the source is empty) or error code.
__checkReturn
inline HRESULT AddStringHeap(
const StringHeapRW *pSourceStringHeap,
UINT32 nStartSourceIndex)
{
return m_StringPool.CopyPool(
nStartSourceIndex,
&pSourceStringHeap->m_StringPool);
} // StringHeapRW::AddStringHeap
__checkReturn
inline HRESULT MakeWritable()
{
return m_StringPool.ConvertToRW();
}
public:
//
// Tracking of heap modifications for EnC
//
//#EnCSessionTracking
// EnC session starts automatically with initialization (code:Initialize or code:InitializeEmpty) or by
// user's explicit call to code:StartNewEnCSession. The heap stores its actual data size, so we can find
// out if some data were added later.
// Gets heap size (in bytes) from the beginning of the last EnC session (code:#EnCSessionTracking).
inline UINT32 GetEnCSessionStartHeapSize() const
{
if (m_StringPool.HaveEdits())
{
return m_StringPool.GetOffsetOfEdit();
}
return m_StringPool.GetRawSize();
}
// Starts new EnC session (code:#EnCSessionTracking).
inline void StartNewEnCSession()
{
m_StringPool.ResetOffsetOfEdit();
}
// Gets size (in bytes) aligned to 4-bytes of adds made from the beginning of the last EnC session.
__checkReturn
inline HRESULT GetEnCSessionAddedHeapSize_Aligned(
_Out_ UINT32 *pcbSize) const
{
if (m_StringPool.HaveEdits())
{
return m_StringPool.GetEditSaveSize(pcbSize);
}
*pcbSize = 0;
return S_OK;
}
}; // class StringHeapRW
}; // namespace MetaData
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: StringHeap.h
//
//
// Classes code:MetaData::StringHeapRO and code:MetaData::StringHeapRW represent #String heap.
// The #String heap stores null-terminated UTF-8 strings (as defined in CLI ECMA specification). Elements
// are indexed by code:#StringHeapIndex.
//
//#StringHeapIndex
// String heap indexes are 0-based. They are stored the same way in the table columns (i.e. there is no
// 0-based vs. 1-based index difference as in table record indexes code:TableRecordStorage).
//
// ======================================================================================
#pragma once
#include "external.h"
namespace MetaData
{
// --------------------------------------------------------------------------------------
//
// This class represents read-only #String heap with all utility methods.
//
class StringHeapRO
{
friend class StringHeapRW;
private:
//
// Private data
//
// The storage of strings.
StgPoolReadOnly m_StringPool;
public:
//
// Initialization
//
__checkReturn
inline HRESULT Initialize(
DataBlob sourceData,
BOOL fCopyData)
{
_ASSERTE(!fCopyData);
return m_StringPool.InitOnMemReadOnly((void *)sourceData.GetDataPointer(), sourceData.GetSize());
}
inline void Delete()
{
return m_StringPool.Uninit();
}
public:
//
// Getters
//
__checkReturn
inline HRESULT GetString(
UINT32 nIndex,
_Outptr_result_z_ LPCSTR *pszString) const
{
return const_cast<StgPoolReadOnly &>(m_StringPool).GetStringReadOnly(
nIndex,
pszString);
}
// Gets raw size (in bytes) of the represented strings.
inline UINT32 GetUnalignedSize() const
{
return m_StringPool.GetPoolSize();
}
}; // class StringHeapRO
// --------------------------------------------------------------------------------------
//
// This class represents read-write #String heap with all utility methods.
//
class StringHeapRW
{
private:
//
// Private data
//
// The storage of strings.
StgStringPool m_StringPool;
public:
//
// Initialization
//
__checkReturn
inline HRESULT InitializeEmpty(
UINT32 cbAllocationSize
COMMA_INDEBUG_MD(BOOL debug_fIsReadWrite))
{
return m_StringPool.InitNew(cbAllocationSize, 0);
}
__checkReturn
inline HRESULT InitializeEmpty_WithItemsCount(
UINT32 cbAllocationSize,
UINT32 cItemsCount
COMMA_INDEBUG_MD(BOOL debug_fIsReadWrite))
{
return m_StringPool.InitNew(cbAllocationSize, cItemsCount);
}
__checkReturn
inline HRESULT Initialize(
DataBlob sourceData,
BOOL fCopyData)
{
return m_StringPool.InitOnMem((void *)sourceData.GetDataPointer(), sourceData.GetSize(), !fCopyData);
}
__checkReturn
inline HRESULT InitializeFromStringHeap(
const StringHeapRO *pSourceStringHeap,
BOOL fCopyData)
{
return m_StringPool.InitOnMem(
(void *)pSourceStringHeap->m_StringPool.GetSegData(),
pSourceStringHeap->m_StringPool.GetDataSize(),
!fCopyData);
}
__checkReturn
inline HRESULT InitializeFromStringHeap(
const StringHeapRW *pSourceStringHeap,
BOOL fCopyData)
{
return m_StringPool.InitOnMem(
(void *)pSourceStringHeap->m_StringPool.GetSegData(),
pSourceStringHeap->m_StringPool.GetDataSize(),
!fCopyData);
}
// Destroys the string heap and all its allocated data. Can run on uninitialized string heap.
inline void Delete()
{
return m_StringPool.Uninit();
}
public:
//
// Getters
//
__checkReturn
inline HRESULT GetString(
UINT32 nIndex,
_Outptr_result_z_ LPCSTR *pszString) const
{
return const_cast<StgStringPool &>(m_StringPool).GetString(
nIndex,
pszString);
}
// Gets raw size (in bytes) of the represented strings. Doesn't align the size as code:GetAlignedSize.
inline UINT32 GetUnalignedSize() const
{
return m_StringPool.GetRawSize();
}
// Gets size (in bytes) aligned up to 4-bytes of the represented strings.
// Fills *pcbSize with 0 on error.
__checkReturn
inline HRESULT GetAlignedSize(
_Out_ UINT32 *pcbSize) const
{
return m_StringPool.GetSaveSize(pcbSize);
}
// Returns TRUE if the string heap is empty (even if it contains only default empty string).
inline BOOL IsEmpty() const
{
return const_cast<StgStringPool &>(m_StringPool).IsEmpty();
}
// Returns TRUE if the string index (nIndex, see code:#StringHeapIndex) is valid (i.e. in the string
// heap).
inline BOOL IsValidIndex(UINT32 nIndex) const
{
return const_cast<StgStringPool &>(m_StringPool).IsValidCookie(nIndex);
}
__checkReturn
inline HRESULT SaveToStream_Aligned(
UINT32 nStartIndex,
_In_ IStream *pStream) const
{
if (nStartIndex == 0)
{
return const_cast<StgStringPool &>(m_StringPool).PersistToStream(pStream);
}
if (nStartIndex == m_StringPool.GetRawSize())
{
_ASSERTE(!m_StringPool.HaveEdits());
return S_OK;
}
_ASSERTE(m_StringPool.HaveEdits());
_ASSERTE(nStartIndex == m_StringPool.GetOffsetOfEdit());
return const_cast<StgStringPool &>(m_StringPool).PersistPartialToStream(pStream, nStartIndex);
}
public:
//
// Heap modifications
//
// Adds null-terminated UTF-8 string (szString) to the end of the heap (incl. its null-terminator).
// Returns S_OK and index of added string (*pnIndex).
// Returns error code otherwise (and fills *pnIndex with 0).
__checkReturn
inline HRESULT AddString(
_In_z_ LPCSTR szString,
_Out_ UINT32 *pnIndex)
{
return m_StringPool.AddString(szString, pnIndex);
}
// Adds null-terminated UTF-16 string (wszString) to the end of the heap (incl. its null-terminator).
// Returns S_OK and index of added string (*pnIndex).
// Returns error code otherwise (and fills *pnIndex with 0).
__checkReturn
inline HRESULT AddStringW(
_In_z_ LPCWSTR wszString,
_Out_ UINT32 *pnIndex)
{
return m_StringPool.AddStringW(wszString, pnIndex);
}
// Adds data from *pSourceStringHeap starting at index (nStartSourceIndex) to the string heap.
// Returns S_OK (even if the source is empty) or error code.
__checkReturn
inline HRESULT AddStringHeap(
const StringHeapRW *pSourceStringHeap,
UINT32 nStartSourceIndex)
{
return m_StringPool.CopyPool(
nStartSourceIndex,
&pSourceStringHeap->m_StringPool);
} // StringHeapRW::AddStringHeap
__checkReturn
inline HRESULT MakeWritable()
{
return m_StringPool.ConvertToRW();
}
public:
//
// Tracking of heap modifications for EnC
//
//#EnCSessionTracking
// EnC session starts automatically with initialization (code:Initialize or code:InitializeEmpty) or by
// user's explicit call to code:StartNewEnCSession. The heap stores its actual data size, so we can find
// out if some data were added later.
// Gets heap size (in bytes) from the beginning of the last EnC session (code:#EnCSessionTracking).
inline UINT32 GetEnCSessionStartHeapSize() const
{
if (m_StringPool.HaveEdits())
{
return m_StringPool.GetOffsetOfEdit();
}
return m_StringPool.GetRawSize();
}
// Starts new EnC session (code:#EnCSessionTracking).
inline void StartNewEnCSession()
{
m_StringPool.ResetOffsetOfEdit();
}
// Gets size (in bytes) aligned to 4-bytes of adds made from the beginning of the last EnC session.
__checkReturn
inline HRESULT GetEnCSessionAddedHeapSize_Aligned(
_Out_ UINT32 *pcbSize) const
{
if (m_StringPool.HaveEdits())
{
return m_StringPool.GetEditSaveSize(pcbSize);
}
*pcbSize = 0;
return S_OK;
}
}; // class StringHeapRW
}; // namespace MetaData
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/vm/comsynchronizable.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Header: COMSynchronizable.h
**
** Purpose: Native methods on System.SynchronizableObject
** and its subclasses.
**
**
===========================================================*/
#ifndef _COMSYNCHRONIZABLE_H
#define _COMSYNCHRONIZABLE_H
#include "field.h" // For FieldDesc definition.
//
// Each function that we call through native only gets one argument,
// which is actually a pointer to its stack of arguments. Our structs
// for accessing these are defined below.
//
struct SharedState;
class ThreadNative
{
friend class ThreadBaseObject;
public:
enum
{
PRIORITY_LOWEST = 0,
PRIORITY_BELOW_NORMAL = 1,
PRIORITY_NORMAL = 2,
PRIORITY_ABOVE_NORMAL = 3,
PRIORITY_HIGHEST = 4,
};
enum
{
ThreadStopRequested = 1,
ThreadSuspendRequested = 2,
ThreadBackground = 4,
ThreadUnstarted = 8,
ThreadStopped = 16,
ThreadWaitSleepJoin = 32,
ThreadSuspended = 64,
ThreadAbortRequested = 128,
};
enum
{
ApartmentSTA = 0,
ApartmentMTA = 1,
ApartmentUnknown = 2
};
static FCDECL1(INT32, GetPriority, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(void, SetPriority, ThreadBaseObject* pThisUNSAFE, INT32 iPriority);
static FCDECL1(void, Interrupt, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(FC_BOOL_RET, IsAlive, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(FC_BOOL_RET, Join, ThreadBaseObject* pThisUNSAFE, INT32 Timeout);
#undef Sleep
static FCDECL1(void, Sleep, INT32 iTime);
#define Sleep(a) Dont_Use_Sleep(a)
static FCDECL1(void, Initialize, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(void, SetBackground, ThreadBaseObject* pThisUNSAFE, CLR_BOOL isBackground);
static FCDECL1(FC_BOOL_RET, IsBackground, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(INT32, GetThreadState, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(INT32, GetThreadContext, ThreadBaseObject* pThisUNSAFE);
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
static FCDECL1(INT32, GetApartmentState, ThreadBaseObject* pThis);
static FCDECL2(INT32, SetApartmentState, ThreadBaseObject* pThisUNSAFE, INT32 iState);
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
static FCDECL1(INT32, GetManagedThreadId, ThreadBaseObject* th);
static FCDECL0(INT32, GetOptimalMaxSpinWaitsPerSpinIteration);
static FCDECL1(void, SpinWait, int iterations);
static FCDECL0(Object*, GetCurrentThread);
static FCDECL1(void, Finalize, ThreadBaseObject* pThis);
#ifdef FEATURE_COMINTEROP
static FCDECL1(void, DisableComObjectEagerCleanup, ThreadBaseObject* pThis);
#endif //FEATURE_COMINTEROP
static FCDECL1(FC_BOOL_RET,IsThreadpoolThread, ThreadBaseObject* thread);
static FCDECL1(void, SetIsThreadpoolThread, ThreadBaseObject* thread);
static FCDECL0(INT32, GetCurrentProcessorNumber);
static void Start(Thread* pNewThread, int threadStackSize, int priority, PCWSTR pThreadName);
static void InformThreadNameChange(Thread* pThread, LPCWSTR name, INT32 len);
private:
struct KickOffThread_Args {
Thread *pThread;
SharedState *share;
ULONG retVal;
};
static void KickOffThread_Worker(LPVOID /* KickOffThread_Args* */);
static ULONG WINAPI KickOffThread(void *pass);
static BOOL DoJoin(THREADBASEREF DyingThread, INT32 timeout);
};
extern "C" void QCALLTYPE ThreadNative_Start(QCall::ThreadHandle thread, int threadStackSize, int priority, PCWSTR pThreadName);
extern "C" void QCALLTYPE ThreadNative_UninterruptibleSleep0();
extern "C" void QCALLTYPE ThreadNative_InformThreadNameChange(QCall::ThreadHandle thread, LPCWSTR name, INT32 len);
extern "C" UINT64 QCALLTYPE ThreadNative_GetProcessDefaultStackSize();
extern "C" BOOL QCALLTYPE ThreadNative_YieldThread();
extern "C" UINT64 QCALLTYPE ThreadNative_GetCurrentOSThreadId();
#endif // _COMSYNCHRONIZABLE_H
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Header: COMSynchronizable.h
**
** Purpose: Native methods on System.SynchronizableObject
** and its subclasses.
**
**
===========================================================*/
#ifndef _COMSYNCHRONIZABLE_H
#define _COMSYNCHRONIZABLE_H
#include "field.h" // For FieldDesc definition.
//
// Each function that we call through native only gets one argument,
// which is actually a pointer to its stack of arguments. Our structs
// for accessing these are defined below.
//
struct SharedState;
class ThreadNative
{
friend class ThreadBaseObject;
public:
enum
{
PRIORITY_LOWEST = 0,
PRIORITY_BELOW_NORMAL = 1,
PRIORITY_NORMAL = 2,
PRIORITY_ABOVE_NORMAL = 3,
PRIORITY_HIGHEST = 4,
};
enum
{
ThreadStopRequested = 1,
ThreadSuspendRequested = 2,
ThreadBackground = 4,
ThreadUnstarted = 8,
ThreadStopped = 16,
ThreadWaitSleepJoin = 32,
ThreadSuspended = 64,
ThreadAbortRequested = 128,
};
enum
{
ApartmentSTA = 0,
ApartmentMTA = 1,
ApartmentUnknown = 2
};
static FCDECL1(INT32, GetPriority, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(void, SetPriority, ThreadBaseObject* pThisUNSAFE, INT32 iPriority);
static FCDECL1(void, Interrupt, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(FC_BOOL_RET, IsAlive, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(FC_BOOL_RET, Join, ThreadBaseObject* pThisUNSAFE, INT32 Timeout);
#undef Sleep
static FCDECL1(void, Sleep, INT32 iTime);
#define Sleep(a) Dont_Use_Sleep(a)
static FCDECL1(void, Initialize, ThreadBaseObject* pThisUNSAFE);
static FCDECL2(void, SetBackground, ThreadBaseObject* pThisUNSAFE, CLR_BOOL isBackground);
static FCDECL1(FC_BOOL_RET, IsBackground, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(INT32, GetThreadState, ThreadBaseObject* pThisUNSAFE);
static FCDECL1(INT32, GetThreadContext, ThreadBaseObject* pThisUNSAFE);
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
static FCDECL1(INT32, GetApartmentState, ThreadBaseObject* pThis);
static FCDECL2(INT32, SetApartmentState, ThreadBaseObject* pThisUNSAFE, INT32 iState);
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
static FCDECL1(INT32, GetManagedThreadId, ThreadBaseObject* th);
static FCDECL0(INT32, GetOptimalMaxSpinWaitsPerSpinIteration);
static FCDECL1(void, SpinWait, int iterations);
static FCDECL0(Object*, GetCurrentThread);
static FCDECL1(void, Finalize, ThreadBaseObject* pThis);
#ifdef FEATURE_COMINTEROP
static FCDECL1(void, DisableComObjectEagerCleanup, ThreadBaseObject* pThis);
#endif //FEATURE_COMINTEROP
static FCDECL1(FC_BOOL_RET,IsThreadpoolThread, ThreadBaseObject* thread);
static FCDECL1(void, SetIsThreadpoolThread, ThreadBaseObject* thread);
static FCDECL0(INT32, GetCurrentProcessorNumber);
static void Start(Thread* pNewThread, int threadStackSize, int priority, PCWSTR pThreadName);
static void InformThreadNameChange(Thread* pThread, LPCWSTR name, INT32 len);
private:
struct KickOffThread_Args {
Thread *pThread;
SharedState *share;
ULONG retVal;
};
static void KickOffThread_Worker(LPVOID /* KickOffThread_Args* */);
static ULONG WINAPI KickOffThread(void *pass);
static BOOL DoJoin(THREADBASEREF DyingThread, INT32 timeout);
};
extern "C" void QCALLTYPE ThreadNative_Start(QCall::ThreadHandle thread, int threadStackSize, int priority, PCWSTR pThreadName);
extern "C" void QCALLTYPE ThreadNative_UninterruptibleSleep0();
extern "C" void QCALLTYPE ThreadNative_InformThreadNameChange(QCall::ThreadHandle thread, LPCWSTR name, INT32 len);
extern "C" UINT64 QCALLTYPE ThreadNative_GetProcessDefaultStackSize();
extern "C" BOOL QCALLTYPE ThreadNative_YieldThread();
extern "C" UINT64 QCALLTYPE ThreadNative_GetCurrentOSThreadId();
#endif // _COMSYNCHRONIZABLE_H
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/jit/jitstd/vector.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ==++==
//
//
//
// ==--==
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX vector<T> XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#pragma once
#include "allocator.h"
#include "iterator.h"
namespace jitstd
{
template <typename T, typename Allocator = allocator<T> >
class vector
{
public:
typedef Allocator allocator_type;
typedef T* pointer;
typedef T& reference;
typedef const T* const_pointer;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T value_type;
// nested classes
class iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
iterator(T* ptr);
public:
iterator();
iterator(const iterator& it);
iterator& operator++();
iterator& operator++(int);
iterator& operator--();
iterator& operator--(int);
iterator operator+(difference_type n);
iterator operator-(difference_type n);
size_type operator-(const iterator& that);
bool operator==(const iterator& it);
bool operator!=(const iterator& it);
T& operator*();
T* operator&();
operator T*();
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class const_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
const_iterator(T* ptr);
const_iterator();
public:
const_iterator(const const_iterator& it);
const_iterator& operator++();
const_iterator& operator++(int);
const_iterator& operator--();
const_iterator& operator--(int);
const_iterator operator+(difference_type n);
const_iterator operator-(difference_type n);
size_type operator-(const const_iterator& that);
bool operator==(const const_iterator& it) const;
bool operator!=(const const_iterator& it) const;
const T& operator*() const;
const T* operator&() const;
operator const T*() const;
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class reverse_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
reverse_iterator(T* ptr);
public:
reverse_iterator();
reverse_iterator(const reverse_iterator& it);
reverse_iterator& operator++();
reverse_iterator& operator++(int);
reverse_iterator& operator--();
reverse_iterator& operator--(int);
reverse_iterator operator+(difference_type n);
reverse_iterator operator-(difference_type n);
size_type operator-(const reverse_iterator& that);
bool operator==(const reverse_iterator& it);
bool operator!=(const reverse_iterator& it);
T& operator*();
T* operator&();
operator T*();
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class const_reverse_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
const_reverse_iterator(T* ptr);
public:
const_reverse_iterator();
const_reverse_iterator(const const_reverse_iterator& it);
const_reverse_iterator& operator++();
const_reverse_iterator& operator++(int);
const_reverse_iterator& operator--();
const_reverse_iterator& operator--(int);
const_reverse_iterator operator+(difference_type n);
const_reverse_iterator operator-(difference_type n);
size_type operator-(const const_reverse_iterator& that);
bool operator==(const const_reverse_iterator& it) const;
bool operator!=(const const_reverse_iterator& it) const;
const T& operator*() const;
const T* operator&() const;
operator const T*() const;
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
// ctors
explicit vector(const Allocator& allocator);
explicit vector(size_type n, const T& value, const Allocator& allocator);
template <typename InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& allocator);
// cctors
vector(const vector& vec);
template <typename Alt, typename AltAllocator>
explicit vector(const vector<Alt, AltAllocator>& vec);
// dtor
~vector();
template <class InputIterator>
void assign(InputIterator first, InputIterator last);
void assign(size_type size, const T& value);
const_reference at(size_type n) const;
reference at(size_type n);
reference back();
const_reference back() const;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
size_type capacity() const;
void clear();
bool empty() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
iterator erase(iterator position);
iterator erase(iterator first, iterator last);
reference front();
const_reference front() const;
allocator_type get_allocator() const;
iterator insert(iterator position, const T& value);
void insert(iterator position, size_type size, const T& value);
template <typename InputIterator>
void insert(iterator position, InputIterator first, InputIterator last);
size_type max_size() const;
vector& operator=(const vector& vec);
template <typename Alt, typename AltAllocator>
vector<T, Allocator>& operator=(const vector<Alt, AltAllocator>& vec);
reference operator[](size_type n);
const_reference operator[](size_type n) const;
void pop_back();
void push_back(const T& value);
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
void reserve(size_type n);
void resize(size_type sz, const T&);
size_type size() const;
T* data() { return m_pArray; }
void swap(vector<T, Allocator>& vec);
private:
typename Allocator::template rebind<T>::allocator m_allocator;
T* m_pArray;
size_type m_nSize;
size_type m_nCapacity;
inline
bool ensure_capacity(size_type capacity);
template <typename InputIterator>
void construct_helper(InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void construct_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag);
void construct_helper(size_type size, const T& value);
template <typename InputIterator>
void insert_helper(iterator iter, InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void insert_helper(iterator iter, InputIterator first, InputIterator last, int_not_an_iterator_tag);
void insert_elements_helper(iterator iter, size_type size, const T& value);
template <typename InputIterator>
void assign_helper(InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void assign_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag);
template <typename Alt, typename AltAllocator>
friend class vector;
};
}// namespace jitstd
// Implementation of vector.
namespace jitstd
{
namespace
{
template <typename InputIterator>
size_t iterator_difference(InputIterator first, const InputIterator& last)
{
size_t size = 0;
for (; first != last; ++first, ++size);
return size;
}
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(nullptr)
, m_nSize(0)
, m_nCapacity(0)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(size_type size, const T& value, const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
construct_helper(size, value);
}
template <typename T, typename Allocator>
template <typename InputIterator>
vector<T, Allocator>::vector(InputIterator first, InputIterator last, const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
construct_helper(first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
template <typename Alt, typename AltAllocator>
vector<T, Allocator>::vector(const vector<Alt, AltAllocator>& vec)
: m_allocator(vec.m_allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
ensure_capacity(vec.m_nSize);
for (size_type i = 0, j = 0; i < vec.m_nSize; ++i, ++j)
{
new (m_pArray + i, placement_t()) T((T) vec.m_pArray[j]);
}
m_nSize = vec.m_nSize;
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(const vector<T, Allocator>& vec)
: m_allocator(vec.m_allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
ensure_capacity(vec.m_nSize);
for (size_type i = 0, j = 0; i < vec.m_nSize; ++i, ++j)
{
new (m_pArray + i, placement_t()) T(vec.m_pArray[j]);
}
m_nSize = vec.m_nSize;
}
template <typename T, typename Allocator>
vector<T, Allocator>::~vector()
{
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i].~T();
}
m_allocator.deallocate(m_pArray, m_nCapacity);
m_nSize = 0;
m_nCapacity = 0;
}
// public methods
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign(InputIterator first, InputIterator last)
{
construct_helper(first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
void vector<T, Allocator>::assign(size_type size, const T& value)
{
ensure_capacity(size);
for (int i = 0; i < size; ++i)
{
m_pArray[i] = value;
}
m_nSize = size;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::at(size_type i) const
{
return operator[](i);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::at(size_type i)
{
return operator[](i);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::back()
{
return operator[](m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::back() const
{
return operator[](m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::begin()
{
return iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::begin() const
{
return const_iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::cbegin() const
{
return const_iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::capacity() const
{
return m_nCapacity;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::clear()
{
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i].~T();
}
m_nSize = 0;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::empty() const
{
return m_nSize == 0;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::end()
{
return iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::end() const
{
return const_iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::cend() const
{
return const_iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(
typename vector<T, Allocator>::iterator position)
{
return erase(position, position + 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(
typename vector<T, Allocator>::iterator first,
typename vector<T, Allocator>::iterator last)
{
assert(m_nSize > 0);
assert(first.m_pElem >= m_pArray);
assert(last.m_pElem >= m_pArray);
assert(first.m_pElem <= m_pArray + m_nSize);
assert(last.m_pElem <= m_pArray + m_nSize);
assert(last.m_pElem > first.m_pElem);
pointer fptr = first.m_pElem;
pointer lptr = last.m_pElem;
pointer eptr = m_pArray + m_nSize;
for (; lptr != eptr; ++lptr, fptr++)
{
(*fptr).~T();
*fptr = *lptr;
}
m_nSize -= (size_type)(lptr - fptr);
return first;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::front()
{
return operator[](0);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::front() const
{
return operator[](0);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::allocator_type
vector<T, Allocator>::get_allocator() const
{
return m_allocator;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(
typename vector<T, Allocator>::iterator iter,
const T& value)
{
size_type pos = (size_type) (iter.m_pElem - m_pArray);
insert_elements_helper(iter, 1, value);
return iterator(m_pArray + pos);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::insert(
iterator iter,
size_type size,
const T& value)
{
insert_elements_helper(iter, size, value);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert(
iterator iter,
InputIterator first,
InputIterator last)
{
insert_helper(iter, first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::max_size() const
{
return ((size_type) -1) >> 1;
}
template <typename T, typename Allocator>
template <typename Alt, typename AltAllocator>
vector<T, Allocator>& vector<T, Allocator>::operator=(const vector<Alt, AltAllocator>& vec)
{
// We'll not observe copy-on-write for now.
m_allocator = vec.m_allocator;
ensure_capacity(vec.m_nSize);
m_nSize = vec.m_nSize;
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i] = (T) vec.m_pArray[i];
}
return *this;
}
template <typename T, typename Allocator>
vector<T, Allocator>& vector<T, Allocator>::operator=(const vector<T, Allocator>& vec)
{
if (this == &vec)
{
return *this;
}
// We'll not observe copy-on-write for now.
m_allocator = vec.m_allocator;
ensure_capacity(vec.m_nSize);
m_nSize = vec.m_nSize;
for (size_type i = 0; i < m_nSize; ++i)
{
new (m_pArray + i, placement_t()) T(vec.m_pArray[i]);
}
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference vector<T, Allocator>::operator[](size_type n)
{
return m_pArray[n];
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::operator[](size_type n) const
{
return m_pArray[n];
}
template <typename T, typename Allocator>
void vector<T, Allocator>::pop_back()
{
m_pArray[m_nSize - 1].~T();
--m_nSize;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::push_back(const T& value)
{
ensure_capacity(m_nSize + 1);
new (m_pArray + m_nSize, placement_t()) T(value);
++m_nSize;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::rbegin()
{
return reverse_iterator(m_pArray + m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rbegin() const
{
return const_reverse_iterator(m_pArray + m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator
vector<T, Allocator>::rend()
{
return reverse_iterator(m_pArray - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rend() const
{
return const_reverse_iterator(m_pArray - 1);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::reserve(size_type n)
{
ensure_capacity(n);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::resize(
size_type sz,
const T& c)
{
for (; m_nSize > sz; m_nSize--)
{
m_pArray[m_nSize - 1].~T();
}
ensure_capacity(sz);
for (; m_nSize < sz; m_nSize++)
{
new (m_pArray + m_nSize, placement_t()) T(c);
}
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type vector<T, Allocator>::size() const
{
return m_nSize;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::swap(vector<T, Allocator>& vec)
{
std::swap(m_pArray, vec.m_pArray);
std::swap(m_nSize, vec.m_nSize);
std::swap(m_nCapacity, vec.m_nCapacity);
std::swap(m_nCapacity, vec.m_nCapacity);
std::swap(m_allocator, vec.m_allocator);
}
// =======================================================================================
template <typename T, typename Allocator>
void vector<T, Allocator>::construct_helper(size_type size, const T& value)
{
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + i, placement_t()) T(value);
}
m_nSize = size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::construct_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
construct_helper(first, last);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::construct_helper(InputIterator first, InputIterator last, forward_iterator_tag)
{
size_type size = iterator_difference(first, last);
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + i, placement_t()) T(*first);
first++;
}
m_nSize = size;
}
// =======================================================================================
template <typename T, typename Allocator>
void vector<T, Allocator>::insert_elements_helper(iterator iter, size_type size, const T& value)
{
assert(size < max_size());
// m_pElem could be NULL then m_pArray would be NULL too.
size_type pos = iter.m_pElem - m_pArray;
assert(pos <= m_nSize); // <= could insert at end.
assert(pos >= 0);
ensure_capacity(m_nSize + size);
for (int src = m_nSize - 1, dst = m_nSize + size - 1; src >= (int) pos; --src, --dst)
{
m_pArray[dst] = m_pArray[src];
}
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + pos + i, placement_t()) T(value);
}
m_nSize += size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert_helper(iterator iter, InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
insert_elements_helper(iter, first, last);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert_helper(iterator iter, InputIterator first, InputIterator last, forward_iterator_tag)
{
// m_pElem could be NULL then m_pArray would be NULL too.
size_type pos = iter.m_pElem - m_pArray;
assert(pos <= m_nSize); // <= could insert at end.
assert(pos >= 0);
size_type size = iterator_difference(first, last);
assert(size < max_size());
ensure_capacity(m_nSize + size);
pointer lst = m_pArray + m_nSize + size - 1;
for (size_type i = pos; i < m_nSize; ++i)
{
*lst-- = m_pArray[i];
}
for (size_type i = 0; i < size; ++i, ++first)
{
m_pArray[pos + i] = *first;
}
m_nSize += size;
}
// =======================================================================================
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign_helper(InputIterator first, InputIterator last, forward_iterator_tag)
{
size_type size = iterator_difference(first, last);
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
m_pArray[i] = *first;
first++;
}
m_nSize = size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
assign_helper(first, last);
}
// =======================================================================================
template <typename T, typename Allocator>
bool vector<T, Allocator>::ensure_capacity(size_type newCap)
{
if (newCap <= m_nCapacity)
{
return false;
}
// Double the alloc capacity based on size.
size_type allocCap = m_nSize * 2;
// Is it still not sufficient?
if (allocCap < newCap)
{
allocCap = newCap;
}
// Allocate space.
pointer ptr = m_allocator.allocate(allocCap);
// Copy over.
for (size_type i = 0; i < m_nSize; ++i)
{
new (ptr + i, placement_t()) T(m_pArray[i]);
}
// Deallocate currently allocated space.
m_allocator.deallocate(m_pArray, m_nCapacity);
// Update the pointers and capacity;
m_pArray = ptr;
m_nCapacity = allocCap;
return true;
}
} // end of namespace jitstd.
// Implementation of vector iterators
namespace jitstd
{
// iterator
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator(const iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator++()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator++(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator--()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator--(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::iterator::operator+(difference_type n)
{
return iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::iterator::operator-(difference_type n)
{
return iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::iterator::operator-(
const typename vector<T, Allocator>::iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::iterator::operator==(const iterator& it)
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::iterator::operator!=(const iterator& it)
{
return !operator==(it);
}
template <typename T, typename Allocator>
T& vector<T, Allocator>::iterator::operator*()
{
return *m_pElem;
}
template <typename T, typename Allocator>
T* vector<T, Allocator>::iterator::operator&()
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::operator T*()
{
return m_pElem;
}
// const_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator(const const_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator++()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator++(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator--()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator--(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::const_iterator::operator+(difference_type n)
{
return const_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::const_iterator::operator-(difference_type n)
{
return const_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::const_iterator::operator-(
const typename vector<T, Allocator>::const_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_iterator::operator==(const const_iterator& it) const
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_iterator::operator!=(const const_iterator& it) const
{
return !operator==(it);
}
template <typename T, typename Allocator>
const T& vector<T, Allocator>::const_iterator::operator*() const
{
return *m_pElem;
}
template <typename T, typename Allocator>
const T* vector<T, Allocator>::const_iterator::operator&() const
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::operator const T*() const
{
return &m_pElem;
}
// reverse_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator(const reverse_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator++()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator++(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator--()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator--(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::reverse_iterator::operator+(difference_type n)
{
return reverse_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::reverse_iterator::operator-(difference_type n)
{
return reverse_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::reverse_iterator::operator-(
const typename vector<T, Allocator>::reverse_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::reverse_iterator::operator==(const reverse_iterator& it)
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::reverse_iterator::operator!=(const reverse_iterator& it)
{
return !operator==(it);
}
template <typename T, typename Allocator>
T& vector<T, Allocator>::reverse_iterator::operator*()
{
return *m_pElem;
}
template <typename T, typename Allocator>
T* vector<T, Allocator>::reverse_iterator::operator&()
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::operator T*()
{
return m_pElem;
}
// const_reverse_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator(const const_reverse_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator++()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator++(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator--()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator--(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator vector<T, Allocator>::const_reverse_iterator::operator+(difference_type n)
{
return const_reverse_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator vector<T, Allocator>::const_reverse_iterator::operator-(difference_type n)
{
return const_reverse_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::const_reverse_iterator::operator-(
const typename vector<T, Allocator>::const_reverse_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_reverse_iterator::operator==(const const_reverse_iterator& it) const
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_reverse_iterator::operator!=(const const_reverse_iterator& it) const
{
return !operator==(it);
}
template <typename T, typename Allocator>
const T& vector<T, Allocator>::const_reverse_iterator::operator*() const
{
return *m_pElem;
}
template <typename T, typename Allocator>
const T* vector<T, Allocator>::const_reverse_iterator::operator&() const
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::operator const T*() const
{
return &m_pElem;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ==++==
//
//
//
// ==--==
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX vector<T> XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#pragma once
#include "allocator.h"
#include "iterator.h"
namespace jitstd
{
template <typename T, typename Allocator = allocator<T> >
class vector
{
public:
typedef Allocator allocator_type;
typedef T* pointer;
typedef T& reference;
typedef const T* const_pointer;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T value_type;
// nested classes
class iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
iterator(T* ptr);
public:
iterator();
iterator(const iterator& it);
iterator& operator++();
iterator& operator++(int);
iterator& operator--();
iterator& operator--(int);
iterator operator+(difference_type n);
iterator operator-(difference_type n);
size_type operator-(const iterator& that);
bool operator==(const iterator& it);
bool operator!=(const iterator& it);
T& operator*();
T* operator&();
operator T*();
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class const_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
const_iterator(T* ptr);
const_iterator();
public:
const_iterator(const const_iterator& it);
const_iterator& operator++();
const_iterator& operator++(int);
const_iterator& operator--();
const_iterator& operator--(int);
const_iterator operator+(difference_type n);
const_iterator operator-(difference_type n);
size_type operator-(const const_iterator& that);
bool operator==(const const_iterator& it) const;
bool operator!=(const const_iterator& it) const;
const T& operator*() const;
const T* operator&() const;
operator const T*() const;
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class reverse_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
reverse_iterator(T* ptr);
public:
reverse_iterator();
reverse_iterator(const reverse_iterator& it);
reverse_iterator& operator++();
reverse_iterator& operator++(int);
reverse_iterator& operator--();
reverse_iterator& operator--(int);
reverse_iterator operator+(difference_type n);
reverse_iterator operator-(difference_type n);
size_type operator-(const reverse_iterator& that);
bool operator==(const reverse_iterator& it);
bool operator!=(const reverse_iterator& it);
T& operator*();
T* operator&();
operator T*();
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
class const_reverse_iterator : public jitstd::iterator<random_access_iterator_tag, T>
{
private:
const_reverse_iterator(T* ptr);
public:
const_reverse_iterator();
const_reverse_iterator(const const_reverse_iterator& it);
const_reverse_iterator& operator++();
const_reverse_iterator& operator++(int);
const_reverse_iterator& operator--();
const_reverse_iterator& operator--(int);
const_reverse_iterator operator+(difference_type n);
const_reverse_iterator operator-(difference_type n);
size_type operator-(const const_reverse_iterator& that);
bool operator==(const const_reverse_iterator& it) const;
bool operator!=(const const_reverse_iterator& it) const;
const T& operator*() const;
const T* operator&() const;
operator const T*() const;
private:
friend class vector<T, Allocator>;
pointer m_pElem;
};
// ctors
explicit vector(const Allocator& allocator);
explicit vector(size_type n, const T& value, const Allocator& allocator);
template <typename InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& allocator);
// cctors
vector(const vector& vec);
template <typename Alt, typename AltAllocator>
explicit vector(const vector<Alt, AltAllocator>& vec);
// dtor
~vector();
template <class InputIterator>
void assign(InputIterator first, InputIterator last);
void assign(size_type size, const T& value);
const_reference at(size_type n) const;
reference at(size_type n);
reference back();
const_reference back() const;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
size_type capacity() const;
void clear();
bool empty() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
iterator erase(iterator position);
iterator erase(iterator first, iterator last);
reference front();
const_reference front() const;
allocator_type get_allocator() const;
iterator insert(iterator position, const T& value);
void insert(iterator position, size_type size, const T& value);
template <typename InputIterator>
void insert(iterator position, InputIterator first, InputIterator last);
size_type max_size() const;
vector& operator=(const vector& vec);
template <typename Alt, typename AltAllocator>
vector<T, Allocator>& operator=(const vector<Alt, AltAllocator>& vec);
reference operator[](size_type n);
const_reference operator[](size_type n) const;
void pop_back();
void push_back(const T& value);
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
void reserve(size_type n);
void resize(size_type sz, const T&);
size_type size() const;
T* data() { return m_pArray; }
void swap(vector<T, Allocator>& vec);
private:
typename Allocator::template rebind<T>::allocator m_allocator;
T* m_pArray;
size_type m_nSize;
size_type m_nCapacity;
inline
bool ensure_capacity(size_type capacity);
template <typename InputIterator>
void construct_helper(InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void construct_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag);
void construct_helper(size_type size, const T& value);
template <typename InputIterator>
void insert_helper(iterator iter, InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void insert_helper(iterator iter, InputIterator first, InputIterator last, int_not_an_iterator_tag);
void insert_elements_helper(iterator iter, size_type size, const T& value);
template <typename InputIterator>
void assign_helper(InputIterator first, InputIterator last, forward_iterator_tag);
template <typename InputIterator>
void assign_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag);
template <typename Alt, typename AltAllocator>
friend class vector;
};
}// namespace jitstd
// Implementation of vector.
namespace jitstd
{
namespace
{
template <typename InputIterator>
size_t iterator_difference(InputIterator first, const InputIterator& last)
{
size_t size = 0;
for (; first != last; ++first, ++size);
return size;
}
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(nullptr)
, m_nSize(0)
, m_nCapacity(0)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(size_type size, const T& value, const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
construct_helper(size, value);
}
template <typename T, typename Allocator>
template <typename InputIterator>
vector<T, Allocator>::vector(InputIterator first, InputIterator last, const Allocator& allocator)
: m_allocator(allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
construct_helper(first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
template <typename Alt, typename AltAllocator>
vector<T, Allocator>::vector(const vector<Alt, AltAllocator>& vec)
: m_allocator(vec.m_allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
ensure_capacity(vec.m_nSize);
for (size_type i = 0, j = 0; i < vec.m_nSize; ++i, ++j)
{
new (m_pArray + i, placement_t()) T((T) vec.m_pArray[j]);
}
m_nSize = vec.m_nSize;
}
template <typename T, typename Allocator>
vector<T, Allocator>::vector(const vector<T, Allocator>& vec)
: m_allocator(vec.m_allocator)
, m_pArray(NULL)
, m_nSize(0)
, m_nCapacity(0)
{
ensure_capacity(vec.m_nSize);
for (size_type i = 0, j = 0; i < vec.m_nSize; ++i, ++j)
{
new (m_pArray + i, placement_t()) T(vec.m_pArray[j]);
}
m_nSize = vec.m_nSize;
}
template <typename T, typename Allocator>
vector<T, Allocator>::~vector()
{
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i].~T();
}
m_allocator.deallocate(m_pArray, m_nCapacity);
m_nSize = 0;
m_nCapacity = 0;
}
// public methods
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign(InputIterator first, InputIterator last)
{
construct_helper(first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
void vector<T, Allocator>::assign(size_type size, const T& value)
{
ensure_capacity(size);
for (int i = 0; i < size; ++i)
{
m_pArray[i] = value;
}
m_nSize = size;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::at(size_type i) const
{
return operator[](i);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::at(size_type i)
{
return operator[](i);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::back()
{
return operator[](m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::back() const
{
return operator[](m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::begin()
{
return iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::begin() const
{
return const_iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::cbegin() const
{
return const_iterator(m_pArray);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::capacity() const
{
return m_nCapacity;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::clear()
{
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i].~T();
}
m_nSize = 0;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::empty() const
{
return m_nSize == 0;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::end()
{
return iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator
vector<T, Allocator>::end() const
{
return const_iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::cend() const
{
return const_iterator(m_pArray + m_nSize);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(
typename vector<T, Allocator>::iterator position)
{
return erase(position, position + 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::erase(
typename vector<T, Allocator>::iterator first,
typename vector<T, Allocator>::iterator last)
{
assert(m_nSize > 0);
assert(first.m_pElem >= m_pArray);
assert(last.m_pElem >= m_pArray);
assert(first.m_pElem <= m_pArray + m_nSize);
assert(last.m_pElem <= m_pArray + m_nSize);
assert(last.m_pElem > first.m_pElem);
pointer fptr = first.m_pElem;
pointer lptr = last.m_pElem;
pointer eptr = m_pArray + m_nSize;
for (; lptr != eptr; ++lptr, fptr++)
{
(*fptr).~T();
*fptr = *lptr;
}
m_nSize -= (size_type)(lptr - fptr);
return first;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference
vector<T, Allocator>::front()
{
return operator[](0);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::front() const
{
return operator[](0);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::allocator_type
vector<T, Allocator>::get_allocator() const
{
return m_allocator;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator
vector<T, Allocator>::insert(
typename vector<T, Allocator>::iterator iter,
const T& value)
{
size_type pos = (size_type) (iter.m_pElem - m_pArray);
insert_elements_helper(iter, 1, value);
return iterator(m_pArray + pos);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::insert(
iterator iter,
size_type size,
const T& value)
{
insert_elements_helper(iter, size, value);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert(
iterator iter,
InputIterator first,
InputIterator last)
{
insert_helper(iter, first, last, iterator_traits<InputIterator>::iterator_category());
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::max_size() const
{
return ((size_type) -1) >> 1;
}
template <typename T, typename Allocator>
template <typename Alt, typename AltAllocator>
vector<T, Allocator>& vector<T, Allocator>::operator=(const vector<Alt, AltAllocator>& vec)
{
// We'll not observe copy-on-write for now.
m_allocator = vec.m_allocator;
ensure_capacity(vec.m_nSize);
m_nSize = vec.m_nSize;
for (size_type i = 0; i < m_nSize; ++i)
{
m_pArray[i] = (T) vec.m_pArray[i];
}
return *this;
}
template <typename T, typename Allocator>
vector<T, Allocator>& vector<T, Allocator>::operator=(const vector<T, Allocator>& vec)
{
if (this == &vec)
{
return *this;
}
// We'll not observe copy-on-write for now.
m_allocator = vec.m_allocator;
ensure_capacity(vec.m_nSize);
m_nSize = vec.m_nSize;
for (size_type i = 0; i < m_nSize; ++i)
{
new (m_pArray + i, placement_t()) T(vec.m_pArray[i]);
}
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reference vector<T, Allocator>::operator[](size_type n)
{
return m_pArray[n];
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reference
vector<T, Allocator>::operator[](size_type n) const
{
return m_pArray[n];
}
template <typename T, typename Allocator>
void vector<T, Allocator>::pop_back()
{
m_pArray[m_nSize - 1].~T();
--m_nSize;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::push_back(const T& value)
{
ensure_capacity(m_nSize + 1);
new (m_pArray + m_nSize, placement_t()) T(value);
++m_nSize;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::rbegin()
{
return reverse_iterator(m_pArray + m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rbegin() const
{
return const_reverse_iterator(m_pArray + m_nSize - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator
vector<T, Allocator>::rend()
{
return reverse_iterator(m_pArray - 1);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator
vector<T, Allocator>::rend() const
{
return const_reverse_iterator(m_pArray - 1);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::reserve(size_type n)
{
ensure_capacity(n);
}
template <typename T, typename Allocator>
void vector<T, Allocator>::resize(
size_type sz,
const T& c)
{
for (; m_nSize > sz; m_nSize--)
{
m_pArray[m_nSize - 1].~T();
}
ensure_capacity(sz);
for (; m_nSize < sz; m_nSize++)
{
new (m_pArray + m_nSize, placement_t()) T(c);
}
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type vector<T, Allocator>::size() const
{
return m_nSize;
}
template <typename T, typename Allocator>
void vector<T, Allocator>::swap(vector<T, Allocator>& vec)
{
std::swap(m_pArray, vec.m_pArray);
std::swap(m_nSize, vec.m_nSize);
std::swap(m_nCapacity, vec.m_nCapacity);
std::swap(m_nCapacity, vec.m_nCapacity);
std::swap(m_allocator, vec.m_allocator);
}
// =======================================================================================
template <typename T, typename Allocator>
void vector<T, Allocator>::construct_helper(size_type size, const T& value)
{
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + i, placement_t()) T(value);
}
m_nSize = size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::construct_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
construct_helper(first, last);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::construct_helper(InputIterator first, InputIterator last, forward_iterator_tag)
{
size_type size = iterator_difference(first, last);
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + i, placement_t()) T(*first);
first++;
}
m_nSize = size;
}
// =======================================================================================
template <typename T, typename Allocator>
void vector<T, Allocator>::insert_elements_helper(iterator iter, size_type size, const T& value)
{
assert(size < max_size());
// m_pElem could be NULL then m_pArray would be NULL too.
size_type pos = iter.m_pElem - m_pArray;
assert(pos <= m_nSize); // <= could insert at end.
assert(pos >= 0);
ensure_capacity(m_nSize + size);
for (int src = m_nSize - 1, dst = m_nSize + size - 1; src >= (int) pos; --src, --dst)
{
m_pArray[dst] = m_pArray[src];
}
for (size_type i = 0; i < size; ++i)
{
new (m_pArray + pos + i, placement_t()) T(value);
}
m_nSize += size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert_helper(iterator iter, InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
insert_elements_helper(iter, first, last);
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::insert_helper(iterator iter, InputIterator first, InputIterator last, forward_iterator_tag)
{
// m_pElem could be NULL then m_pArray would be NULL too.
size_type pos = iter.m_pElem - m_pArray;
assert(pos <= m_nSize); // <= could insert at end.
assert(pos >= 0);
size_type size = iterator_difference(first, last);
assert(size < max_size());
ensure_capacity(m_nSize + size);
pointer lst = m_pArray + m_nSize + size - 1;
for (size_type i = pos; i < m_nSize; ++i)
{
*lst-- = m_pArray[i];
}
for (size_type i = 0; i < size; ++i, ++first)
{
m_pArray[pos + i] = *first;
}
m_nSize += size;
}
// =======================================================================================
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign_helper(InputIterator first, InputIterator last, forward_iterator_tag)
{
size_type size = iterator_difference(first, last);
ensure_capacity(size);
for (size_type i = 0; i < size; ++i)
{
m_pArray[i] = *first;
first++;
}
m_nSize = size;
}
template <typename T, typename Allocator>
template <typename InputIterator>
void vector<T, Allocator>::assign_helper(InputIterator first, InputIterator last, int_not_an_iterator_tag)
{
assign_helper(first, last);
}
// =======================================================================================
template <typename T, typename Allocator>
bool vector<T, Allocator>::ensure_capacity(size_type newCap)
{
if (newCap <= m_nCapacity)
{
return false;
}
// Double the alloc capacity based on size.
size_type allocCap = m_nSize * 2;
// Is it still not sufficient?
if (allocCap < newCap)
{
allocCap = newCap;
}
// Allocate space.
pointer ptr = m_allocator.allocate(allocCap);
// Copy over.
for (size_type i = 0; i < m_nSize; ++i)
{
new (ptr + i, placement_t()) T(m_pArray[i]);
}
// Deallocate currently allocated space.
m_allocator.deallocate(m_pArray, m_nCapacity);
// Update the pointers and capacity;
m_pArray = ptr;
m_nCapacity = allocCap;
return true;
}
} // end of namespace jitstd.
// Implementation of vector iterators
namespace jitstd
{
// iterator
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::iterator(const iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator++()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator++(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator--()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator& vector<T, Allocator>::iterator::operator--(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::iterator::operator+(difference_type n)
{
return iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::iterator vector<T, Allocator>::iterator::operator-(difference_type n)
{
return iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::iterator::operator-(
const typename vector<T, Allocator>::iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::iterator::operator==(const iterator& it)
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::iterator::operator!=(const iterator& it)
{
return !operator==(it);
}
template <typename T, typename Allocator>
T& vector<T, Allocator>::iterator::operator*()
{
return *m_pElem;
}
template <typename T, typename Allocator>
T* vector<T, Allocator>::iterator::operator&()
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::iterator::operator T*()
{
return m_pElem;
}
// const_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::const_iterator(const const_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator++()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator++(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator--()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator& vector<T, Allocator>::const_iterator::operator--(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::const_iterator::operator+(difference_type n)
{
return const_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_iterator vector<T, Allocator>::const_iterator::operator-(difference_type n)
{
return const_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::const_iterator::operator-(
const typename vector<T, Allocator>::const_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_iterator::operator==(const const_iterator& it) const
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_iterator::operator!=(const const_iterator& it) const
{
return !operator==(it);
}
template <typename T, typename Allocator>
const T& vector<T, Allocator>::const_iterator::operator*() const
{
return *m_pElem;
}
template <typename T, typename Allocator>
const T* vector<T, Allocator>::const_iterator::operator&() const
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_iterator::operator const T*() const
{
return &m_pElem;
}
// reverse_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::reverse_iterator(const reverse_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator++()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator++(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator--()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator& vector<T, Allocator>::reverse_iterator::operator--(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::reverse_iterator::operator+(difference_type n)
{
return reverse_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::reverse_iterator vector<T, Allocator>::reverse_iterator::operator-(difference_type n)
{
return reverse_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::reverse_iterator::operator-(
const typename vector<T, Allocator>::reverse_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::reverse_iterator::operator==(const reverse_iterator& it)
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::reverse_iterator::operator!=(const reverse_iterator& it)
{
return !operator==(it);
}
template <typename T, typename Allocator>
T& vector<T, Allocator>::reverse_iterator::operator*()
{
return *m_pElem;
}
template <typename T, typename Allocator>
T* vector<T, Allocator>::reverse_iterator::operator&()
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::reverse_iterator::operator T*()
{
return m_pElem;
}
// const_reverse_iterator
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator()
: m_pElem(NULL)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator(T* ptr)
: m_pElem(ptr)
{
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::const_reverse_iterator(const const_reverse_iterator& it)
: m_pElem(it.m_pElem)
{
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator++()
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator++(int)
{
--m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator--()
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator& vector<T, Allocator>::const_reverse_iterator::operator--(int)
{
++m_pElem;
return *this;
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator vector<T, Allocator>::const_reverse_iterator::operator+(difference_type n)
{
return const_reverse_iterator(m_pElem + n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::const_reverse_iterator vector<T, Allocator>::const_reverse_iterator::operator-(difference_type n)
{
return const_reverse_iterator(m_pElem - n);
}
template <typename T, typename Allocator>
typename vector<T, Allocator>::size_type
vector<T, Allocator>::const_reverse_iterator::operator-(
const typename vector<T, Allocator>::const_reverse_iterator& that)
{
return m_pElem - that.m_pElem;
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_reverse_iterator::operator==(const const_reverse_iterator& it) const
{
return (m_pElem == it.m_pElem);
}
template <typename T, typename Allocator>
bool vector<T, Allocator>::const_reverse_iterator::operator!=(const const_reverse_iterator& it) const
{
return !operator==(it);
}
template <typename T, typename Allocator>
const T& vector<T, Allocator>::const_reverse_iterator::operator*() const
{
return *m_pElem;
}
template <typename T, typename Allocator>
const T* vector<T, Allocator>::const_reverse_iterator::operator&() const
{
return &m_pElem;
}
template <typename T, typename Allocator>
vector<T, Allocator>::const_reverse_iterator::operator const T*() const
{
return &m_pElem;
}
}
| -1 |
dotnet/runtime | 66,213 | [mono] Put WeakAttribute support under an ifdef | This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | lambdageek | 2022-03-04T19:50:51Z | 2022-03-08T14:08:40Z | 34880aaeb463cc17268b44aecb80dda0914cfa01 | 8342a08b8bf0ff2ffb64cd5992e2d60c8d6d63c1 | [mono] Put WeakAttribute support under an ifdef. This code has been effectively dead in .NET 6 on all platforms since `System.WeakAttribute` is not in CoreLib (it was a pre-.NET 5 mono-specific extension)
Not everything is removed:
- `MonoClass:has_weak_fields` bit is still present (and always 0).
- the AOT compiler still emits a (size 0) `weak_field_indexes` symbol (but the AOT runtime reader code is under an ifdef). Likewise the AOT table definitions, etc are still there. It seemed unnecessary to perturb the AOT format. | ./src/coreclr/vm/comdatetime.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _COMDATETIME_H_
#define _COMDATETIME_H_
#include <oleauto.h>
#include "fcall.h"
#include <pshpack1.h>
class COMDateTime {
static const INT64 TicksPerMillisecond;
static const INT64 TicksPerSecond;
static const INT64 TicksPerMinute;
static const INT64 TicksPerHour;
static const INT64 TicksPerDay;
static const INT64 MillisPerSecond;
static const INT64 MillisPerDay;
static const int DaysPer4Years;
static const int DaysPer100Years;
static const int DaysPer400Years;
// Number of days from 1/1/0001 to 1/1/10000
static const int DaysTo10000;
static const int DaysTo1899;
static const INT64 DoubleDateOffset;
static const INT64 OADateMinAsTicks; // in ticks
static const double OADateMinAsDouble;
static const double OADateMaxAsDouble;
static const INT64 MaxTicks;
static const INT64 MaxMillis;
public:
// Native util functions for other classes.
static INT64 DoubleDateToTicks(const double d); // From OleAut Date
static double TicksToDoubleDate(const INT64 ticks);
};
#include <poppack.h>
#endif // _COMDATETIME_H_
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _COMDATETIME_H_
#define _COMDATETIME_H_
#include <oleauto.h>
#include "fcall.h"
#include <pshpack1.h>
class COMDateTime {
static const INT64 TicksPerMillisecond;
static const INT64 TicksPerSecond;
static const INT64 TicksPerMinute;
static const INT64 TicksPerHour;
static const INT64 TicksPerDay;
static const INT64 MillisPerSecond;
static const INT64 MillisPerDay;
static const int DaysPer4Years;
static const int DaysPer100Years;
static const int DaysPer400Years;
// Number of days from 1/1/0001 to 1/1/10000
static const int DaysTo10000;
static const int DaysTo1899;
static const INT64 DoubleDateOffset;
static const INT64 OADateMinAsTicks; // in ticks
static const double OADateMinAsDouble;
static const double OADateMaxAsDouble;
static const INT64 MaxTicks;
static const INT64 MaxMillis;
public:
// Native util functions for other classes.
static INT64 DoubleDateToTicks(const double d); // From OleAut Date
static double TicksToDoubleDate(const INT64 ticks);
};
#include <poppack.h>
#endif // _COMDATETIME_H_
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.