dotnet / dotnet/runtime

MetadataLoadContext: Load assemblies from metadata stream

Open
#122,864 3 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-System.Reflection
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

MetadataLoadContext's assembly loading APIs currently require full PE images. In some scenarios, the full PE image is unavailable. For example, the ICorDebug API only provides easy access only to the metadata stream of loaded modules.

The majority of MetadataLoadContext functionality can be implemented using only the metadata stream. In these scenarios, it would be useful to have a way to load assemblies by providing only the metadata stream.

### API Proposal

```csharp
namespace System.Reflection;

public partial class MetadataLoadContext
{
public Assembly LoadFromMetadataReader(System.Reflection.Metadata.MetadataReader metadataReader);
}
```

Much like the existing `LoadFromStream` API, this method transfers ownership of the MetadataReader to the MetadataLoadContext. The caller must not dispose the MetadataReader while the MetadataLoadContext is in use.

The following APIs would be non-functional in assemblies loaded via this method and would throw NotSupportedException. These APIs require data not stored in the metadata stream (e.g., IL code):

- Module.GetPEKind
- Assembly.EntryPoint
- MethodBase.GetMethodBody

### API Usage

```csharp
IMetaDataTables2 tables = ...;
Marshal.ThrowExceptionForHR(tables.GetMetaDataStorage(out byte* pointer, out uint length));
var reader = new MetadataReader(pointer, checked((int)length));

var assembly = metadataLoadContext.LoadFromMetadataReader(reader);
```

### Alternative Designs

Overloads accepting a pointer, byte array, and/or stream directly could be added instead. This would allow the MetadataReader object to be fully encapsulated within the MetadataLoadContext. However, this complicates the API design for a small reduction in risk.

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.