Skip to content
ptklattPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Glean

Glean is a usability layer over System.Reflection.Metadata that keeps traversal costs explicit.

The goal is not to hide System.Reflection.Metadata. The goal is to remove the repetitive parts that most users end up writing anyway while keeping the raw reader, handles, and metadata structs available whenever you want them.

Build and Package

Glean ships .NET 8 and .NET 10 package assets and references System.Reflection.Metadata 10.0.5. .NET 9 applications use the .NET 8 Glean asset. Tests and package consumers cover .NET 8, .NET 9 and .NET 10. Install the SDK pinned in global.json, plus .NET 8 and .NET 9 runtimes to run all test targets.

dotnet build Glean.slnx -c Release
dotnet test test/Glean.Tests/Glean.Tests.csproj -c Release --no-build
dotnet pack src/Glean/Glean.csproj -c Release -o artifacts/packages

Local packages default to 1.0.0-rc.1. The package includes XML documentation, the MIT license and this README; the symbol package includes portable PDBs with SourceLink and embedded library sources. To inspect the packages and compile fresh package consumers on all three runtimes, run from the repository root:

dotnet run --project eng/VerifyPackage -c Release -- artifacts/packages 1.0.0-rc.1 <git-revision>

Use the full commit hash from git rev-parse HEAD for <git-revision>. CI runs the same checks on Ubuntu and Windows. Tag builds upload package artifacts; publishing requires a manual run of ci on a v* tag with publish selected. After both platforms pass, the publish job uses that run's Linux packages without rebuilding.

Before publishing, configure the GitHub nuget environment with required reviewers, deployment access restricted to v* tags, and a NUGET_API_KEY secret scoped to Glean. Approve the publish job only for the intended version.

Choose a Lane

Glean is easiest to use if you pick the lane that matches the cost model you want:

  • Fast traversal: AssemblyScope, AssemblyContext, TypeContext, ModuleContext, MethodContext, MetadataTraversal, struct enumerators, and identity helpers like NameIs, NamespaceIs, and TryFind*.
  • Rich decoding: Decode* helpers, TypeSignature, ITypeSignatureVisitor<TState>, CustomAttributeDecoder, and formatting helpers that materialize richer object graphs.
  • Cross assembly resolution: AssemblyClosure and AssemblySet for resolving type and member references across a dependency closure.

Raw System.Reflection.Metadata is always still here:

  • AssemblyScope.Reader
  • AssemblyClosure.EntryReader
  • AssemblyContext.Reader
  • TypeContext.Reader
  • MethodContext.Reader

Primary Entry Points

The examples run in a console project that references Glean. Pass an assembly path as the first argument, followed by any dependency directories needed for closure loading.

Use AssemblyScope when you only need one assembly:

using Glean;

using var scope = AssemblyScope.Open(args[0]);
var assembly = scope.Context;

foreach (var type in assembly.EnumerateTypes())
{
    if (type.IsNested || !type.IsPublic)
    {
        continue;
    }

    Console.WriteLine(type.FullName);
}

Use AssemblyClosure when you need transitive dependencies and explicit resolution:

using Glean;
using Glean.Extensions;

using var closure = AssemblyClosure.Load(args[0], args.Skip(1).ToArray());

foreach (var typeReference in closure.EntryReader.EnumerateTypeReferences())
{
    if (!closure.Set.TryResolveType(
        closure.EntryReader,
        typeReference.Handle,
        out var targetReader,
        out var targetHandle))
    {
        continue;
    }

    var targetType = targetReader.GetTypeDefinition(targetHandle);
    Console.WriteLine(targetType.ToFullNameString(targetReader));
}

Assembly binding requires an exact name, version, normalized culture, and public key token by default. To allow version substitutions, pass AssemblyLoadOptions with BindingPolicy = AssemblyBindingPolicy.ExactThenCompatible (both in Glean.Resolution). Exact candidates always take priority; fallback uses search path order and changes only the version. Inspect closure.BindingSubstitutions for the requested identity, resolved identity, and file path. See the binding recipe for an example.

On case-sensitive systems, assembly probing tries exact filenames first, then filename matches that differ only in case. Case variants preserve the probing directory and extension order; variants of each candidate filename use ordinal order. Assembly identity checks and filesystem path comparison still apply.

Cost Model

For IL bytes or CLI headers, reuse AssemblyScope.PeReader or AssemblyClosure.EntryPeReader. A closure, loader or directory resolver can also return the borrowed PE reader for one of its metadata readers with TryGetPeReader(reader, out var peReader). Keep the owner alive and do not dispose borrowed readers.

AssemblyScope.TryGetManagedEntryPoint and AssemblyClosure.TryGetManagedEntryPoint return a method context for a managed entry point in the current image. They return false for native or external module entry points and absent or invalid method tokens. Use method.Definition.GetILSpan(peReader) for borrowed IL bytes, or DecodeILBytes for an allocated copy.

Use parameter.EnumerateConstraints() for constraint rows and their type handles or custom attributes. Enumeration does not decode signatures. Call constraint.DecodeType() for Glean's signature model, or pass your own provider and generic context to DecodeType(provider, context). The typeSpecHandle.DecodeTypeSpecification(reader, provider, context) overload also decodes directly into your model. Signature decoding may allocate.

module.EnumerateMethodSpecifications() exposes generic method instantiations. Each context provides its target method handle and signature blob; DecodeSignature() decodes the type arguments, leaving open parameters symbolic. Pass a provider and the referring type/method's generic context to decode into your own model with substitutions. This does not resolve the target method or decode its parameter and return types.

Context enumerators, identity checks such as NameIs and NamespaceIs, and MetadataTraversal use raw metadata without building signature graphs. Struct visitors implement every callback explicitly; unused callbacks can have empty bodies.

Decode* and formatting helpers materialize richer values and can allocate. TypeSignature.Accept(ref visitor, state) dispatches over an already decoded signature; passing a struct visitor by reference avoids boxing.

Overloads that take an AssemblySet perform explicit resolution and may populate caches. EnumerateAllInterfaces(assemblySet) also builds a queue and visited set.

If you are on a hot path, stay on contexts, enumerators, handles, and the raw reader. If you need a friendlier shape for signatures, attributes, or resolution, move up a tier only where it pays for itself.

See performance notes for allocation boundaries and the scope of the regression tests.

Reader Lifetime

Keep the owning AssemblyScope, AssemblyClosure, AssemblyLoader, or metadata factory scope alive while using its readers. Contexts, enumerators, metadata backed signatures and AssemblySet borrow those readers. Disposing an AssemblySet clears its state; it does not dispose the readers. A context's IsValid checks for a reader and, where applicable, a row handle. It does not validate metadata or check whether the owner has been disposed.

AssemblyLoader, AssemblySet and CustomAttributeTypeProvider hold mutable state and are not thread safe. Keep their use and disposal on one thread, or synchronize access externally. Resolution analyzes metadata; it does not reproduce runtime binding, redirects or AssemblyLoadContext behavior.

Samples

Runnable samples live under samples:

The first three are starter samples. InspectorSample is a larger demo tool that shows how the tiers mix in one flow. All of them are path driven and work against real assemblies rather than test fixtures.

Recipes

Usage recipes cover module metadata, visitors, portable PDBs, signature decoding, and cross assembly resolution.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages