Giter Site home page Giter Site logo

washi1337 / asmresolver Goto Github PK

View Code? Open in Web Editor NEW
793.0 36.0 124.0 8.57 MB

A library for creating, reading and editing PE files and .NET modules.

Home Page: https://docs.washi.dev/asmresolver/

License: MIT License

C# 99.91% C++ 0.06% C 0.02% Batchfile 0.01% Shell 0.01% Visual Basic .NET 0.01%
pe-analyzer disassembler native dotnet metadata-editor reader writer cil il msil

asmresolver's People

Contributors

766f6964 avatar anonym0ose avatar charterino avatar cursedland avatar dazombiekiller avatar dependabot[bot] avatar dr4k0nia avatar ds5678 avatar elektrokill avatar holly-hacker avatar jerres avatar jpaja avatar liiir1985 avatar maxxor avatar n78750469 avatar osumatrix avatar rstarkov avatar sunnamed434 avatar svenskithesource avatar theproxyre avatar tobitofatitore avatar washi1337 avatar windows10ce avatar zsr2531 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

asmresolver's Issues

Rebuilding Assembly

Hi there

I tried out AsmResolver and I am really impressed, good stuff. I just have one question though. Did you have any code implemented for the rebuilding as managed feature? I see you set it to throw the not implemented error for now.

Also I seen some screenshots of the lite code editor on your blog, I am wondering if you are going to make that available. I need a designer for a redevelopment of an application I have. I am using FCTB as well. Don't worry though it isn't a ide/code editor, it is for game scripting.

GetOrCreateStaticConstructor() fails if no global module type is present

System:
System: Tested on Arch Linux x64
Kernel: 5.5.11-arch1-1
DotNet Version: 3.1.103
AsmResolver Branch: v4

Summary
The ModuleDefinition class already provides functionality to automatically create a global static constructor with the method GetOrCreateStaticConstructor() .
However, this only works, if the type is already present, otherwise GetModuleType() returns null.

Steps to reproduce:

  1. Create a project with the following code
static void Main(string[] args)
{
    var assembly = new AssemblyDefinition("Test", new Version(1, 0, 0, 0));
    var moduleDefinition = new ModuleDefinition("TestModule", KnownCorLibs.NetStandard_v2_1_0_0);
    
    assembly.Modules.Add(moduleDefinition);
    assembly.ManifestModule.GetOrCreateModuleConstructor();

    Console.WriteLine("ok");
}
  1. Run the code, and observe that AsmResolver throws a NullReferenceException exception, because GetModuleType() just returns null, if the type is not present:
public TypeDefinition GetModuleType() => TopLevelTypes.Count > 0 ? TopLevelTypes[0] : null;

See: ModuleDefinition.cs (L.596)

Suggestion:
Either modify GetModuleType() to GetOrCreateModuleType(), or add a second method with that functionality.
If there is already a shortcut to create a static module type constructor, there should also be a shortcut to create the global module type itself, if not present.

Wrong disasm

Somthing wrong with:
0F 86 55 00 00 00

Must be
CODE:00401051 jbe loc_4010AC

Not

db 0F
xchng dword ptr[ch], edx
add dword ptr[al], eax

GetLocalVariable() fails to process instructions with byte operands

System:
System: Tested on Arch Linux x64
Kernel: 5.6.2-arch1-2
DotNet Version: 3.1.103
AsmResolver Branch: v4

Summary:
Instructions such as Ldloc, Ldloc_S, Stloc and Stloc_S are processed incorrectly when the instruction operand is of type System.Byte.
Casting the operand triggers an InvalidCastException:

System.InvalidCastException: Unable to cast object of type 'System.Byte' to type 'AsmResolver.DotNet.Code.Cil.CilLocalVariable'.

The same problem probably also applies when the operand is of type System.SByte.

Steps to reproduce:
Call GetLocalVariable on an instruction with the following form:

2020-04-09-171242_406x124_scrot

Add member cloning functionality?

One feature that AsmResolver is still missing, but could be really useful is a member cloner.
Let me demonstrate a scenario where a member cloner would be very beneficial:

Suppose you develop an application that processes/analyzes assemblies, such as a deobfuscator.
You'd like to write unit tests for this application, but you notice there could be a lot (maybe hundreds) of very specific cases that you should cover.
In other words, you need to generate hundreds of very specific dummy assemblies to test against.
Currently, you only have two ways of achieving this:

