Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify a "reference assembly"?

A lot of .NET assemblies ship with a reference only version which is stripped of actual code, and only has the metadata.

For example, I can find System.Core.dll at several locations on my machine, two of which are:

  • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Core.dll Size: 276 KB
  • C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll Size: 1291 KB

The first one only has metadata, and loading it in default load context throws a BadImageFormat exception.

System.BadImageFormatException: Could not load file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context

Given the path to an assembly, is it possible to find out if it is a "reference assembly"?

I can check the path for keyword "Reference Assemblies", but that is hacky and won't work if the assembly is copied to a different location. I have the freedom to first load the assembly in reflection only context if that would help.

like image 712
Turbo Avatar asked Aug 05 '16 23:08

Turbo


1 Answers

I found this code dotnet/coreclr/.../pefile.inl in CoreCLR, which identifies a reference assembly by what I think is System.Runtime.CompilerServices.ReferenceAssemblyAttribute:

if (mdImport->GetCustomAttributeByName(TokenFromRid(1, mdtAssembly),
                                       g_ReferenceAssemblyAttribute,
                                       NULL,
                                       NULL) == S_OK) {
    ThrowHR(COR_E_LOADING_REFERENCE_ASSEMBLY, BFA_REFERENCE_ASSEMBLY);
}

I would assume full CLR does the same.

I haven't tried it yet, but you could probably load your assembly into Reflection-only context, and then checked whether it has a ReferenceAssemblyAttribute.

like image 78
Andrey Shchekin Avatar answered Oct 04 '22 03:10

Andrey Shchekin