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
4 changes: 4 additions & 0 deletions src/tools/ilasm/MANAGED-ILASM-FIXES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ This table includes deliberate behavior differences as well as fixes. Defects li

| Fixed issue | ilasm behavior | Managed ILASM behavior |
| --- | --- | --- |
| `#line` auto-increment | Advances only the start line on each physical newline, leaving the end line unchanged and producing reversed ranges. | Advances both line endpoints by the physical source-line delta, preserving the range and columns. The line-only form with a double-quoted file name maps the following source line to the specified line; other forms map the directive's own line to it. Includes have independent mappings, and unrepresentable effective spans are diagnosed at the directive. |
| Pseudoattribute lowering is opt-in | Automatically lowers recognized pseudo custom attributes. | Preserves custom attributes unchanged by default; `--pseudoattributes` enables lowering and the pseudoattribute-specific fixes below. |
| Partly specified `.line` end columns | Fails to assemble partly specified `.line` directives when producing a Portable PDB. | Defaults an omitted end column to `0xfffe` (65534) for compatibility with existing metadata readers; explicit end columns are preserved and validated, including the legal maximum `0xffff`. Hidden sequence points retain columns `0,0`. |
| Unencodable sequence-point line deltas | Cannot encode start-line differences outside the signed compressed integer range. | Reports `ILA0061` when the start line differs from the previous non-hidden point by less than `-0x10000000` or more than `0x0fffffff`, including across document changes and hidden points. Error-tolerant mode omits the unencodable point. |
| Invalid sequence-point coordinates | Warns and fails the method body for invalid coordinates. | Reports `ILA0061` at the `.line` or `#line` directive when producing a PDB: line and column values must fit the Portable PDB format, ranges must be ordered, and hidden points require both lines `0xFEEFEE` and columns `0,0`. Assembly fails unless error-tolerant mode is enabled; in that mode the instructions are retained but points from invalid directives are omitted, since some invalid ranges cannot be encoded. |
| `FloatingPointInstruction_ByteForms_EmitExpectedConstants` | Rejects the `bytearray` operand for floating-point constants. | Accepts byte-array forms for floating-point instruction constants. |
| `LabelBasedFilterRegion_EmitsExactExceptionRegionBounds` | Rejects the label-based filter region as undefined or structurally separated. | Emits the label-based filter region with the requested bounds. |
| `Ldtoken_NumericTokenEmittedCorrectly` | Rejects a numeric metadata token as an `ldtoken` operand. | Accepts and emits a numeric metadata token operand for `ldtoken`. |
Expand Down
18 changes: 18 additions & 0 deletions src/tools/ilasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,22 @@ This will update the generated files before building the main project.

---

## Source line mapping

With debug information enabled, `.line` fixes the source span of subsequent instructions until another
source directive is encountered. `#line` also advances both line endpoints for each physical source
newline, including blank and comment lines, while keeping the columns unchanged. The hidden-sequence-point
marker remains hidden until another directive.

The line-only form with a double-quoted file name, such as `#line 42 "program.cs"`, assigns line 42 to
the following source line. Other forms, such as `#line 42 'program.cs'` or
`#line 42,44 : 1,8 'program.cs'`, anchor the specified range to the directive's own source line.
Instructions on the same source line share a sequence point. Includes maintain their own mappings;
returning from an include restores the including source's mapping. An effective span outside the
Portable PDB coordinate limits is diagnosed at the directive.

An omitted end column defaults to 65534 (`ushort.MaxValue - 1`) for compatibility with existing
metadata readers. Explicit columns are preserved, including the legal maximum 65535, which requires
a corrected reader. Hidden sequence points retain columns `0,0`.

For more details, see the main repository README or contact the maintainers.
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ private ImmutableArray<ValidatedExport> ValidateExports(
portablePdb = null;

// Only /DEBUG (any mode) or /PDB produces a PDB. Without them, .line
// directives are still parsed and validated, and no sequence points are recorded.
// directives are still parsed, but their PDB coordinates are not validated or recorded.
if (!GeneratesPdb)
{
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ public CurrentMethodContext(EntityRegistry.MethodDefinitionEntity definition)

public EntityRegistry.MethodDefinitionEntity Definition { get; }

public SequencePointSpan? LastRejectedSequencePointSpan { get; set; }

public Dictionary<string, LabelHandle> Labels { get; } = new();

public Dictionary<string, IToken> UndefinedLabelReferences { get; } = new();
Expand Down
148 changes: 132 additions & 16 deletions src/tools/ilasm/src/ILAssembler/Actions/GrammarActions.Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using Antlr4.Runtime;

namespace ILAssembler;
Expand All @@ -20,7 +21,9 @@ internal SourceDirectiveValue CreateSourceLine(
IToken? path)
{
int lineNumber = ParseInt32(line);
return CreateSourceDirective(autoIncrement, lineNumber, 0, lineNumber, 0, path);
return CreateSourceDirective(
autoIncrement, lineNumber, 0, lineNumber, null, path,
appliesToNextLine: autoIncrement && path?.Type == CILLexer.QSTRING);
}

internal SourceDirectiveValue CreateSourceColumn(
Expand All @@ -36,7 +39,7 @@ internal SourceDirectiveValue CreateSourceColumn(
lineNumber,
columnNumber,
lineNumber,
columnNumber,
null,
path);
}

Expand Down Expand Up @@ -70,7 +73,7 @@ internal SourceDirectiveValue CreateSourceLineRange(
ParseInt32(startLine),
columnNumber,
ParseInt32(endLine),
columnNumber,
null,
path);
}

Expand All @@ -94,15 +97,26 @@ private static SourceDirectiveValue CreateSourceDirective(
int startLine,
int startColumn,
int endLine,
int endColumn,
IToken? path)
=> new(
int? endColumn,
IToken? path,
bool appliesToNextLine = false)
{
// Match Roslyn's column limit for compatibility with existing SRM readers' off-by-one check:
// https://github.com/dotnet/roslyn/blob/e3c31f15b79e226656e3b082a921d4d60127b1fa/src/Compilers/Core/Portable/CodeGen/SequencePointList.cs#L182-L186
const int DefaultEndColumn = ushort.MaxValue - 1;

return new(
autoIncrement,
startLine,
startColumn,
endLine,
endColumn,
path is null ? null : StringHelpers.ParseQuotedString(path.Text));
endColumn ?? (startLine == SequencePoint.HiddenLine && endLine == SequencePoint.HiddenLine &&
startColumn == 0 ? 0 : DefaultEndColumn),
path is null ? null : StringHelpers.ParseQuotedString(path.Text))
{
AppliesToNextLine = appliesToNextLine,
};
}

internal void EndSourceDirective(
CILParser.ExtSourceSpecContext context,
Expand Down Expand Up @@ -135,7 +149,10 @@ context.Value is not { } value ||
/// inclusion of an <c>#include</c>d file), wherever it is and across methods, and the next instruction always
/// gets a point. An empty file name (<c>''</c> or <c>""</c>), which ildasm writes for "the same file", and
/// a missing one keep the source's current document: the source itself until a directive in it names another
/// file.
/// file. With <c>#line</c>, both line endpoints advance by the number of physical source lines since the
/// directive; columns do not change. The line-only form with a double-quoted file name anchors the specified
/// line to the following source line; all other forms anchor it to the directive's own line. Hidden sequence
/// points stay hidden until another directive, since their line is a marker rather than a source coordinate.
/// </remarks>
private void ApplySourceDirective(SourceDirectiveValue value, IToken directiveToken)
{
Expand All @@ -145,14 +162,56 @@ private void ApplySourceDirective(SourceDirectiveValue value, IToken directiveTo
state.Document = _pdbDocuments.GetOrAdd(value.DocumentPath, _currentLanguageGuid);
}

int endColumn = value.EndColumn;
if (value.EndLine == value.StartLine && endColumn == value.StartColumn)
state.HasInvalidDirective = GeneratesPdb && !ValidateSourceDirective(value, directiveToken);
state.DirectiveToken = directiveToken;
state.DirectiveCoordinates = (value.StartLine, value.StartColumn, value.EndLine, value.EndColumn);
state.AutoIncrementLine = value.AutoIncrement
? (long)directiveToken.Line + (value.AppliesToNextLine ? 1 : 0)
: null;
_lastSequencePointSpan = null;
if (_currentMethod is not null)
{
endColumn++;
_currentMethod.LastRejectedSequencePointSpan = null;
}
}

state.DirectiveCoordinates = (value.StartLine, value.StartColumn, value.EndLine, endColumn);
_lastSequencePointSpan = null;
private bool ValidateSourceDirective(SourceDirectiveValue value, IToken directiveToken)
=> ValidateSourceCoordinates(value.StartLine, value.StartColumn, value.EndLine, value.EndColumn, directiveToken);

private bool ValidateSourceCoordinates(long startLine, int startColumn, long endLine, int endColumn, IToken directiveToken)
{
// Portable PDB, Sequence Points: docs/design/specs/PortablePdb-Metadata.md#sequence-points-blob.
const int MaximumLine = 0x1fffffff;
string? message = null;
if (startLine == SequencePoint.HiddenLine || endLine == SequencePoint.HiddenLine)
{
if (startLine != SequencePoint.HiddenLine || endLine != SequencePoint.HiddenLine ||
startColumn != 0 || endColumn != 0)
{
message = DiagnosticMessageTemplates.InvalidHiddenSequencePoint;
}
}
else if ((ulong)startLine > MaximumLine || (ulong)endLine > MaximumLine)
{
message = DiagnosticMessageTemplates.SequencePointLineOutOfRange;
}
else if ((uint)startColumn > ushort.MaxValue || (uint)endColumn > ushort.MaxValue)
{
message = DiagnosticMessageTemplates.SequencePointColumnOutOfRange;
}
else if (endLine < startLine ||
(endLine == startLine && endColumn <= startColumn))
{
message = DiagnosticMessageTemplates.SequencePointReversedRange;
}

if (message is not null)
{
ReportError(DiagnosticIds.InvalidSequencePoint, message, directiveToken);
return false;
}

return true;
}

/// <summary>
Expand Down Expand Up @@ -184,19 +243,67 @@ private void RecordSequencePoint(CurrentMethodContext method, IToken opcodeToken
}

SourceLineState state = GetSourceLineState(opcodeToken);
if (state.HasInvalidDirective)
{
// An invalid range may not be representable in the sequence-points blob, even in error-tolerant mode.
return;
}

int document = state.Document ??= _pdbDocuments.GetOrAdd(state.SourceName, _currentLanguageGuid);
(int startLine, int startColumn, int endLine, int endColumn) =
state.DirectiveCoordinates ?? (opcodeToken.Line, 1, opcodeToken.Line, 2);
if (state.AutoIncrementLine is long directiveLine && startLine != SequencePoint.HiddenLine)
{
long delta = (long)opcodeToken.Line - directiveLine;
long effectiveStartLine = startLine + delta;
long effectiveEndLine = endLine + delta;
Debug.Assert(state.DirectiveToken is not null);
if (!ValidateSourceCoordinates(effectiveStartLine, startColumn, effectiveEndLine, endColumn, state.DirectiveToken))
{
state.HasInvalidDirective = true;
return;
}

startLine = (int)effectiveStartLine;
endLine = (int)effectiveEndLine;
}

var span = new SequencePointSpan(document, startLine, startColumn, endLine, endColumn);
if (_lastSequencePointSpan == span)
if (_lastSequencePointSpan == span || method.LastRejectedSequencePointSpan == span)
{
return;
}

_lastSequencePointSpan = span;
int ilOffset = method.Definition.MethodBody.Offset;
var point = new EntityRegistry.SequencePoint(document, ilOffset, startLine, startColumn, endLine, endColumn);
List<EntityRegistry.SequencePoint> sequencePoints = method.Definition.DebugInfo.SequencePoints;
if (!point.IsHidden)
{
// Start lines after the first non-hidden point use a signed compressed integer, across documents
// and hidden points. Exclude a point at this offset, since it is about to be replaced.
for (int i = sequencePoints.Count - 1; i >= 0; i--)
{
EntityRegistry.SequencePoint previous = sequencePoints[i];
if (previous.IsHidden || previous.ILOffset == ilOffset)
{
continue;
}

int delta = startLine - previous.StartLine;
if (delta is < -0x10000000 or > 0x0fffffff)
{
method.LastRejectedSequencePointSpan = span;
ReportError(
DiagnosticIds.InvalidSequencePoint,
DiagnosticMessageTemplates.SequencePointLineDeltaOutOfRange,
state.DirectiveToken ?? opcodeToken);
return;
Comment thread
jkoritzinsky marked this conversation as resolved.
Resolved
}

break;
}
}

Debug.Assert(sequencePoints.Count == 0 || sequencePoints[^1].ILOffset <= ilOffset, "IL offsets never decrease.");
if (sequencePoints.Count > 0 && sequencePoints[^1].ILOffset == ilOffset)
{
Expand All @@ -208,6 +315,9 @@ private void RecordSequencePoint(CurrentMethodContext method, IToken opcodeToken
{
sequencePoints.Add(point);
}

_lastSequencePointSpan = span;
method.LastRejectedSequencePointSpan = null;
}

/// <summary>Gets the <c>.line</c> state of the source a token was read from, creating it on first use.</summary>
Expand Down Expand Up @@ -250,6 +360,12 @@ private sealed class SourceLineState(string sourceName)
/// source, or <see langword="null"/> when none has been.
/// </summary>
public (int StartLine, int StartColumn, int EndLine, int EndColumn)? DirectiveCoordinates { get; set; }

public bool HasInvalidDirective { get; set; }

public long? AutoIncrementLine { get; set; }

public IToken? DirectiveToken { get; set; }
}

/// <summary>The document and source span of a recorded sequence point.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ public sealed record SourceDirectiveValue(
int StartColumn,
int EndLine,
int EndColumn,
string? DocumentPath);
string? DocumentPath)
{
public bool AppliesToNextLine { get; init; }
}

public sealed record LanguageDirectiveValue(
string Language,
Expand Down
6 changes: 6 additions & 0 deletions src/tools/ilasm/src/ILAssembler/Diagnostic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public static class DiagnosticIds
public const string LocalScopeWithoutInstructions = "ILA0058";
public const string LocalNameDeclaredTwiceInScope = "ILA0059";
public const string LocalSlotNamedTwiceInScope = "ILA0060";
public const string InvalidSequencePoint = "ILA0061";
public const string DuplicateEntryPoint = "ILA0063";
public const string InstanceEntryPoint = "ILA0064";
}
Expand Down Expand Up @@ -144,6 +145,11 @@ 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 InvalidHiddenSequencePoint = "A hidden sequence point must have start and end lines 0xFEEFEE and columns 0,0";
public const string SequencePointLineOutOfRange = "Sequence point lines must be between 0 and 0x1fffffff";
public const string SequencePointColumnOutOfRange = "Sequence point columns must be between 0 and 0xffff";
public const string SequencePointReversedRange = "A sequence point must end after it starts";
public const string SequencePointLineDeltaOutOfRange = "The start line difference from the previous non-hidden sequence point must be between -0x10000000 and 0x0fffffff";
public const string DuplicateEntryPoint = "Multiple entry points declared";
public const string InstanceEntryPoint = "Entry point method must be static";
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.CommandLine;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using Xunit;

namespace ILAssembler.Tests;
Expand Down Expand Up @@ -170,6 +171,40 @@ private static (int Offset, int StartLine, int StartColumn, int EndLine, int End
private static (int, int, int, int, int, string) OnLine(int offset, int line, string document)
=> (offset, line, 1, line, 2, document);

[Theory]
[InlineData("10,9 : 1,2", false)]
[InlineData("10,9 : 1,2", true)]
[InlineData("10,10 : 1,70000", false)]
[InlineData("10,10 : 1,70000", true)]
[InlineData("0xFEEFEE,0xFEEFEE : 1,2", false)]
[InlineData("0xFEEFEE,0xFEEFEE : 1,2", true)]
public void InvalidSequencePoint_RequiresErrorToleranceToWriteOutput(string coordinates, bool errorTolerant)
{
string source = DocumentCompilerTestHelpers.MethodSource($".line {coordinates} 'a.cs'\nnop\nret");
string input = WriteSource("invalid.il", source);
string dll = Path.Combine(_directory, "out", "Test.dll");
string pdbPath = Path.ChangeExtension(dll, ".pdb");
string[] args = ["-nologo", "-quiet", "-dll", "-debug", $"-output={dll}", input];
if (errorTolerant)
{
args = [.. args, "-error"];
}

var command = new IlasmRootCommand();
ParseResult result = command.Parse(NativeCommandLine.Normalize(args, command));
Assert.Empty(result.Errors);
Assert.Equal(errorTolerant ? 0 : 1, new Program(command, result).Run());
Assert.Equal(errorTolerant, File.Exists(dll));
Assert.Equal(errorTolerant, File.Exists(pdbPath));
if (errorTolerant)
{
using var pdb = PortablePdbTestReader.Open(dll, pdbPath);
Assert.Empty(pdb.GetSequencePoints("M"));
using var pe = new PEReader(File.OpenRead(dll));
Assert.Equal(new byte[] { 0, 0x2a }, DocumentCompilerTestHelpers.GetMethodBody(pe).GetILBytes());
}
}

// The input's implicit points are in a document named by the input's full path, whatever path the command line
// gives: a path relative to the current directory (read, never set: it is process-wide), or a full path with a
// ".." segment.
Expand Down
Loading
Loading