Option 1:
To craft these tests you build a new assembly from scratch in every test case.
You create new TypeDefinitions, MethodDefinitions, FieldDefinitions with the properties you want to test against, and add them to your assembly.
While this approach allows you to generate isolated test assemblies for the specific cases you'd like to cover, it also comes with some downsides:
Test cases become really long and unreadable, and also you (most likely) will end up with a lot of duplicate code across your test cases.

Option 2:
You add 100 new projects to your project solution to account for your 100 test scenarios. While this still ensures isolation between tests, it is just as bad as the first option.
You not only have to compile 100's of different projects, which takes a long time, but again, you generate a lot of duplicate code.

So, instead I propose a different approach, that ensures concise, easily readable test cases, while still ensuring isolation and decent compile times: Dynamically generating test assemblies with a member cloner.

You'd have only one additional project in your solution which contains all the scenarios you'd like to test as classes.
In the tests, you'd generate an empty dummy assembly, and use a member cloner to clone the test classes from the test project and add them to your generated assembly.
This would keep the tests concise, readable and still ensures isolation.
The creation of a specific assembly in a unit test could then look like this:

var tempAssembly = new TempAssemblyBuilder(templateAssembly)
.IncludeType(nameof(Class1))
.ExcludeMethod(nameof(Class1.Method1))
.IncludeType(nameof(Class2))
.Build()

Some FieldDefinitiondoes Fullname

Hi, I recently used your library (AsmResolver) to resolve some of class member,but I dont know why for some of Field Definition I get Invalid Operation exception,it says it should be in readonly mode
while for others not, where i can change readonly property to true,because its getter is public not setter, is there any guide, please?

PEImage layer needs more access to sections

Summary:
Right now the philosophy of IPEImage is to abstract away as many raw offsets and/or sizes present in the raw structures of the PE file format. This allows for an unifying API, allowing easy creation of new PEImages, while images that are read from the disk can lazily pull the data from an underlying PEFile, without burdening the user with calculating raw offsets and or sizes of sections and/or data directories.

For this reason, there is no PEFile instance exposed either in IPEImage, and thus there is no way to access sections and their headers. This might be a problem for users that do in fact need this information (e.g. for writing obfuscators and/or packers).

The potentially most important things that are missing right now is access to:

  • Section flags
  • Section physical and/or virtual size
  • Read-only access of section data

It is also not psosible to add new sections yet in the IPEImage layer.

There is potentially a need for an abstraction of raw sections to make it easier than maintaining the separate instance of a PEFile the image was based on. The design, however, has to be considered very carefully without breaking the philosophy of IPEImage.

Additional info:
Some of the other PEFile fields are in fact present:

  • Machine type
  • File characteristics
  • Time date stamp
  • Optional header kind
  • Dll characteristics
  • Image base (Although this value could be ignored depending on the IPEFileBuilder)

In a similar fashion we might be able to introduce sections here as well.

Case sensitive file name

Hi and many thanks for this project,
I have built AsmResolver on Windows without any problem, but on Linux (with Mono), there are two minor errors concerning the file naming difference between Linux (case sensitive) and Windows (case insensitive). They come from two files: MetaDataToken.cs and MetaDataStreamHeader.cs which should be renamed to MetadataToken.cs and MetadataStreamHeader.cs.

CallSite

what is equivalent of Callsite (Mono Cecil) in AsmResolver?

Adding custom PE Sections

Hello,

Currently there seems to be no way to add a custom PE section to the loaded assembly.
It would be nice to see this getting implemented in future updates of AsmResolver.

Regards,

Resources Duplicated

I have an assembly with two Resources files embedded, and after processing the assembly with AsmResolver, it ends up copying the contents of the first resources file instead of using the contents of the second resources file. The emitted assembly still shows the two resources files, and they have the correct names, the contents are just wrong.

All I'm using AsmResolver to do is change the assembly version and the version of certain referenced assemblies. Not touching the Resources section at all.

Feature: Get implied structure layout statically

Summary:
Some assembly processors/obfuscators like to inject sizeof instructions to hide the value of a constant, or make use of raw pointers referencing fields inside a structure. To reverse this, it would be nice to have a way to statically compute the size of the referenced type definition, as well as the implied offsets of any field defined in the type.

Suggested syntax:
Introduce a TypeMemoryLayout class, that stores both the total size of the type (Size), as well as the offsets of each field in the type (GetFieldOffset(FieldDefinition)).

TypeDefinition type = ...
TypeMemoryLayout layout = type.GetImpliedMemoryLayout(is32bit: true);

Console.WriteLine("Total type size: {0}", layout.Size);
foreach (var field in type.Fields)
   Console.WriteLine("Field {0} starts at offset {1}", field.Name, layout.GetFieldOffset(field));

Requirements:

  • For primitive corlib types, return the primitive size.
  • For other value types, compute size by looking at:
    • The sizes of each field (this might need a recursive call).
    • The field offsets.
    • The class layout of the struct.
      • If class size != 0, return this size, but only if this size is bigger than the inferred type size based on the fields.
      • If the class layout = null or class layout packingsize = 0, assume packing size of 4 or 8 depending on provided bitness.
  • For reference types, return the size of a pointer based on the provided bitness of the program.

Complications:
Structs can contain fields with generic types. Instantiations of those will need #53

Adding functionality to obtain inherited types

Currently, there doesn't seem to be a quick way to obtain all types, that one type inherits from.
Similar libraries to AsmResolver, such as dnlib provide such functionality.
An example is shown below:

type.InheritsFrom("System.Configuration.SettingsBase"){
    Console.WriteLine("Inherits!");
}

Is it possible to add such functionality to AsmResolver?

VariableDefinition

why there is no VariableDefinition like ParameterDefinition,MethodDefinition,..?

Add visitor pattern for TypeSignature

Summary:
Currently, when traversing type signatures and their decorators, it is often required to pattern match either on TypeSignature itself, or using TypeSignature.ElementType. This results in lots of repeated code for figuring out what kind of type signature we're dealing with, only to dispatch it to a piece of code that knows how to process the more specific type signature.

Since the set of possible type signatures is well-defined, we could leverage the powers of object orientation, and implement a visitor or listener pattern for TypeSignature. This could be in particular useful for the reference importer (or signature cloning in general).

Suggested syntax:

Define an interface ITypeSignatureVisitor:

public interface ITypeSignatureVisitor<TState, TResult>
{
   TResult VisitCorLibType(CorLibTypeSignature signature, TState state);
   TResult VisitTypeDefOrRef(TypeDefOrRefSignature signature, TState state);
   TResult VisitSzArrayType(SzArrayTypeSignature signature, TState state);
   // ...
}

Add method AcceptVisitor to TypeSignature:

public abstract class TypeSignature
{
   // ...
   public abstract TResult AcceptVisitor<TState, TResult>(ITypeSignatureVisitor<TState, TResult> visitor);
}

Each type signature then implements it in the following way:

public class CorLibTypeSignature : TypeSignature
{
   // ...
   public override  TResult AcceptVisitor<TState, TResult>(ITypeSignatureVisitor<TState, TResult> visitor)
   {
      return visitor.VisitCorLibType(this, state);
   }
}

Default corlib definitions

Summary:
Creating a new module definition in memory automatically defaults to referencing mscorlib 4.0.0.0 from the .NET Framework (or Mono). There is an overload for this constructor to accept other corlib implementations (like netstandard.dll, System.Private.CorLib, etc.).

