Turbo
Turbo

Reputation: 2551

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:

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.

Upvotes: 9

Views: 2672

Answers (1)

Andrey Shchekin
Andrey Shchekin

Reputation: 21599

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.

Upvotes: 5

Related Questions