Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -252,12 +253,31 @@ internal void SetMaxStack(IToken valueToken)
}
}

internal void SetEntryPoint()
internal void SetEntryPoint(IToken directiveToken)
{
if (_currentMethod is not null)
if (_currentMethod is null)
{
return;
}

if (_entityRegistry.EntryPoint is not null)
{
ReportError(
DiagnosticIds.DuplicateEntryPoint,
DiagnosticMessageTemplates.DuplicateEntryPoint,
directiveToken);
return;
}

if (!_currentMethod.Definition.MethodAttributes.HasFlag(MethodAttributes.Static))
{
_entityRegistry.EntryPoint = _currentMethod.Definition;
ReportError(
DiagnosticIds.InstanceEntryPoint,
DiagnosticMessageTemplates.InstanceEntryPoint,
directiveToken);
}

_entityRegistry.EntryPoint = _currentMethod.Definition;
}

internal void SetZeroInit()
Expand Down
4 changes: 4 additions & 0 deletions src/tools/ilasm/src/ILAssembler/Diagnostic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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";
}
2 changes: 1 addition & 1 deletion src/tools/ilasm/src/ILAssembler/gen/CIL.g4
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/tools/ilasm/src/ILAssembler/gen/CILParser.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

170 changes: 170 additions & 0 deletions src/tools/ilasm/tests/ILAssembler.Tests/MethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,176 @@ .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));
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);
}
}

[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);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void InstanceEntryPoint_WithSubsequentEntryPoint_ReportsDuplicateAndRetainsFirst(bool errorTolerant)
{
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 = 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]
public void EntryPointMethod_SetsCorHeaderEntryPointToken()
{
Expand Down
Loading