var module1 = new ModuleDefinition("name"); // Defaults to mscorlib 4.0.0.0
var module2 = new ModuleDefinition("name", new AssemblyReference("netstandard.dll", ...); // Use netstandard instead.

Rather than redefining these implementations over and over again as a user (and risking the fact that people might misspell the name or public key token), it would be nice to have a few default instances of AssemblyReference stored somewhere that they can use instead.

Maybe something like the following:

var module = new ModuleDefinition("name", KnownCorLibs.NetStandard20);

System.InvalidOperationException on 64bit assembly

I was testing OldRod on some dummies and found out that it cannot reassemble 64bit net files.

Here is log:

// ...
21:24:16.586 [Main]: Executing Clean up stage...
21:24:16.587 [Main]: Commiting changes to metadata streams...
21:24:16.790 [Main]: Not removing koi stream as some exports were ignored.
21:24:16.791 [Main]: Reassembling file...
21:24:16.812 [TUI]: Something went wrong! Try the latest version or report a bug
 at the repository.
21:24:16.819 [TUI]: System.InvalidOperationException: Sequence contains no matching element
// ...

It seems that is related to the fact that AsmResolver cannot find and properly write import directory to assembly as there is none in 64bit file. I have attached the file that I am working with.
WindowsFormsApplication4.zip

Wrong disasm

83 3D D4 F6 02 10 00
must be:
cmp dword_1002F6D4, 0

not
CMP DWORD[EBP], D4
DB F6
ADD EDX, DWORD[EAX]

Preservation of metadata tokens upon writing .NET assemblies in high-level mode

Summary:
Currently the managed PE image builder constructs the metadata tables by adding rows to the tables in the order "as they come in", that is, in the traversal order of the member tree. This is very likely to completely reorder tables if the .NET module was read from e.g. a file. This might not be desirable for input binaries that rely on this (e.g. obfuscated binaries)

Suggested Features

Preservation of order of all unsorted and redirectable tables

  • Module definitions Is already preserved by default
  • Type references
  • Type definitions
  • Field definitions
  • Method definitions
  • Parameter definitions
  • Member references
  • Stand-alone signatures
  • Event definitions
  • Property definitions
  • Module references
  • Type specifications
  • Assembly references
  • File references Is already preserved by default
  • Exported types Is already preserved by default
  • Manifest resources Is already preserved by default
  • Method specifications

Preservation of heap indices

  • Blob
  • GUID
  • Strings
  • User strings

ThisParameter

How to find out if ThisParameter is In (Ref read only) parameter from Method Definition?

Exception is thrown at beginning of disassembling

Exception thrown:
System.NotSupportedException: 'Unrecognized or unsupported addressing method.' at line while ((inst = disassembler.ReadNextInstruction()) != null)

Program.cs:

    static void Main(string[] args)
    {
        var winAsm = WindowsAssembly.FromFile("testpe2.exe");
        var reader = winAsm.ReadingContext
                           .Reader
                           .CreateSubReader(winAsm.NtHeaders.OptionalHeader.BaseOfCode,
                                       (int)winAsm.NtHeaders.OptionalHeader.SizeOfCode);

        var disassembler = new X86Disassembler(reader);

        X86Instruction inst;
        while ((inst = disassembler.ReadNextInstruction()) != null)
        {
            Console.WriteLine(inst);
        }

        Console.ReadKey();
    }

What's wrong?

How to use MsilAssembler an MsilDisassembler in the new version?

Hi @jerres,

Been using v1 for long time and things were quite good. However one day when I upgraded my PC to windows 10, v1 was no longer working. Some stackoverflow error happened in ntdll.dll. Then I updated to v2 and got drowned in the changes. Can you show me how to use MsilAssembler and MsilDisassembler? Let's say I want to get the instructions list of a method from offset A too offset B, then replace some instructions. What I did in v1 was:

var assembler = new MSILAssembler(method.Body);
var disassembler = new MSILDisassembler(method.Body);
var instructions = disassembler.Disassemble(0, (int)method.Body.CodeSize);
foreach (var ins in instructions)
    assembler.Replace(ins, MSILInstruction.Create(MSILOpCodes.Nop, null), true);
assembler.Replace(instructions[0], MSILInstruction.Create(MSILOpCodes.Ret, null), true);
method.ApplyChanges();

What should I do to achieve the same in v2?

Thanks,
Alex

Method Overrides

Hi there, I have two questions,:

  1. if I have a MethodDefinition that has overrides, how to get overrides from method definition?
  2. how to check if a method return type has FieldMarshal?, this might be strange , but I saw some codes from Mono Cecil the checking FieldMarshal availability with methodReturnType!.
    sample Code would be very helpful.

Thanks

Instruction cloning fails when casting SerializedMethodSpecifications to IMethodDefOrRef

System:
System: Tested on Arch Linux x64
Kernel: 5.5.8-arch1-1
DotNet Version: 3.1.102
AsmResolver Branch: v4

Summary:
Cloning process fails on virtual overridden events, by failing to cast a call instruction operand.

Steps to reproduce:

  1. Create a new assembly with the following classes:
public class BaseClass
{
    public virtual event EventHandler VirtualEvent;
}

public class DerivedClass : BaseClass
{
    public override event EventHandler VirtualEvent
    {
        add => base.VirtualEvent += value;
        remove => base.VirtualEvent -= value;
    }
}
  1. From a different assembly, try to clone these classes non-recursivly:
var cloner = new MemberCloner(assembly.ManifestModule);
var sourceModule = ModuleDefinition.FromFile(typeof(BaseClass).Assembly.Location);
cloner.Include(sourceModule.TopLevelTypes.First(t => t.Name == nameof(BaseClass)), false);
cloner.Include(sourceModule.TopLevelTypes.First(t => t.Name == nameof(DerivedClass)), false);
var result = cloner.Clone();
  1. Observe the cloning process fail on the call instruction IL_001E: call !!0 System.Threading.Interlocked::CompareExchange<System.EventHandler>(!!0&, !!0, !!0) in MemberCloner.Methods.cs L.160:
System.InvalidCastException : Unable to cast object of type 'AsmResolver.DotNet.Serialized.SerializedMethodSpecification' to type 'AsmResolver.DotNet.IMethodDefOrRef'.

Enhancement: Add a Location property to Assembly- and/or ModuleDefintion

Summary:
It would be useful to know the full path of an Assembly/Module Definition

Suggested Syntax:

AssemblyDefintion asm = ...
ModuleDefinition mod = ...

string asmPath = asm.Location;
string modPath = mod.Location;

Requirements:

  • Add a Location property to Assembly/Module Definition

MemberCloner fails to clone interfaces due to BaseType being null

System:
System: Tested on Arch Linux x64
Kernel: 5.5.11-arch1-1
DotNet Version: 3.1.103
AsmResolver Branch: v4

Summary:
The MemberCloner fails to process interfaces correctly. Resolving their BaseType yields null, causing the ReferenceImporter to throw an ArgumentOutOfRangeException:

System.ArgumentOutOfRangeException : Specified argument was out of the range of valid values. (Parameter 'type')

Steps to reproduce:

  1. Call the MemberCloner on a structure with the following form:
public interface IInterfaceSimpleInheritance
{
    void InterfaceMethod();
}

public class SimpleInterfaceImplementingClass : IInterfaceSimpleInheritance
{
    public void InterfaceMethod()
    {
    }
}
  1. Observe the MemberCloner throwing an ArgumentOutOfRangeException.

Feature: Obtain all imported typereferences and/or member references of a module

Summary:
Currently, ModuleDefinition only exposes top-level type definitions, and assembly and module references, but there is no way to directly obtain all imported type and/or member references, other than directly trying to resolve metadata tokens to these type and/or member references.

This could especially be useful when we try to update a name of a member definition in a dependency .NET module. Such a modification would require the dependent module to update its member reference of it to remain working. These references that need to be synchronized can then be easily found without having to traverse the entire module's contents.

Suggested syntax:

ModuleDefinition module = ...;
IEnumerable<TypeReference> typeRefs = module.GetTypeReferences();
IEnumerable<MemberReference> memberRefs = module.GetMemberReferences();

Complications:

  • These lists can only be used as a snapshot of the type and member references as they were stored on the disk.
  • What should the ReferenceImporter do when importing type references?
    • Q: Should it add newly imported type or member references to the respective lists?
      A: No, it should only reflect what was serialized.
    • Q: Should it try to reuse TypeReferences and MemberReferences when possible?
      A: No, this is a breaking change. Callees of ReferenceImporter should be responsible for caching.

CallSite

what is equivalent of Callsite (Mono Cecil) in AsmResolver?

File Path

how to get back file path from loaded Assembly AssemblyDefinition?

How to create an instruction with TypeReference or FieldReference?

Hello, World!

Am trying to replace an instruction using MSILAssembler.Replace(). Let's assume that I want to return an empty Guid, how can I create an instruction which refers to System.Guid::Empty field? I tried using MSILInstruction.Create(MSILOpCodes.Ldsfld, 0x0A00013C, assembly.NETHeader) (0x0A00013C was the metadata token I found and the instruction seemed to be successfully created) however I got "System.Guid System.Guid::Empty does not match with the metadata member provided in the target assembly Parameter name: newInstruction".

Any help would be appreciated.

Assembly file type

How to find out where an assembly is Windows (exe), Console(exe), or Library (.dll)?

Feature: Generic Context for types

Summary:
Generic types and methods use instances of the GenericParameterSignature to reference type parameters. When instantiated, these signatures are at runtime replaced with the type arguments of the type or method instantiation. Therefore, for better analysis of the .NET metadata, it can is useful to obtain the type argument as was provided in the instantiation context.

Suggested syntax:

var context = new GenericContext(genericTypeInstance, genericMethodInstance);
GenericParameterSignature parameter = ...;
TypeSignature typeArgument = context.GetTypeArgument(parameter);

Troubles with filling IList<ImageSymbolExport> Exports in ImageExportDirectory.cs

Troubles arise while working with dll having ordinals exports and mixed ordinals and named.

  1. If only ordinals in dll then AddressOfNameOrdinals and AddressOfNames both are equal to 0 and code below gives exceptions (ArgumentOutOfRangeException("rva") leaving Exports property empty.

application.RvaToFileOffset(AddressOfNameOrdinals);
application.RvaToFileOffset(AddressOfNames);

  1. If mixed "ordinals and named export functions" the
    for (int i = 0; i < NumberOfFunctions; i++) {} cycle
    gives wrong results. The first ordinal gets name of first named function and then exception after (NumberOfNames)-times.
    We must skip reading nameReader.ReadAsciiString() (NumberOfFunctions-NumberOfNames)-times.
    AFAIK, NumberOfFunctions - is a total number of exported functions, including NumberOfNames.
    I didn't look at standard but as it's in mfcm90.dll named functions go after ordinals.

  2. Examples of such dlls are mfc90.dll and mfcm90.dll

Signature Comparer gets stuck in infinite loop when comparing PropertySignatures

System:
System: Tested on Arch Linux x64
Kernel: 5.5.11-arch1-1
DotNet Version: 3.1.103
AsmResolver Branch: v4

Summary:
Comparing two PropertyDefinition signatures results the following method to get stuck in an infinite loop:

public bool Equals(CallingConventionSignature x, CallingConventionSignature y)
{
    if (ReferenceEquals(x, y))
        return true;
    if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
        return false;

    return x switch
    {
        LocalVariablesSignature localVarSig => Equals(localVarSig, y as LocalVariablesSignature),
        FieldSignature fieldSig => Equals(fieldSig, y as FieldSignature),
        MethodSignature methodSig => Equals(methodSig, y as MethodSignature),
        PropertySignature propertySig => Equals(propertySig, y as PropertySignature),
        _ => false
    };
}

The PropertySigantures that are being compared have the following characteristics:
image

Adding multiple members to a TypeDefinition with AddRange()

Currently, adding members like EventDefinitons, FieldDefinitions and MethodDefinitions to a TypeDefiniton is done with the Add() method.

However, sometimes it is required to add multiple members at once.
Right now, the only solution is to write a loop that iterates over all members in a given collection and performs the Add() operation on each one.

For convenience, I propose adding a AddRange(IEnumerable<T>) method.
That way adding many members at once does not require the user to write a loop every time.

Rebuilding an AssemblyDefinition results in CorLib reference being null

System:
System: Tested on Arch Linux x64
Kernel: 5.5.8-arch1-1
DotNet Version: 3.1.102
AsmResolver Branch: v4

Summary:
When creating a new AssemblyDefinition and rebuilding it in memory, the reading process of the AssemblyDefinition fails, because the corLib parameter in the CreateAssemblyResolver method in the ModuleDefinition class is null.

Steps to reproduce:

  1. Create a new AssemblyDefinition from scratch:
var assembly = new AssemblyDefinition("Test", new Version(1, 0, 0, 0));
var module = new ModuleDefinition("TestModule");
assembly.Modules.Add(module);
  1. Rebuild the AssemblyDefinition:
public AssemblyDefinition Rebuild(AssemblyDefinition assemblyDefinition)
{
    using var stream = new MemoryStream();
    assemblyDefinition.ManifestModule.Write(stream);
    return AssemblyDefinition.FromReader(new ByteArrayReader(stream.ToArray()));
}
  1. Observe AsmResolver crash when reading the rebuilt AssemblyDefinition from the stream.

Possible cause:
Somehow, it seems that AssemblyReferences are not processed/loaded correctly when reading an AssemblyDefinition. (See: FindMostRecentCorLib() in SerializedModuleDefinition.cs)

Change license to LGPL instead of GPL

When using this library I might not want to make my code that uses it open source. Please consider using LGPL. This way changes to your library will be sent back to you, but people are not forced to make their tools open source as well.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.