Repository navigation
Description
TL;DR: When ILLink removes unreachable code, the local scopes that covered it stay in the PDB with zero length, and can come before a sibling scope that starts at the same offset. Both break the Portable PDB spec's
LocalScoperules; a reader that validates them refuses the whole PDB, which is how I found this inSystem.Private.CoreLib.pdb. Would you prefer the fix in ILLink or in Cecil's writer? I can send a PR for the one you choose.
Description
When ILLink removes unreachable code (for example, under a feature switch or a substitution), the local scopes that covered that code stay in the PDB with zero length, collapsed onto the offset of the first instruction after the removed code. When a sibling scope starts at that same offset, the zero-length row comes before it. Both break the Portable PDB spec:
Lengthis "integer (0..0x80000000)", an open interval, so 0 is out of range;- "The table is required to be sorted first by Method in ascending order, then by StartOffset in ascending order, then by Length in descending order." A zero-length row placed before a longer row with the same start breaks the third key.
Impact. System.Reflection.Metadata reads these rows without complaint. A reader that validates the spec's LocalScope constraints refuses the whole PDB. Ours refused System.Private.CoreLib.pdb, which is how we found this. I have not seen a debugger symptom.
Question. Would you prefer the fix in ILLink or in Cecil's writer? The two options are under "Possible fixes" below. I can send a PR for the one you choose.
The System.Private.CoreLib.pdb of the 10.0.12 linux-x64 runtime from Ubuntu's source-built packages (dotnet-runtime-dbg-10.0) has 54 zero-length LocalScope rows across 44 methods. Three of those rows are in System.Collections.BitArray.CopyTo, from the removed AdvSimd.Arm64.IsSupported branch. They sit at offset 1171, before the [1171, 1221) scope of the loop that follows, and that is the file's only ordering break. Microsoft's runtime packs do not include the CoreLib PDB, so I could not check Microsoft's own build.
Reproduction
Save the project and program below in a directory app/, and the scope lister in scopes.cs beside that directory, outside the project. Then run, from the parent directory:
dotnet build app/ZeroScope.csproj -c Debug -o out-build
dotnet publish app/ZeroScope.csproj -c Debug -o out-publish
dotnet run scopes.cs -- out-build/ZeroScope.dll out-build/ZeroScope.pdb Run
dotnet run scopes.cs -- out-publish/ZeroScope.dll out-publish/ZeroScope.pdb Runapp/ZeroScope.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<DebugType>portable</DebugType>
<PublishTrimmed>true</PublishTrimmed>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
</PropertyGroup>
<ItemGroup>
<RuntimeHostConfigurationOption Include="ZeroScope.Feature.IsSupported" Value="false" Trim="true" />
</ItemGroup>
</Project>app/Program.cs:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
public static class Feature
{
[FeatureSwitchDefinition("ZeroScope.Feature.IsSupported")]
public static bool IsSupported =>
AppContext.TryGetSwitch("ZeroScope.Feature.IsSupported", out bool on) && on;
}
public static class Program
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static int Run(int n)
{
int total = 0;
if (Feature.IsSupported)
{
int doubled = n * 2;
total += doubled;
}
else
{
int tripled = n * 3;
total += tripled;
}
return total;
}
public static int Main(string[] args) => Run(args.Length) == 0 ? 0 : 1;
}scopes.cs: lists a method's LocalScope rows in table order
#:property UseAppHost=false
// Usage: dotnet run scopes.cs -- <dll> <pdb> <methodName>
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
var (dllPath, pdbPath, name) = (args[0], args[1], args[2]);
using var pe = new PEReader(File.OpenRead(dllPath));
var md = pe.GetMetadataReader();
using var pdbProvider = MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(pdbPath));
var pdb = pdbProvider.GetMetadataReader();
int rowNumber = 0;
foreach (var h in pdb.LocalScopes)
{
rowNumber++;
var s = pdb.GetLocalScope(h);
var m = md.GetMethodDefinition(s.Method);
if (md.GetString(m.Name) != name)
continue;
var vars = string.Join(", ", s.GetLocalVariables().Select(v => pdb.GetString(pdb.GetLocalVariable(v).Name)));
Console.WriteLine($"row {rowNumber}: method 0x{MetadataTokens.GetToken(s.Method):X8} [{s.StartOffset},{s.EndOffset}) length {s.Length} vars [{vars}]");
}Expected: the trimmed PDB's LocalScope rows satisfy the spec's Length range and sort order, as the untrimmed build's do.
Actual, with SDK 10.0.301 on Ubuntu 26.04 x64:
$ dotnet run scopes.cs -- out-build/ZeroScope.dll out-build/ZeroScope.pdb Run
row 2: method 0x06000002 [0,42) length 42 vars [total]
row 3: method 0x06000002 [12,22) length 10 vars [doubled]
row 4: method 0x06000002 [24,34) length 10 vars [tripled]
$ dotnet run scopes.cs -- out-publish/ZeroScope.dll out-publish/ZeroScope.pdb Run
row 1: method 0x06000001 [0,26) length 26 vars [total]
row 2: method 0x06000001 [8,8) length 0 vars [doubled]
row 3: method 0x06000001 [8,18) length 10 vars [tripled]
Configuration. Reproduced with SDK 10.0.301 (Microsoft.NET.ILLink.Tasks 10.0.9) and with SDK 11.0.100-preview.7 (Microsoft.NET.ILLink.Tasks 10.0.10), in Debug and in Release. In Release, the publish gives [5,5) doubled before [5,13) tripled. With the switch set to true, the else branch is the one removed, and its scope becomes a zero-length [19,19) after the kept scope: out of range, but in order. I have not tried a build of main.
Cause
This analysis is of the Cecil that runtime v10.0.12 pins (Microsoft.DotNet.Cecil 0.11.5-alpha.26411.108, dotnet/dotnet 6f10c96a0e):
UnreachableBlocksOptimizer'sBodySweeper.Processfirst replaces unreachable instructions withnop(or a terminalret).BodyReducer.RewriteBodythen removes them (inRemoveUnreachableInstructions) and the sentinelnops. Both removals go throughLinkerILProcessor.RemoveAt/Remove(src/tools/illink/src/linker/Linker/LinkerILProcessor.cs). That wrapper re-targets exception-handler boundaries and branch operands itself. ItsRedirectScopeEndis empty ("Currently Cecil treats all block boundaries as 'starts' so nothing to do here"), and it leaves debug-scope boundaries to Cecil'sILProcessor.Remove.- Cecil's
InstructionCollection.OnRemovecallsUpdateDebugInformation(item, next ?? previous), which re-targets a scope boundary that referred to the removed instruction (src/cecil/Mono.Cecil.Cil/MethodBody.cs; an end-of-methodEndis left alone). In this reproduction, the successive removals move the dead scope'sStartonto itsEnd.UpdateLocalScopeupdates the bounds of every scope in the tree, but it never removes one. MetadataBuilder.AddLocalScope(src/cecil/Mono.Cecil/AssemblyWriter.cs) writes the scope tree depth-first, withLength = End.Offset - Start.Offsetand no check for zero, andLocalScopeTableis not a sorted table. So the collapsed scope keeps its pre-trim position, before a later sibling that starts at the same offset.
The same code is on main (checked 2026-10-04). In dotnet/runtime main, UnreachableBlocksOptimizer still removes through processor.Remove and processor.RemoveAt, and the repository pins Cecil 0.11.5-preview.26471.108. In dotnet/cecil main (0d7319f08f), OnRemove, UpdateLocalScope, AddLocalScope and LocalScopeTable are unchanged.
Possible fixes, and a question
One fix would be to omit LocalScope rows whose final range is empty, together with their variable and constant rows and the custom debug information attached to them. In this reproduction their child scopes are empty too, but a general fix should check that rather than assume it. This applies to the LocalScope tree only. The StateMachineHoistedLocalScopes blob is positional, with one entry per hoisted variable, so its entries cannot be dropped the same way.
There are two places it could go:
- ILLink, in
LinkerILProcessor.Remove, which already keeps exception-handler boundaries consistent, or in a pass afterBodyReducer.RewriteBody. This is confined to ILLink, and does not change Cecil's behaviour for other users. - Cecil's writer (
AddLocalScope). This covers every Cecil user and any input, but it changes serialization for all of them. Per dotnet/cecil's README, such a change would go to jbevain/cecil first.
Sorting the LocalScope rows alone would not be enough, because the zero-length rows would still be out of range.
The ILLink-side change looks smaller to me, but you know the constraints better. Which would you prefer? I'm happy to send a PR for it.
Note
This report was prepared with AI assistance (Anthropic Claude and OpenAI Codex) under my direction, and I reviewed it before posting. The reproduction output above is from running the steps exactly as written.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Oct 5, 2026
Tagging subscribers to this area: @agocke, @dotnet/illink
See info in area-owners.md if you want to be subscribed.