Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature]: Trimmable DotNet Project #304

Merged
merged 136 commits into from
Aug 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
136 commits
Select commit Hold shift + click to select a range
9fba18b
move dynamic code into a separate project
ds5678 Apr 26, 2022
507ab54
move FieldReader to dynamic project
ds5678 Apr 26, 2022
43d1aa5
more descriptive trim warnings
ds5678 Apr 26, 2022
9e404cb
make dynamic method body creation private
ds5678 Apr 26, 2022
640403d
Bump System.Text.Json from 6.0.4 to 6.0.5
dependabot[bot] Jun 15, 2022
410b90d
Basic read support PDB info stream.
Washi1337 Jun 16, 2022
8e4de81
Add write support for pdb hash tables and info stream.
Washi1337 Jun 18, 2022
8375199
Add BinaryStreamReader.ReadBytesUntil overload that can strip off the…
Washi1337 Jun 18, 2022
bc5ce14
Add basic read support for DBI stream header.
Washi1337 Jun 18, 2022
3ef199a
Add read support for dbi module descriptors.
Washi1337 Jun 18, 2022
09d5166
Add read support section contributions to DBI header.
Washi1337 Jun 19, 2022
f982803
Add read support section mappings in DBI stream.
Washi1337 Jun 19, 2022
3573e63
Add basic read support for typeservermap substream.
Washi1337 Jun 21, 2022
0f6032c
Add basic read support for ec substream.
Washi1337 Jun 21, 2022
fea51df
Add read support for source file collections.
Washi1337 Jun 21, 2022
5f700ac
Add read support extra dbg stream indices.
Washi1337 Jun 21, 2022
6f169b5
Add write support for DBI stream.
Washi1337 Jun 24, 2022
d510ec9
Add BinaryStreamReader.ReadUtf8String
Washi1337 Jun 24, 2022
e4ef4c1
Explode DbiStream.BuildNumber into major, minor and newfileformat ver…
Washi1337 Jun 24, 2022
c7039c5
BUGFIX: Include pdb hash table and feature codes in size computation …
Washi1337 Jun 25, 2022
e871718
Use for loop to avoid heap allocated enumerator.
Washi1337 Jun 25, 2022
a774186
Merge pull request #326 from Washi1337/feature/pdb-meta-streams
Washi1337 Jun 25, 2022
3aa01a9
Add unusual typeref order test.
Washi1337 Jul 8, 2022
c73a427
Naive implementation of MetadataTableBuffer.Insert.
Washi1337 Jul 8, 2022
f60f298
Optimize availability boolean list using bitlists.
Washi1337 Jul 8, 2022
5542366
Add member resolution to older .NET version test.
Washi1337 Jul 9, 2022
57b0cb5
BUGFIX: Disable exact assembly version match in signature comparisons…
Washi1337 Jul 9, 2022
1948c5d
Merge branch 'master' into hotfix/md-resolution-version-check
Washi1337 Jul 9, 2022
c052097
Fix merge conflict once again. git please git gud.
Washi1337 Jul 9, 2022
9b51059
Merge pull request #330 from Washi1337/hotfix/preserve-order-nested-t…
Washi1337 Jul 9, 2022
de84e0e
Merge pull request #331 from Washi1337/hotfix/md-resolution-version-c…
Washi1337 Jul 9, 2022
b43b84a
Normalize newlines in json test.
Washi1337 Jul 9, 2022
37e8dde
Skip native method body test on non-windows platforms.
Washi1337 Jul 9, 2022
5954241
List main features of AsmResolver in readme.
Washi1337 Jul 9, 2022
e2d65b5
Version bump to v4.11.2
Washi1337 Jul 9, 2022
09103b2
Merge branch 'master' into development
Washi1337 Jul 9, 2022
5419a46
Bump Nullable from 1.3.0 to 1.3.1
dependabot[bot] Jul 11, 2022
7426481
Basic PDB symbol interpretation.
Washi1337 Jul 15, 2022
5f9528c
Add S_PUB32 symbol read support.
Washi1337 Jul 15, 2022
ee231d5
Add S_UDT read support.
Washi1337 Jul 15, 2022
8e26e83
Add PDB stream index checks.
Washi1337 Jul 15, 2022
f0cd900
Rename SymbolRecord -> CodeViewSymbol.
Washi1337 Jul 16, 2022
5170115
Add basic TPI/IPI read support.
Washi1337 Jul 16, 2022
92760d7
Add simple type index parsing.
Washi1337 Jul 20, 2022
6434d0b
Extract serialized classes for symbol records.
Washi1337 Jul 20, 2022
9c2f42d
Move sample pdb image to fixture.
Washi1337 Jul 20, 2022
4e898c5
Add S_CONSTANT read support.
Washi1337 Jul 20, 2022
63d0f96
Add basic LF_ENUM read support.
Washi1337 Jul 20, 2022
e5592d0
Rename Types to Leaves.
Washi1337 Jul 21, 2022
d81e0a4
Add read support for LF_FIELDLIST and LF_ENUMERATE records.
Washi1337 Jul 27, 2022
1ef794e
BUGFIX: TpiStream::TryGetTypeRecordReader should return a reader that…
Washi1337 Jul 27, 2022
cecbf4a
Rename EnumerateLeaf to EnumerateField. Add missing xmldoc.
Washi1337 Jul 27, 2022
f04ec64
Add read support LF_POINTER records.
Washi1337 Jul 27, 2022
f168740
Add read support for LF_MODIFIER records.
Washi1337 Jul 27, 2022
ca8436e
Rename UnknownCodeViewType to UnknownCodeViewLeaf
Washi1337 Jul 27, 2022
53f3e8b
Add convenience properties to ModifierType.
Washi1337 Jul 27, 2022
1e9cc01
Extract CodeViewComplexType from EnumType, add read support for LF_CL…
Washi1337 Jul 27, 2022
6bd00ed
Add read support LF_VTSHAPE records.
Washi1337 Jul 28, 2022
9e5a9db
BUGFIX: Shift by 4 instead of 8 for reading vtable shape entries.
Washi1337 Jul 28, 2022
b548e82
Add type tests.
Washi1337 Jul 28, 2022
8b449cc
Add read support for LF_MEMBER records.
Washi1337 Jul 28, 2022
75e1172
Add read support for LF_ARGLIST, LF_MFUNCTION, LF_METHODLIST and LF_M…
Washi1337 Jul 28, 2022
c367a8f
Add read support for LF_ONEMETHOD records.
Washi1337 Jul 28, 2022
a273559
Add read support LF_BCLASS records.
Washi1337 Jul 28, 2022
eee0f2c
Add read support LF_NESTTYPE and LF_NESTTYPEEX records.
Washi1337 Jul 30, 2022
bb3d977
Extract CodeViewCompositeType base class and read support LF_UNION.
Washi1337 Jul 30, 2022
90bc833
Add read support LF_ARRAY records.
Washi1337 Jul 30, 2022
3766e24
Add read support LF_PROCEDURE records.
Washi1337 Jul 30, 2022
86bffa0
Refactor by adding Leaf or TypeRecord suffixes to CV leaves.
Washi1337 Jul 30, 2022
6ac9cee
Added Callbacks implementation for MemberCloner.
CursedLand Aug 6, 2022
4422b63
Add missing xmldocs.
CursedLand Aug 6, 2022
c1e1639
Add CustomMemberClonerListener tests.
CursedLand Aug 7, 2022
86ab800
Merge pull request #332 from Washi1337/dependabot/nuget/development/N…
Washi1337 Aug 7, 2022
b372492
Merge pull request #325 from Washi1337/dependabot/nuget/development/S…
Washi1337 Aug 7, 2022
17e14ba
Changes Request Applied.
CursedLand Aug 7, 2022
9bd7747
Make TypeDefOrRefSignature.Type settable
JPaja Aug 7, 2022
b3f0444
Update xunit deps.
Washi1337 Aug 8, 2022
80d5d8b
Syntax & Grammer fixs.
CursedLand Aug 8, 2022
b78c244
Fix: GenericType setter
JPaja Aug 9, 2022
fb63f8c
Merge pull request #338 from JPaja/development
Washi1337 Aug 10, 2022
17383f0
Merge pull request #337 from CursedLand/development
Washi1337 Aug 10, 2022
22f7b1e
Add float/double read support in CodeViewLeaf.ReadNumeric.
Washi1337 Aug 10, 2022
4f50531
Add read support for LF_VBCLASS and LF_IVBCLASS records.
Washi1337 Aug 10, 2022
b5048a9
Add read support for LF_STMEMBER records.
Washi1337 Aug 10, 2022
e69c062
Bump Microsoft.NET.Test.Sdk from 17.2.0 to 17.3.0
dependabot[bot] Aug 10, 2022
c6bb816
Add read support for LF_BITFIELD records.
Washi1337 Aug 10, 2022
528c663
Add read support for LF_VFUNCTAB records.
Washi1337 Aug 10, 2022
a72dcd9
Add missing GetFunction override in LF_ONEMETHOD records.
Washi1337 Aug 10, 2022
76f55a8
Rename TypeRecordReader to LeafRecordReader in TPI stream.
Washi1337 Aug 11, 2022
7b3379a
Add BaseClassField::.ctor
Washi1337 Aug 11, 2022
b1d549c
Update xmldoc in calling conventions.
Washi1337 Aug 11, 2022
d2afd6f
Clean up leftover microsoft-pdb comments in leafkind.
Washi1337 Aug 11, 2022
53834b2
Add missing MemberFunctionLeaf::.ctor
Washi1337 Aug 11, 2022
1764c50
Rename MethodListEntry::VFTableOffset to VTableOffset.
Washi1337 Aug 11, 2022
6344941
Add public constructors for methods.
Washi1337 Aug 11, 2022
59e021f
Move name parameter in field constructors to first position for consi…
Washi1337 Aug 11, 2022
4f30643
Rename type to leaf in PdbImage.
Washi1337 Aug 11, 2022
1c1768d
Merge pull request #342 from Washi1337/feature/pdb-image
Washi1337 Aug 12, 2022
ee70984
Merge pull request #343 from Washi1337/dependabot/nuget/development/M…
Washi1337 Aug 12, 2022
90d2ba0
BUGFIX: Performance regression on creating new TypeDefOrRef and Gener…
Washi1337 Aug 16, 2022
505da7a
Add convenience properties in DotNetRuntimeInfo for quick classificat…
Washi1337 Aug 19, 2022
bf3b6cb
BUGFIX: Check if .net directory exists before using it while preservi…
Washi1337 Aug 19, 2022
cb283fc
Refactor ISegment.UpdateOffsets to use RelocationParameters instead.
Washi1337 Aug 20, 2022
27d4def
Remove public imagebase and 32bit properties in TLS directory, and us…
Washi1337 Aug 20, 2022
7e62f4e
Add CodeSegment.UpdateOffsets override. Remove image base argument in…
Washi1337 Aug 20, 2022
e09103f
Remove unused INativeSymbolsProvider.ImageBase property.
Washi1337 Aug 20, 2022
1b03c98
Remove image base arguments in CodeSegment tests.
Washi1337 Aug 20, 2022
c00e898
Add portable pdb table indices.
Washi1337 Aug 20, 2022
c3da2f3
Add DocumentRow structure.
Washi1337 Aug 20, 2022
3a4f938
Add MethodDebugInformationRow structure.
Washi1337 Aug 20, 2022
e605bdb
Add LocalScopeRow structure.
Washi1337 Aug 20, 2022
ff2824b
Add LocalVariableRow structure.
Washi1337 Aug 20, 2022
acc16ba
Add LocalConstant structure.
Washi1337 Aug 20, 2022
0a818e9
Add ImportScopeRow structure.
Washi1337 Aug 20, 2022
df9a7d2
Add StateMachineMethodRow structure.
Washi1337 Aug 20, 2022
a49e1f7
Add CustomDebugInformationRow structure.
Washi1337 Aug 20, 2022
57be35a
Add index encoders and table layouts.
Washi1337 Aug 20, 2022
5b21249
Update docs on new API changes in TLS directory.
Washi1337 Aug 21, 2022
aa159cd
Make relocation parameters mutable to avoid a lot of copying.
Washi1337 Aug 21, 2022
32d2aee
Remove redundant SegmentReference.CanUpdateOffsets
Washi1337 Aug 21, 2022
479f605
Merge pull request #346 from Washi1337/feature/imgbase-in-update-offsets
Washi1337 Aug 21, 2022
591f610
Add ITypeDefOrRef.ToTypeSignature overload taking isValueType paramet…
Washi1337 Aug 21, 2022
a45279b
Update index encoders and token allocators to allow for pdb md table …
Washi1337 Aug 22, 2022
4cfa428
Add PdbStream.
Washi1337 Aug 23, 2022
0c17393
Replace SerializedMetadata's PEReaderContext with more conservative M…
Washi1337 Aug 23, 2022
fa7a3df
Merge branch 'development' into feature/portable-pdb-tables
Washi1337 Aug 23, 2022
e493785
Move VirtualAddress and factory into main AsmResolver library.
Washi1337 Aug 23, 2022
28f812d
Add PdbStream::UpdateRowCounts
Washi1337 Aug 23, 2022
6cfb095
Add TablesStream.ExternalRowCounts, ILazyMetadatStream.
Washi1337 Aug 24, 2022
5fb58c7
Move table initialization and layouts to separate file.
Washi1337 Aug 24, 2022
f0d1605
Add IMetadataTable.IsSorted.
Washi1337 Aug 24, 2022
b2ea332
Include missing test PDB files.
Washi1337 Aug 24, 2022
f1017bf
Only include sorted bits of type system or pdb tables if tables strea…
Washi1337 Aug 25, 2022
6a0ae2c
Merge pull request #348 from Washi1337/feature/portable-pdb-tables
Washi1337 Aug 25, 2022
1aca894
Merge branch 'TrimmableDotNetProject' of https://github.com/ds5678/As…
Washi1337 Aug 25, 2022
558cff9
Move dynamic local variable signature resolution to DynamicMethodHelper
Washi1337 Aug 25, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions AsmResolver.sln
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsmResolver.DotNet.Dynamic.Tests", "test\AsmResolver.DotNet.Dynamic.Tests\AsmResolver.DotNet.Dynamic.Tests.csproj", "{C089D0AB-B428-4136-89CC-7974CB590513}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsmResolver.DotNet.Dynamic", "src\AsmResolver.DotNet.Dynamic\AsmResolver.DotNet.Dynamic.csproj", "{62420213-67AD-40FC-B451-BD05C2437CE3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -422,6 +426,30 @@ Global
{2D1DF5DA-7367-4490-B3F0-B996348E150B}.Release|x64.Build.0 = Release|Any CPU
{2D1DF5DA-7367-4490-B3F0-B996348E150B}.Release|x86.ActiveCfg = Release|Any CPU
{2D1DF5DA-7367-4490-B3F0-B996348E150B}.Release|x86.Build.0 = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|x64.ActiveCfg = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|x64.Build.0 = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|x86.ActiveCfg = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Debug|x86.Build.0 = Debug|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|Any CPU.Build.0 = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|x64.ActiveCfg = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|x64.Build.0 = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|x86.ActiveCfg = Release|Any CPU
{C089D0AB-B428-4136-89CC-7974CB590513}.Release|x86.Build.0 = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|x64.ActiveCfg = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|x64.Build.0 = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|x86.ActiveCfg = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Debug|x86.Build.0 = Debug|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|Any CPU.Build.0 = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|x64.ActiveCfg = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|x64.Build.0 = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|x86.ActiveCfg = Release|Any CPU
{62420213-67AD-40FC-B451-BD05C2437CE3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -459,6 +487,8 @@ Global
{40483E28-C703-4933-BA5B-9512EF6E6A21} = {EA971BB0-94BA-44DB-B16C-212D2DB27E17}
{CF6A7E02-37DC-4963-AC14-76D74ADCD87A} = {B3AF102B-ABE1-41B2-AE48-C40702F45AB0}
{2D1DF5DA-7367-4490-B3F0-B996348E150B} = {B3AF102B-ABE1-41B2-AE48-C40702F45AB0}
{C089D0AB-B428-4136-89CC-7974CB590513} = {786C1732-8C96-45DD-97BB-639C9AA7F45B}
{62420213-67AD-40FC-B451-BD05C2437CE3} = {34A95168-A162-4F6A-803B-B6F221FE9EA6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3302AC79-6D23-4E7D-8C5F-C0C7261044D0}
Expand Down
33 changes: 33 additions & 0 deletions src/AsmResolver.DotNet.Dynamic/AsmResolver.DotNet.Dynamic.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Title>AsmResolver.DotNet.Dynamic</Title>
<Description>Dynamic method support for the AsmResolver executable file inspection toolsuite.</Description>
<PackageTags>exe pe directories imports exports resources dotnet cil inspection manipulation assembly disassembly dynamic</PackageTags>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<NoWarn>1701;1702;NU5105</NoWarn>
<TargetFrameworks>net6.0;netcoreapp3.1;netstandard2.0</TargetFrameworks>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DocumentationFile>bin\Debug\AsmResolver.DotNet.xml</DocumentationFile>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DocumentationFile>bin\Release\AsmResolver.DotNet.xml</DocumentationFile>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\AsmResolver.DotNet\AsmResolver.DotNet.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Nullable" Version="1.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Text.Json" Version="6.0.3" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables;

namespace AsmResolver.DotNet.Code.Cil
namespace AsmResolver.DotNet.Dynamic
{
/// <summary>
/// Provides an implementation of <see cref="ICilOperandResolver"/> that resolves operands based on
Expand All @@ -34,13 +35,13 @@ public DynamicCilOperandResolver(SerializedModuleDefinition contextModule, CilMe
switch (token.Table)
{
case TableIndex.TypeDef:
object? type = _tokens[(int) token.Rid];
object? type = _tokens[(int)token.Rid];
if (type is RuntimeTypeHandle runtimeTypeHandle)
return _importer.ImportType(Type.GetTypeFromHandle(runtimeTypeHandle));
break;

case TableIndex.Field:
object? field = _tokens[(int) token.Rid];
object? field = _tokens[(int)token.Rid];

if (field is null)
return null;
Expand All @@ -61,7 +62,7 @@ public DynamicCilOperandResolver(SerializedModuleDefinition contextModule, CilMe

case TableIndex.Method:
case TableIndex.MemberRef:
object? obj = _tokens[(int) token.Rid];
object? obj = _tokens[(int)token.Rid];

if (obj is null)
return null;
Expand Down Expand Up @@ -94,7 +95,7 @@ public DynamicCilOperandResolver(SerializedModuleDefinition contextModule, CilMe
break;

case TableIndex.StandAloneSig:
var reader = ByteArrayDataSource.CreateReader((byte[]) _tokens[(int) token.Rid]!);
var reader = ByteArrayDataSource.CreateReader((byte[])_tokens[(int)token.Rid]!);
return CallingConventionSignature.FromReader(new BlobReadContext(_readerContext), ref reader);
}

Expand All @@ -104,7 +105,7 @@ public DynamicCilOperandResolver(SerializedModuleDefinition contextModule, CilMe
/// <inheritdoc />
public override object? ResolveString(MetadataToken token)
{
return _tokens[(int) token.Rid] as string;
return _tokens[(int)token.Rid] as string;
}
}
}
101 changes: 101 additions & 0 deletions src/AsmResolver.DotNet.Dynamic/DynamicMethodDefinition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.DotNet.Signatures.Types;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables;
using MethodAttributes = AsmResolver.PE.DotNet.Metadata.Tables.Rows.MethodAttributes;

namespace AsmResolver.DotNet.Dynamic
{
/// <summary>
/// Represents a single method in a type definition of a .NET module.
/// </summary>
public class DynamicMethodDefinition : MethodDefinition
{
/// <summary>
/// Create a Dynamic Method Definition
/// </summary>
/// <param name="module">Target Module</param>
/// <param name="dynamicMethodObj">Dynamic Method / Delegate / DynamicResolver</param>
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Calls ResolveDynamicResolver and FromDynamicMethod")]
public DynamicMethodDefinition(ModuleDefinition module, object dynamicMethodObj) :
base(new MetadataToken(TableIndex.Method, 0))
{
dynamicMethodObj = DynamicMethodHelper.ResolveDynamicResolver(dynamicMethodObj);
var methodBase = FieldReader.ReadField<MethodBase>(dynamicMethodObj, "m_method");
if (methodBase is null)
{
throw new ArgumentException(
"Could not get the underlying method base in the provided dynamic method object.");
}

Module = module;
Name = methodBase.Name;
Attributes = (MethodAttributes)methodBase.Attributes;
Signature = new ReferenceImporter(module).ImportMethodSignature(ResolveSig(methodBase, module));
CilMethodBody = ToCilMethodBody(this, dynamicMethodObj);
}

private MethodSignature ResolveSig(MethodBase methodBase, ModuleDefinition module)
{
var imp = new ReferenceImporter(module);
var returnType = methodBase is MethodInfo info
? imp.ImportTypeSignature(info.ReturnType)
: module.CorLibTypeFactory.Void;

var parameters = methodBase.GetParameters();

var parameterTypes = new TypeSignature[parameters.Length];
for (int i = 0; i < parameterTypes.Length; i++)
parameterTypes[i] = imp.ImportTypeSignature(parameters[i].ParameterType);

return new MethodSignature(
methodBase.IsStatic ? 0 : CallingConventionAttributes.HasThis,
returnType, parameterTypes);
}

/// <inheritdoc />
public override ModuleDefinition Module { get; }

/// <summary>
/// Creates a CIL method body from a dynamic method.
/// </summary>
/// <param name="method">The method that owns the method body.</param>
/// <param name="dynamicMethodObj">The Dynamic Method/Delegate/DynamicResolver.</param>
/// <returns>The method body.</returns>
public static CilMethodBody ToCilMethodBody(MethodDefinition method, object dynamicMethodObj)
ds5678 marked this conversation as resolved.
Show resolved Hide resolved
{
if (!(method.Module is SerializedModuleDefinition module))
throw new ArgumentException("Method body should reference a serialized module.");

var result = new CilMethodBody(method);
dynamicMethodObj = DynamicMethodHelper.ResolveDynamicResolver(dynamicMethodObj);

//Get Runtime Fields
byte[] code = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_code")!;
object scope = FieldReader.ReadField<object>(dynamicMethodObj, "m_scope")!;
var tokenList = FieldReader.ReadField<List<object?>>(scope, "m_tokens")!;
byte[] localSig = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_localSignature")!;
byte[] ehHeader = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_exceptionHeader")!;
var ehInfos = FieldReader.ReadField<IList<object>>(dynamicMethodObj, "m_exceptions")!;

//Local Variables
DynamicMethodHelper.ReadLocalVariables(result, method, localSig);

// Read raw instructions.
var reader = ByteArrayDataSource.CreateReader(code);
var disassembler = new CilDisassembler(reader, new DynamicCilOperandResolver(module, result, tokenList));
result.Instructions.AddRange(disassembler.ReadInstructions());

//Exception Handlers
DynamicMethodHelper.ReadReflectionExceptionHandlers(result, ehInfos, ehHeader, new ReferenceImporter(module));

return result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Cil;

namespace AsmResolver.DotNet
namespace AsmResolver.DotNet.Dynamic
{
internal static class DynamicMethodHelper
{
Expand All @@ -34,10 +34,10 @@ public static void ReadReflectionExceptionHandlers(CilMethodBody methodBody,
IList<object>? ehInfos, byte[] ehHeader, ReferenceImporter importer)
{
//Sample needed!
if (ehHeader is {Length: > 4})
if (ehHeader is { Length: > 4 })
throw new NotImplementedException("Exception handlers from ehHeader not supported yet.");

if (ehInfos is {Count: > 0})
if (ehInfos is { Count: > 0 })
{
foreach (var ehInfo in ehInfos)
InterpretEHInfo(methodBody, importer, ehInfo);
Expand All @@ -61,7 +61,7 @@ private static void InterpretEHInfo(CilMethodBody methodBody, ReferenceImporter
int handlerStart = FieldReader.ReadField<int[]>(ehInfo, "m_catchAddr")![i];
int handlerEnd = FieldReader.ReadField<int[]>(ehInfo, "m_catchEndAddr")![i];
var exceptionType = FieldReader.ReadField<Type?[]>(ehInfo, "m_catchClass")![i];
var handlerType = (CilExceptionHandlerType) FieldReader.ReadField<int[]>(ehInfo, "m_type")![i];
var handlerType = (CilExceptionHandlerType)FieldReader.ReadField<int[]>(ehInfo, "m_type")![i];

var endTryLabel = instructions.GetByOffset(tryEnd)?.CreateLabel() ?? new CilOffsetLabel(tryEnd);

Expand All @@ -81,7 +81,6 @@ private static void InterpretEHInfo(CilMethodBody methodBody, ReferenceImporter
}
}

[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Calls GetTypes")]
public static object ResolveDynamicResolver(object dynamicMethodObj)
{
//Convert dynamicMethodObj to DynamicResolver
Expand Down Expand Up @@ -111,7 +110,7 @@ public static object ResolveDynamicResolver(object dynamicMethodObj)
.Invoke(dynamicMethodObj, null);

//Create instance of dynamicResolver
dynamicMethodObj = Activator.CreateInstance(dynamicResolver, (BindingFlags) (-1), null, new[]
dynamicMethodObj = Activator.CreateInstance(dynamicResolver, (BindingFlags)(-1), null, new[]
{
ilGenerator
}, null)!;
Expand Down
1 change: 1 addition & 0 deletions src/AsmResolver.DotNet/AsmResolver.DotNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<NoWarn>1701;1702;NU5105</NoWarn>
<Nullable>enable</Nullable>
<TargetFrameworks>net6.0;netcoreapp3.1;netstandard2.0</TargetFrameworks>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
Expand Down
37 changes: 0 additions & 37 deletions src/AsmResolver.DotNet/Code/Cil/CilMethodBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,43 +130,6 @@ public bool VerifyLabelsOnBuild
| (value ? CilMethodBodyBuildFlags.VerifyLabels : 0);
}

/// <summary>
/// Creates a CIL method body from a dynamic method.
/// </summary>
/// <param name="method">The method that owns the method body.</param>
/// <param name="dynamicMethodObj">The Dynamic Method/Delegate/DynamicResolver.</param>
/// <returns>The method body.</returns>
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Calls ResolveDynamicResolver")]
public static CilMethodBody FromDynamicMethod(MethodDefinition method, object dynamicMethodObj)
{
if (!(method.Module is SerializedModuleDefinition module))
throw new ArgumentException("Method body should reference a serialized module.");

var result = new CilMethodBody(method);
dynamicMethodObj = DynamicMethodHelper.ResolveDynamicResolver(dynamicMethodObj);

//Get Runtime Fields
byte[] code = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_code")!;
object scope = FieldReader.ReadField<object>(dynamicMethodObj, "m_scope")!;
var tokenList = FieldReader.ReadField<List<object?>>(scope, "m_tokens")!;
byte[] localSig = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_localSignature")!;
byte[] ehHeader = FieldReader.ReadField<byte[]>(dynamicMethodObj, "m_exceptionHeader")!;
var ehInfos = FieldReader.ReadField<IList<object>>(dynamicMethodObj, "m_exceptions")!;

//Local Variables
DynamicMethodHelper.ReadLocalVariables(result, method, localSig);

// Read raw instructions.
var reader = ByteArrayDataSource.CreateReader(code);
var disassembler = new CilDisassembler(reader, new DynamicCilOperandResolver(module, result, tokenList));
result.Instructions.AddRange(disassembler.ReadInstructions());

//Exception Handlers
DynamicMethodHelper.ReadReflectionExceptionHandlers(result, ehInfos, ehHeader, new ReferenceImporter(module));

return result;
}

/// <summary>
/// Creates a CIL method body from a raw CIL method body.
/// </summary>
Expand Down
Loading