Repository navigation
Description
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:
uno/src/SourceGenerators/Uno.UI.Tasks/EmbeddedResourceInjector/EmbeddedResourceInjectorTask.cs
Lines 26 to 141 in afe93db
| 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.csprojOnce 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
jonpryor commentedon Aug 11, 2026
I've been chatting with Claude, which found the Cecil bug:
It provided a patch to Cecil:
When I replace
src/SourceGenerators/Uno.UI.Tasks/bin/Release/Mono.Cecil.dllin my build tree with aMono.Cecil.dllcontaining the above patch and re-run thedotnet buildfrom the original description, no problems are found in the.pdbfiles:% ~/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.
jonpryor commentedon Aug 11, 2026
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
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:
Which brings us to my current understanding: both Uno and dotnet/cecil require updates.
The above patch is not in fact sufficient.
If I bring over the
ByteBufferTestsfrom jbevain/cecil#958, along with the previous patch to dotnet/cecil, theByteBufferTestspass.However, if I add the new tests that Claude cooked up, the new tests pass on current jbevain/cecil but fail on dotnet/cecil:
Add additional ByteBufferTest tests
Add additional ByteBufferTest tests
Add additional ByteBufferTest tests (#504)
chore: use Mono.Cecil 0.11.6
chore: use Mono.Cecil 0.11.6
chore: use Mono.Cecil 0.11.6