Skip to content

Fix fast patching potentially corrupting EH catch type in memory #747

Merged
Washi1337 merged 2 commits into
Washi1337:developmentfrom
wondercrash:development
May 28, 2026
Merged

Fix fast patching potentially corrupting EH catch type in memory #747
Washi1337 merged 2 commits into
Washi1337:developmentfrom
wondercrash:development

Conversation

@wondercrash
Copy link
Copy Markdown
Contributor

@wondercrash wondercrash commented May 20, 2026

When fast patching method bodies, the EH catch type token is rewritten directly into the original raw body's section data

var raw = (CilRawFatMethodBody) sourceBody.OriginalRawBody;
foreach (var section in raw.ExtraSections)
{
byte[] sectionData = section.Data;
if (section.IsEHTable)
{
try
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
FastCilReassembler.PatchExceptionHandlerSection(sectionData, tokenRewriter, section.IsFat);
#else

Since sectionData is ultimately owned by the sourceBody.OriginalRawBody, patching the catch type token in place mutates the original body itself in memory. So for example if you write a module twice, the first module will be fine while the second module may have the wrong token for the catch type.

repro case:

void test()
{
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        return;
    }
}

var module = ModuleDefinition.FromModule(typeof(Program).Module);
module.Write(new MemoryStream());

var method = module.TopLevelTypes.SelectMany(t => t.Methods).First(m => m.Name.Contains("test"));

// should print System.Exception, but it doesn't
Console.WriteLine(method.CilMethodBody!.ExceptionHandlers[0].ExceptionType); 

To fix it, I just Clone the sectionData before patching it.

@wondercrash wondercrash changed the base branch from master to development May 20, 2026 16:22
@Washi1337 Washi1337 added bug dotnet Issues related to AsmResolver.DotNet labels May 21, 2026
@Washi1337
Copy link
Copy Markdown
Owner

Thanks for the catch and the fix. Could you add your repro as a unit test?

@Washi1337 Washi1337 added this to the 6.1.0 milestone May 25, 2026
@Washi1337 Washi1337 merged commit 182cb25 into Washi1337:development May 28, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug dotnet Issues related to AsmResolver.DotNet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants