From 4368f1d945a1e4a0139596bc0138557e53f8da95 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 23 Oct 2026 11:09:19 -0700 Subject: [PATCH 1/3] Validate managed ilasm method entry points Reject repeated entry-point directives and instance entry points with source diagnostics. Preserve the first valid PE/PDB entry point in error-tolerant output and cover rejection and recovery cases. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/tools/ilasm/README.md | 9 ++ .../Actions/GrammarActions.Instructions.cs | 27 +++- src/tools/ilasm/src/ILAssembler/Diagnostic.cs | 4 + src/tools/ilasm/src/ILAssembler/gen/CIL.g4 | 2 +- .../ilasm/src/ILAssembler/gen/CILParser.cs | 5 +- .../tests/ILAssembler.Tests/MethodTests.cs | 146 ++++++++++++++++++ 6 files changed, 187 insertions(+), 6 deletions(-) diff --git a/src/tools/ilasm/README.md b/src/tools/ilasm/README.md index 203eaecda412cf..7000395ff317c7 100644 --- a/src/tools/ilasm/README.md +++ b/src/tools/ilasm/README.md @@ -20,6 +20,15 @@ If you modify any `.g4` grammar files (rare), you must regenerate the parser and This will update the generated files before building the main project. +## Entry-point validation + +Only one method may declare `.entrypoint`, and that method must be static. +A repeated directive (including a second directive in the same method) or an +instance entry point is an assembly error reported at the directive. +With `-ERROR`, the image is emitted: the first valid entry point is retained, +and an instance method is not selected. Compiler callers still receive the +diagnostics; the command line suppresses them in error-tolerant mode. + --- For more details, see the main repository README or contact the maintainers. diff --git a/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs b/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs index 590f42bb435fd0..819eb8ea41491c 100644 --- a/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs +++ b/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; @@ -252,12 +253,32 @@ internal void SetMaxStack(IToken valueToken) } } - internal void SetEntryPoint() + internal void SetEntryPoint(IToken directiveToken) { - if (_currentMethod is not null) + if (_currentMethod is null) { - _entityRegistry.EntryPoint = _currentMethod.Definition; + return; + } + + if (_entityRegistry.EntryPoint is not null) + { + ReportError( + DiagnosticIds.DuplicateEntryPoint, + DiagnosticMessageTemplates.DuplicateEntryPoint, + directiveToken); + return; } + + if (!_currentMethod.Definition.MethodAttributes.HasFlag(MethodAttributes.Static)) + { + ReportError( + DiagnosticIds.InstanceEntryPoint, + DiagnosticMessageTemplates.InstanceEntryPoint, + directiveToken); + return; + } + + _entityRegistry.EntryPoint = _currentMethod.Definition; } internal void SetZeroInit() diff --git a/src/tools/ilasm/src/ILAssembler/Diagnostic.cs b/src/tools/ilasm/src/ILAssembler/Diagnostic.cs index 02edf85f717deb..a80352be4645eb 100644 --- a/src/tools/ilasm/src/ILAssembler/Diagnostic.cs +++ b/src/tools/ilasm/src/ILAssembler/Diagnostic.cs @@ -79,6 +79,8 @@ public static class DiagnosticIds public const string LocalScopeWithoutInstructions = "ILA0058"; public const string LocalNameDeclaredTwiceInScope = "ILA0059"; public const string LocalSlotNamedTwiceInScope = "ILA0060"; + public const string DuplicateEntryPoint = "ILA0063"; + public const string InstanceEntryPoint = "ILA0064"; } internal static class DiagnosticMessageTemplates @@ -144,4 +146,6 @@ internal static class DiagnosticMessageTemplates public const string LocalScopeWithoutInstructions = "Local var '{0}' is declared in a scope that has no instructions; a PDB local scope must not be empty"; public const string LocalNameDeclaredTwiceInScope = "Local var '{0}' is already declared in this scope"; public const string LocalSlotNamedTwiceInScope = "Local var '{0}': slot {1} is already named '{2}' in this scope"; + public const string DuplicateEntryPoint = "Multiple entry points declared"; + public const string InstanceEntryPoint = "Entry point method must be static"; } diff --git a/src/tools/ilasm/src/ILAssembler/gen/CIL.g4 b/src/tools/ilasm/src/ILAssembler/gen/CIL.g4 index 15df9798442bdd..69b36ab3fe3a62 100644 --- a/src/tools/ilasm/src/ILAssembler/gen/CIL.g4 +++ b/src/tools/ilasm/src/ILAssembler/gen/CIL.g4 @@ -2038,7 +2038,7 @@ methodDecl: | EMITBYTE value = int32 {Actions.EmitByte($value.start);} | sehBlock | MAXSTACK value = int32 {Actions.SetMaxStack($value.start);} - | ENTRYPOINT {Actions.SetEntryPoint();} + | directive = ENTRYPOINT {Actions.SetEntryPoint($directive);} | ZEROINIT {Actions.SetZeroInit();} | labelDecl | scopeBlock diff --git a/src/tools/ilasm/src/ILAssembler/gen/CILParser.cs b/src/tools/ilasm/src/ILAssembler/gen/CILParser.cs index ff77224ac0efb3..d3c165c33fbb07 100644 --- a/src/tools/ilasm/src/ILAssembler/gen/CILParser.cs +++ b/src/tools/ilasm/src/ILAssembler/gen/CILParser.cs @@ -12850,6 +12850,7 @@ public MethodDeclsContext methodDecls() { public partial class MethodDeclContext : ParserRuleContext { public Int32Context value; + public IToken directive; public DataDeclContext declaration; public SecDeclContext security; public ExtSourceSpecContext source; @@ -12972,8 +12973,8 @@ public MethodDeclContext methodDecl() { EnterOuterAlt(_localctx, 5); { State = 2759; - Match(ENTRYPOINT); - Actions.SetEntryPoint(); + _localctx.directive = Match(ENTRYPOINT); + Actions.SetEntryPoint(_localctx.directive); } break; case ZEROINIT: diff --git a/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs b/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs index 7030bed8d31ba6..cbbaf4c5ffa665 100644 --- a/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs +++ b/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs @@ -471,6 +471,152 @@ .emitbyte 0x00 pe.GetSectionData(field.GetRelativeVirtualAddress()).GetContent().AsSpan(0, sizeof(int)))); } + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void Diagnostic_DuplicateEntryPoint(bool sameMethod, bool errorTolerant) + { + string source = $$""" + .assembly test { } + .class public Program + { + .method public static void Main() cil managed + { + .entrypoint + {{(sameMethod ? ".entrypoint" : string.Empty)}} + ret + } + .method public static void Other() cil managed + { + {{(sameMethod ? string.Empty : ".entrypoint")}} + ret + } + } + """; + + var (diagnostics, result) = DocumentCompilerTestHelpers.CompileWithDiagnostics( + source, new Options { ErrorTolerant = errorTolerant, Debug = true }); + Diagnostic error = Assert.Single(diagnostics); + Assert.Equal(DiagnosticIds.DuplicateEntryPoint, error.Id); + Assert.Equal(DiagnosticSeverity.Error, error.Severity); + Assert.Equal("Multiple entry points declared", error.Message); + Assert.Equal("test.il", error.Location.Source.Path); + Assert.Equal(new SourceSpan(source.LastIndexOf(".entrypoint", StringComparison.Ordinal), ".entrypoint".Length), error.Location.Span); + if (errorTolerant) + { + Assert.NotNull(result); + using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); + MetadataReader reader = pe.GetMetadataReader(); + MethodDefinitionHandle mainHandle = reader.MethodDefinitions + .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Main"); + Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); + Assert.Equal(mainHandle, pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint); + } + else + { + Assert.Null(result); + } + } + + [Theory] + [InlineData("", false)] + [InlineData("", true)] + [InlineData("instance", false)] + [InlineData("instance", true)] + public void Diagnostic_InstanceEntryPoint(string callingConvention, bool errorTolerant) + { + string source = $$""" + .assembly test { } + .class public Program + { + .method public {{callingConvention}} void Main() cil managed + { + .entrypoint + ret + } + } + """; + + var (diagnostics, result) = DocumentCompilerTestHelpers.CompileWithDiagnostics( + source, new Options { ErrorTolerant = errorTolerant, Debug = true }); + Diagnostic error = Assert.Single(diagnostics); + Assert.Equal(DiagnosticIds.InstanceEntryPoint, error.Id); + Assert.Equal(DiagnosticSeverity.Error, error.Severity); + Assert.Equal("Entry point method must be static", error.Message); + Assert.Equal("test.il", error.Location.Source.Path); + Assert.Equal(new SourceSpan(source.IndexOf(".entrypoint", StringComparison.Ordinal), ".entrypoint".Length), error.Location.Span); + if (errorTolerant) + { + Assert.NotNull(result); + using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); + Assert.Equal(0, pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); + Assert.True(pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint.IsNil); + } + else + { + Assert.Null(result); + } + } + + [Fact] + public void EntryPointAcrossDocuments_ReportsDuplicateAndRetainsFirst() + { + var first = new SourceText(""" + .assembly test { } + .method public static void Main() cil managed { .entrypoint ret } + """, "first.il"); + var second = new SourceText(""" + .method public static void Other() cil managed { .entrypoint ret } + """, "second.il"); + + var (diagnostics, result) = new DocumentCompiler().Compile( + [first, second], + _ => throw new InvalidOperationException("Unexpected include"), + _ => throw new InvalidOperationException("Unexpected resource"), + new Options { ErrorTolerant = true }); + + Diagnostic error = Assert.Single(diagnostics); + Assert.Equal(DiagnosticIds.DuplicateEntryPoint, error.Id); + Assert.Equal(DiagnosticSeverity.Error, error.Severity); + Assert.Equal("second.il", error.Location.Source.Path); + Assert.Equal(new SourceSpan(second.Text.IndexOf(".entrypoint", StringComparison.Ordinal), ".entrypoint".Length), error.Location.Span); + Assert.NotNull(result); + using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); + MetadataReader reader = pe.GetMetadataReader(); + MethodDefinitionHandle mainHandle = reader.MethodDefinitions + .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Main"); + Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + } + + [Fact] + public void InstanceEntryPoint_DoesNotPreventSubsequentStaticEntryPoint() + { + string source = """ + .assembly test { } + .class public Program + { + .method public instance void Invalid() cil managed { .entrypoint ret } + .method public static void Main() cil managed { .entrypoint ret } + } + """; + + var (diagnostics, result) = DocumentCompilerTestHelpers.CompileWithDiagnostics( + source, new Options { ErrorTolerant = true, Debug = true }); + Assert.Equal(DiagnosticIds.InstanceEntryPoint, Assert.Single(diagnostics).Id); + Assert.NotNull(result); + using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); + MetadataReader reader = pe.GetMetadataReader(); + MethodDefinitionHandle mainHandle = reader.MethodDefinitions + .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Main"); + Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); + Assert.Equal(mainHandle, pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint); + } + [Fact] public void EntryPointMethod_SetsCorHeaderEntryPointToken() { From 815f1d01f2453e547c9a0e41a4d8dab78ddfaa14 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Mon, 26 Oct 2026 10:12:48 -0700 Subject: [PATCH 2/3] Preserve invalid entrypoints in error-tolerant ilasm output Retain the first declared entrypoint even when it is an instance method, while continuing to diagnose invalid and duplicate entrypoints. Update recovery tests and documentation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/tools/ilasm/README.md | 4 +- .../Actions/GrammarActions.Instructions.cs | 1 - .../tests/ILAssembler.Tests/MethodTests.cs | 52 ++++++++++++++----- 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/src/tools/ilasm/README.md b/src/tools/ilasm/README.md index 7000395ff317c7..071a6d84ff3baf 100644 --- a/src/tools/ilasm/README.md +++ b/src/tools/ilasm/README.md @@ -25,8 +25,8 @@ This will update the generated files before building the main project. Only one method may declare `.entrypoint`, and that method must be static. A repeated directive (including a second directive in the same method) or an instance entry point is an assembly error reported at the directive. -With `-ERROR`, the image is emitted: the first valid entry point is retained, -and an instance method is not selected. Compiler callers still receive the +With `-ERROR`, the image is emitted: the first entry point is retained, +even if it is an invalid instance method. Compiler callers still receive the diagnostics; the command line suppresses them in error-tolerant mode. --- diff --git a/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs b/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs index 819eb8ea41491c..464c754ff0e4dd 100644 --- a/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs +++ b/src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Instructions.cs @@ -275,7 +275,6 @@ internal void SetEntryPoint(IToken directiveToken) DiagnosticIds.InstanceEntryPoint, DiagnosticMessageTemplates.InstanceEntryPoint, directiveToken); - return; } _entityRegistry.EntryPoint = _currentMethod.Definition; diff --git a/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs b/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs index cbbaf4c5ffa665..f76987ac8849fc 100644 --- a/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs +++ b/src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs @@ -552,9 +552,12 @@ .class public Program { Assert.NotNull(result); using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); - Assert.Equal(0, pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + MetadataReader reader = pe.GetMetadataReader(); + MethodDefinitionHandle mainHandle = reader.MethodDefinitions + .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Main"); + Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); - Assert.True(pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint.IsNil); + Assert.Equal(mainHandle, pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint); } else { @@ -592,8 +595,10 @@ .method public static void Other() cil managed { .entrypoint ret } Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); } - [Fact] - public void InstanceEntryPoint_DoesNotPreventSubsequentStaticEntryPoint() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InstanceEntryPoint_WithSubsequentEntryPoint_ReportsDuplicateAndRetainsFirst(bool errorTolerant) { string source = """ .assembly test { } @@ -605,16 +610,35 @@ .method public static void Main() cil managed { .entrypoint ret } """; var (diagnostics, result) = DocumentCompilerTestHelpers.CompileWithDiagnostics( - source, new Options { ErrorTolerant = true, Debug = true }); - Assert.Equal(DiagnosticIds.InstanceEntryPoint, Assert.Single(diagnostics).Id); - Assert.NotNull(result); - using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); - MetadataReader reader = pe.GetMetadataReader(); - MethodDefinitionHandle mainHandle = reader.MethodDefinitions - .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Main"); - Assert.Equal(MetadataTokens.GetToken(mainHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); - using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); - Assert.Equal(mainHandle, pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint); + source, new Options { ErrorTolerant = errorTolerant, Debug = true }); + Assert.Collection(diagnostics, + error => + { + Assert.Equal(DiagnosticIds.InstanceEntryPoint, error.Id); + Assert.Equal(DiagnosticSeverity.Error, error.Severity); + Assert.Equal(new SourceSpan(source.IndexOf(".entrypoint", StringComparison.Ordinal), ".entrypoint".Length), error.Location.Span); + }, + error => + { + Assert.Equal(DiagnosticIds.DuplicateEntryPoint, error.Id); + Assert.Equal(DiagnosticSeverity.Error, error.Severity); + Assert.Equal(new SourceSpan(source.LastIndexOf(".entrypoint", StringComparison.Ordinal), ".entrypoint".Length), error.Location.Span); + }); + if (errorTolerant) + { + Assert.NotNull(result); + using var pe = new PEReader(DocumentCompilerTestHelpers.Serialize(result)); + MetadataReader reader = pe.GetMetadataReader(); + MethodDefinitionHandle invalidHandle = reader.MethodDefinitions + .Single(handle => reader.GetString(reader.GetMethodDefinition(handle).Name) == "Invalid"); + Assert.Equal(MetadataTokens.GetToken(invalidHandle), pe.PEHeaders.CorHeader!.EntryPointTokenOrRelativeVirtualAddress); + using MetadataReaderProvider pdb = DocumentCompilerTestHelpers.GetPortablePdbReaderProvider(result); + Assert.Equal(invalidHandle, pdb.GetMetadataReader().DebugMetadataHeader!.EntryPoint); + } + else + { + Assert.Null(result); + } } [Fact] From dcb60fcdb252692546e664e1f9849b7f90001fd7 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Mon, 26 Oct 2026 20:22:30 -0700 Subject: [PATCH 3/3] Revert entrypoint README changes Remove the entrypoint documentation addition as requested in review; retain implementation and regression tests unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/tools/ilasm/README.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/tools/ilasm/README.md b/src/tools/ilasm/README.md index 071a6d84ff3baf..203eaecda412cf 100644 --- a/src/tools/ilasm/README.md +++ b/src/tools/ilasm/README.md @@ -20,15 +20,6 @@ If you modify any `.g4` grammar files (rare), you must regenerate the parser and This will update the generated files before building the main project. -## Entry-point validation - -Only one method may declare `.entrypoint`, and that method must be static. -A repeated directive (including a second directive in the same method) or an -instance entry point is an assembly error reported at the directive. -With `-ERROR`, the image is emitted: the first entry point is retained, -even if it is an invalid instance method. Compiler callers still receive the -diagnostics; the command line suppresses them in error-tolerant mode. - --- For more details, see the main repository README or contact the maintainers.