Skip to content

EmbeddedResourceInjectorTask potentially corrupts PDB files #24036

Closed

Description

@jonpryor

Current behavior 🐛

Context: #23966

While trying to add an iOS+Native AOT test stage (#23966), I found that the build would fail with:

Error: Sequence point value is out of range.
System.BadImageFormatException: Sequence point value is out of range.
   at System.Reflection.Throw.SequencePointValueOutOfRange() in /_/src/runtime/src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs:line 239

After (too much) investigation, I have tracked it down to EmbeddedResourceInjectorTask_v0:

public class EmbeddedResourceInjectorTask_v0 : Microsoft.Build.Utilities.Task
{
private const MessageImportance DefaultLogMessageLevel
#if DEBUG
= MessageImportance.High;
#else
= MessageImportance.Low;
#endif
[Required]
public Microsoft.Build.Framework.ITaskItem[]? EmbeddedResources { get; set; }
[Required]
public string TargetAssembly { get; set; } = "";
[Required]
public Microsoft.Build.Framework.ITaskItem[]? ReferencePath { get; set; }
public override bool Execute()
{
try
{
// Debugger.Launch();
if (EmbeddedResources?.Length > 0)
{
Log.LogMessage(DefaultLogMessageLevel, $"Writing embedded files to {TargetAssembly}");
var resolver = new DefaultAssemblyResolver();
foreach (var path in BuildReferencesPaths())
{
resolver.AddSearchDirectory(path);
}
using (var asm = AssemblyDefinition.ReadAssembly(TargetAssembly, new()
{
AssemblyResolver = resolver,
ReadSymbols = true,
ReadWrite = true,
SymbolReaderProvider = new DefaultSymbolReaderProvider(throwIfNoSymbol: false),
}))
{
foreach (var embeddedResource in EmbeddedResources)
{
var logicalName = embeddedResource.GetMetadata("LogicalName");
Log.LogMessage(MessageImportance.Low, $"Embedding file {embeddedResource.ItemSpec} as {logicalName}");
// Remove existing resources with the same name
var existingResources = asm.MainModule.Resources
.OfType<EmbeddedResource>()
.Where(r => r.Name == logicalName)
.ToArray();
foreach (var existingResource in existingResources)
{
asm.MainModule.Resources.Remove(existingResource);
}
// Add the new merged content
asm.MainModule.Resources.Add(new EmbeddedResource(logicalName, ManifestResourceAttributes.Public, File.ReadAllBytes(embeddedResource.GetMetadata("FullPath"))));
}
asm.Write(new WriterParameters() { WriteSymbols = asm.MainModule.SymbolReader is not null });
}
WaitForUnlockedFile(TargetAssembly);
WaitForUnlockedFile(Path.ChangeExtension(TargetAssembly, "pdb"));
}
return true;
}
catch (Exception e)
{
// Require because the task is running out of process
// and can't marshal non-CLR known exceptions.
throw new Exception(e.ToString());
}
}
private string[] BuildReferencesPaths() => ReferencePath
.Select(p => Path.GetDirectoryName(p.ItemSpec))
.Distinct()
.ToArray();
private void WaitForUnlockedFile(string filePath)
{
// if the threadpool isn't using threads assume they aren't enabled
ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
if (workerThreads == 1 && completionPortThreads == 1)
{
// Single threaded environment, skip waiting
return;
}
var sw = Stopwatch.StartNew();
while (sw.Elapsed < TimeSpan.FromSeconds(5))
{
try
{
File.OpenWrite(filePath).Dispose();
break;
}
catch
{
Log.LogMessage(MessageImportance.Low, $"Waiting for availability for {TargetAssembly}");
}
Thread.Sleep(100);
}
}
}

(Though it's probably really in Mono.Cecil…)

Expected behavior 🎯

No System.BadImageFormatException from ilc when trying to build src/SamplesApp/SamplesApp.Skia.netcoremobile for iOS+Native AOT.

(Instead, we should instead hit dotnet/macios#26428 !)

How to reproduce it (as minimally and precisely as possible) 🔬

git clone https://github.com/unoplatform/uno
cd uno
# error is not limited to this commit; commit used for consistency/future reproducibility
git checkout 83effab5c73cddf21ef3ee7598edd9f6e45771fb
cat <<'EOF' | git apply
diff --git a/src/SourceGenerators/Uno.UI.Tasks/EmbeddedResourceInjector/EmbeddedResourceInjectorTask.cs b/src/SourceGenerators/Uno.UI.Tasks/EmbeddedResourceInjector/EmbeddedResourceInjectorTask.cs
index 778c035878..3847adc7c1 100644
--- a/src/SourceGenerators/Uno.UI.Tasks/EmbeddedResourceInjector/EmbeddedResourceInjectorTask.cs
+++ b/src/SourceGenerators/Uno.UI.Tasks/EmbeddedResourceInjector/EmbeddedResourceInjectorTask.cs
@@ -59,6 +59,13 @@ namespace Uno.UI.Tasks.EmbeddedResourceInjector
 						resolver.AddSearchDirectory(path);
 					}
 
+					File.Copy(TargetAssembly, $"{TargetAssembly}.jporig__");
+					var __pdb = Path.ChangeExtension(TargetAssembly, "pdb");
+					if (File.Exists(__pdb))
+					{
+						File.Copy(__pdb, $"{__pdb}.jporig__");
+					}
+
 					using (var asm = AssemblyDefinition.ReadAssembly(TargetAssembly, new()
 					{
 						AssemblyResolver = resolver,
EOF
dotnet build -c Release -f net10.0 -bl src/SamplesApp/SamplesApp.Skia/SamplesApp.Skia.csproj

Once completed, use the verify-pdb-sequence-points single-file script (further below) to verify the .pdb files:

% ~/bin/verify-pdb-sequence-points src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb.jporig__ src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb
src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb.jporig__
  OK - 162669 method(s) checked, all sequence points decoded cleanly.
src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb
  [row 18209] NavigationViewInfoBadgeTestPage::.ctor: BadImageFormatException: Invalid compressed integer. (after 384 good sequence point(s); last good IL=0x11F1 line=21263)
  [row 24501] ScrollViewDynamicPage::.ctor: BadImageFormatException: Invalid compressed integer. (after 156 good sequence point(s); last good IL=0x6AC line=8956)
  [row 53981] TeachingTipPage::.ctor: BadImageFormatException: Invalid compressed integer. (after 152 good sequence point(s); last good IL=0x685 line=8280)
  [row 57616] ItemsViewSummaryPage::.ctor: BadImageFormatException: Invalid compressed integer. (after 339 good sequence point(s); last good IL=0xE99 line=18531)
  4 of 162669 method(s) have corrupt sequence points.

We see that the original csc-generated .pdb is fine, but after the EmbeddedResourceInjectorTask updates the .pdb, it now contains errors.

Given that <EmbeddedResourceInjectorTask/> mostly adds and removes resources using Cecil, this is almost certainly a Cecil bug, not a Uno bug.

Workaround 🛠️

Don't use debug symbols, e.g. build with -p:DebugType=none, as is done in dotnet/macios#26428.

Renderer 🎨

  • Skia
  • Native

Affected platforms 📱💻🖥️

All platforms 🌍

Uno.Sdk version (and other relevant versions) 📦

No response

IDE version 🧑‍💻

No response

Anything else we need to know? 💬

verify-pdb-sequence-points file-based C# program
#!/usr/bin/env -S dotnet --

#:package Mono.Options@6.12.0.148

using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;

using Mono.Options;

var Name = Environment.GetCommandLineArgs()[0];
int verbosity = 0;
var show_help = false;
var options = new OptionSet {
    $"Usage: {Name} [-v] <PDB-FILES>",
    "",
    "Verify the sequence points within `.pdb` files.",
    "",
    "Options:",
    {
        "v|verbose:",
        "Increase logging verbosity or set to {VALUE}.",
        (int? v) => verbosity = v ?? (verbosity + 1)
    },
    { "help", "Show this message and exit.", v => show_help = v != null },
};
List<string> pdb_files;
try {
    pdb_files = options.Parse(args);
}
catch (Exception e) {
    Console.Error.WriteLine($"{Name}: {e.Message}");
    if (verbosity > 0)
    {
        Console.Error.WriteLine(e);
    }
    return 1;
}

if (pdb_files.Count == 0 || show_help)
{
    options.WriteOptionDescriptions(Console.Out);
    return 0;
}

if (args.Length == 0)
{
    Console.Error.WriteLine("Usage: verify-pdb-sequence-points <path-to-pdb> [more paths...]");
    return 1;
}

int totalBad = 0;
foreach (var pdbPath in args)
{
    totalBad += VerifyPdb(pdbPath);
}
return totalBad > 0 ? 1 : 0;

int VerifyPdb(string pdbPath)
{
    Console.WriteLine($"{pdbPath}");

    byte[] pdbBytes;
    try
    {
        pdbBytes = File.ReadAllBytes(pdbPath);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"  ERROR reading file: {ex.Message}");
        return 1;
    }

    using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(new MemoryStream(pdbBytes));
    MetadataReader pdbReader = provider.GetMetadataReader();

    // Optional: a sibling .dll with matching row numbers gives us type/method names.
    var dllPath = Path.ChangeExtension(pdbPath, ".dll");
    Dictionary<int, string>? namesByRow = File.Exists(dllPath) ? TryLoadNames(dllPath) : null;

    int methodCount = pdbReader.GetTableRowCount(TableIndex.MethodDebugInformation);
    int badCount = 0;

    for (int row = 1; row <= methodCount; row++)
    {
        var handle = MetadataTokens.MethodDebugInformationHandle(row);
        MethodDebugInformation info;
        try
        {
            info = pdbReader.GetMethodDebugInformation(handle);
        }
        catch (Exception ex)
        {
            badCount++;
            Console.WriteLine($"  [row {row}] {Describe(row, namesByRow)}: FAILED to read debug info header: {ex.GetType().Name}: {ex.Message}");
            continue;
        }

        if (info.SequencePointsBlob.IsNil)
        {
            continue;
        }

        int decoded = 0;
        SequencePoint last = default;
        bool haveLast = false;
        try
        {
            foreach (var sp in info.GetSequencePoints())
            {
                last = sp;
                haveLast = true;
                decoded++;
            }
        }
        catch (Exception ex)
        {
            badCount++;
            string context = haveLast
                ? $"after {decoded} good sequence point(s); last good IL=0x{last.Offset:X} line={last.StartLine}"
                : "on the very first sequence point";
            Console.WriteLine($"  [row {row}] {Describe(row, namesByRow)}: {ex.GetType().Name}: {ex.Message} ({context})");
            if (verbosity > 0)
            {
                var reader = new StringReader(ex.ToString());
                string? line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine($"    {line}");
                }
            }
        }
    }

    if (badCount == 0)
    {
        Console.WriteLine($"  OK - {methodCount} method(s) checked, all sequence points decoded cleanly.");
    }
    else
    {
        Console.WriteLine($"  {badCount} of {methodCount} method(s) have corrupt sequence points.");
    }

    return badCount;
}

static string Describe(int row, Dictionary<int, string>? namesByRow) =>
    namesByRow is not null && namesByRow.TryGetValue(row, out var name) ? name : "(name unavailable - no matching .dll found)";

static Dictionary<int, string>? TryLoadNames(string dllPath)
{
    try
    {
        using var dllStream = File.OpenRead(dllPath);
        using var peReader = new PEReader(dllStream);
        var mdReader = peReader.GetMetadataReader();

        var result = new Dictionary<int, string>();
        foreach (var methodHandle in mdReader.MethodDefinitions)
        {
            var methodDef = mdReader.GetMethodDefinition(methodHandle);
            var typeDef = mdReader.GetTypeDefinition(methodDef.GetDeclaringType());
            var typeName = mdReader.GetString(typeDef.Name);
            var methodName = mdReader.GetString(methodDef.Name);
            var debugHandle = methodHandle.ToDebugInformationHandle();
            var row = MetadataTokens.GetRowNumber(debugHandle);
            result[row] = $"{typeName}::{methodName}";
        }
        return result;
    }
    catch
    {
        return null;
    }
}

Activity

  1. added theissue type on Aug 10, 2026
  2. added
    triage/untriaged
    on Aug 10, 2026
  3. jonpryor commented on Aug 11, 2026

    @jonpryor
    ContributorAuthor

    I've been chatting with Claude, which found the Cecil bug:

    Root cause: Mono.Cecil.PE.ByteBuffer.WriteCompressedInt32 (…/dotnet/cecil/Mono.Cecil.PE/ByteBuffer.cs) uses bias 0x20000000 for the 4-byte signed-compressed-integer encoding, but Cecil's own reader (ReadCompressedInt32, same file) uses 0x10000000 for that form — and 0x10000000 is what the ECMA-335/Portable-PDB spec actually requires (confirmed by hand-decoding Roslyn's own correct output byte-for-byte).…

    It provided a patch to Cecil:

    diff --git a/Mono.Cecil.PE/ByteBuffer.cs b/Mono.Cecil.PE/ByteBuffer.cs
    index 9a6567c..6d1fe76 100644
    --- a/Mono.Cecil.PE/ByteBuffer.cs
    +++ b/Mono.Cecil.PE/ByteBuffer.cs
    @@ -261,8 +261,8 @@ namespace Mono.Cecil.PE {
     				value = 0x40 + value;
     			else if (value >= -0x2000)
     				value = 0x2000 + value;
    -			else if (value >= -0x20000000)
    -				value = 0x20000000 + value;
    +			else if (value >= -0x10000000)
    +				value = 0x10000000 + value;
     
     			WriteCompressedUInt32 ((uint) ((value << 1) | 1));
     		}

    When I replace src/SourceGenerators/Uno.UI.Tasks/bin/Release/Mono.Cecil.dll in my build tree with a Mono.Cecil.dll containing the above patch and re-run the dotnet build from the original description, no problems are found in the .pdb files:

    % ~/bin/verify-pdb-sequence-points src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb.jporig__ src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb
    src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb.jporig__
      OK - 162669 method(s) checked, all sequence points decoded cleanly.
    src/SamplesApp/SamplesApp.Skia/obj/Release/net10.0/SamplesApp.Skia.pdb
      OK - 162669 method(s) checked, all sequence points decoded cleanly.

    I have Claude working on writing a unit test for dotnet/cecil.

  4. jonpryor commented on Aug 11, 2026

    @jonpryor
    ContributorAuthor

    Things got increasingly complicated…

    For starters, the dotnet/cecil fork of jbevain/cecil is huge: jbevain/cecil@master...dotnet:cecil:main

    A notable difference between them: jbevain/cecil#958

    Fix WriteCompressedInt32 logic by using the same code as in System.Reflection.Metadata

    Which is present in jbevain/cecil but not dotnet/cecil.

    Additionally, jbevain/cecil#958 is commit jbevain/cecil@608fac6, which is included in Mono.Cecil 0.11.6:

    git tag --contains 608fac6f22814e3eeb4609c80c0b5f08205e24ed
    0.11.6

    Which brings us to my current understanding: both Uno and dotnet/cecil require updates.

    1. Uno needs to use Mono.Cecil 0.11.6 to get the fix from Fix WriteCompressedInt32 logic by using the same code as in System.Reflection.Metadata jbevain/cecil#958.
    2. dotnet/cecil needs fixing, full stop.

    The above patch is not in fact sufficient.

    If I bring over the ByteBufferTests from jbevain/cecil#958, along with the previous patch to dotnet/cecil, the ByteBufferTests pass.

    However, if I add the new tests that Claude cooked up, the new tests pass on current jbevain/cecil but fail on dotnet/cecil:

    diff --git a/Test/Mono.Cecil.Tests/ByteBufferTests.cs b/Test/Mono.Cecil.Tests/ByteBufferTests.cs
    index 1ea9478..549f2aa 100644
    --- a/Test/Mono.Cecil.Tests/ByteBufferTests.cs
    +++ b/Test/Mono.Cecil.Tests/ByteBufferTests.cs
    @@ -12,5 +12,38 @@ namespace Mono.Cecil.Tests {
     			var result = testee.ReadCompressedInt32 ();
     			Assert.AreEqual (-9076, result);
     		}
    +
    +		// Round-trips WriteCompressedInt32/ReadCompressedInt32 across every encoding-width
    +		// boundary of the ECMA-335 compressed signed integer format (1/2/4-byte forms), plus
    +		// -8269, the exact delta between a Roslyn-emitted portable PDB sequence point's start
    +		// line and the preceding one that a Mono.Cecil fork (dotnet/cecil) failed to round-trip:
    +		// a fork of WriteCompressedInt32 used the wrong bias (0x20000000 instead of 0x10000000)
    +		// for the 4-byte form, corrupting any PDB rewritten by that fork - manifesting as
    +		// BadImageFormatException ("Invalid compressed integer" / "Sequence point value is out
    +		// of range") when the corrupted PDB was later read by System.Reflection.Metadata (e.g.
    +		// via illink or a NativeAOT compilation). This implementation is not affected, but the
    +		// case is kept here as a regression guard for the format's boundary values.
    +		[TestCase (0)]
    +		[TestCase (1)]
    +		[TestCase (-1)]
    +		[TestCase (63)]
    +		[TestCase (-64)]
    +		[TestCase (64)]
    +		[TestCase (-65)]
    +		[TestCase (8191)]
    +		[TestCase (-8192)]
    +		[TestCase (8192)]
    +		[TestCase (-8193)]
    +		[TestCase (-8269)]
    +		[TestCase (268435455)]
    +		[TestCase (-268435456)]
    +		public void CompressedInt32RoundTripsAcrossEncodingWidths (int value)
    +		{
    +			var testee = new ByteBuffer ();
    +			testee.WriteCompressedInt32 (value);
    +			testee.position = 0;
    +			var result = testee.ReadCompressedInt32 ();
    +			Assert.AreEqual (value, result);
    +		}
     	}
     }
  5. added a commit that references this issue on Aug 12, 2026
  6. added a commit that references this issue on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage/untriaged

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions