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

GetOrCreateStaticConstructor() fails if no global module type is present #46

Closed
766F6964 opened this issue Mar 26, 2020 · 0 comments
Closed
Labels

Comments

@766F6964
Copy link
Contributor

766F6964 commented Mar 26, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants