AsmResolver: Bad IL format on MacOS

AsmResolver Version

5.5.1 and 6.0.0-beta.3

.NET Version

.Net 8.0

Operating System

MacOS

Describe the Bug

I am attempting to add an assembly weaver in BenchmarkDotNet (I tried Mono.Cecil and dnlib, but they both had issues in Visual Studio that AsmResolver does not). https://github.com/dotnet/BenchmarkDotNet/pull/2336

I created an MsBuild task to run the assembly weaver during the dotnet build process.

How To Reproduce

.targets file

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="BenchmarkDotNet.Weaver.WeaveAssemblyTask" AssemblyFile="$(MSBuildThisFileDirectory)..\..\tasks\netstandard2.0\BenchmarkDotNet.Weaver.dll" />

  <Target Name="WeaveAssemblies" AfterTargets="AfterBuild" >
    <WeaveAssemblyTask TargetDir="$(TargetDir)" TargetAssembly="$(TargetDir)$(TargetFileName)" />
  </Target>
</Project>

MsBuild Task code

using AsmResolver.DotNet;
using AsmResolver.PE.DotNet.Metadata.Tables;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.IO;
using System.Linq;

namespace BenchmarkDotNet.Weaver;

/// <summary>
/// The Task used by MSBuild to weave the assembly.
/// </summary>
public sealed class WeaveAssemblyTask : Task
{
    /// <summary>
    /// The directory of the output.
    /// </summary>
    [Required]
    public string TargetDir { get; set; }

    /// <summary>
    /// The path of the target assembly.
    /// </summary>
    [Required]
    public string TargetAssembly { get; set; }

    /// <summary>
    /// Runs the weave assembly task.
    /// </summary>
    /// <returns><see langword="true"/> if successful; <see langword="false"/> otherwise.</returns>
    public override bool Execute()
    {
        if (!File.Exists(TargetAssembly))
        {
            Log.LogError($"Assembly not found: {TargetAssembly}");
            return false;
        }

        // Load the assembly using AsmResolver.
        var module = ModuleDefinition.FromFile(TargetAssembly);

        bool benchmarkMethodsImplAdjusted = false;
        try
        {
            foreach (var type in module.GetAllTypes())
            {
                // We can skip non-public types as they are not valid for benchmarks.
                if (type.IsNotPublic)
                {
                    continue;
                }

                foreach (var method in type.Methods)
                {
                    if (method.CustomAttributes.Any(IsBenchmarkAttribute))
                    {
                        var oldImpl = method.ImplAttributes;
                        // Remove AggressiveInlining and add NoInlining.
                        method.ImplAttributes = (oldImpl & ~MethodImplAttributes.AggressiveInlining) | MethodImplAttributes.NoInlining;
                        benchmarkMethodsImplAdjusted |= (oldImpl & MethodImplAttributes.NoInlining) == 0;
                    }
                }
            }

            // Write the modified assembly to file.
            module.Write(TargetAssembly);
        }
        catch (Exception e)
        {
            if (benchmarkMethodsImplAdjusted)
            {
                Log.LogWarning($"Benchmark methods were found that require NoInlining, and assembly weaving failed.{Environment.NewLine}{e}");
            }
        }
        return true;
    }

    private static bool IsBenchmarkAttribute(CustomAttribute attribute)
    {
        // BenchmarkAttribute is unsealed, so we need to walk its hierarchy.
        for (var attr = attribute.Constructor.DeclaringType; attr != null; attr = attr.Resolve()?.BaseType)
        {
            if (attr.FullName == "BenchmarkDotNet.Attributes.BenchmarkAttribute")
            {
                return true;
            }
        }
        return false;
    }
}

Expected Behavior

Works without errors.

Actual Behavior

System.BadImageFormatException: Bad IL format. The format of the file '(filepath)' is invalid.

https://github.com/dotnet/BenchmarkDotNet/actions/runs/15482646123/job/43591177885?pr=2336

Additional Context

I tried both the latest stable and latest beta versions (5.5.1 and 6.0.0-beta.3) and observe the same behavior on both. It works flawlessly on Windows and Linux, but fails on MacOS.

BenchmarkDotNet v0.15.1-ci, macOS Sequoia 15.5 (24F74) [Darwin 24.5.0]
 Apple M1 (Virtual), 1 CPU, 3 logical and 3 physical cores
 .NET SDK 8.0.401
   [Host] : .NET 8.0.8 (8.0.824.36612), Arm64 RyuJIT AdvSIMD

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 19 (9 by maintainers)

Most upvoted comments

@timcassell glad this fixes the problem. We have a few more breaking changes in the pipeline, but we can maybe get another beta release on the official nuget relatively soon.

Even if the assembly contains native code, if we’re not modifying it or adding new native code, could it just write back what was originally there without processing it? Hypothetically then the platform wouldn’t matter at all.

This is what UnmanagedPEFileBuilder attempts to do as much as possible 😃 (see also docs)

Sadly, this is not always possible, as modifying one part in a PE may require other parts to be rearranged as well (especially when the size of that part increased and thus doesn’t fit anymore in its original place).

Note, also, that regardless of the addition of a generic platform, mixed mode apps are not fully supported in AsmResolver.DotNet yet. Only PEImages from AsmResolver.PE currently feature a full-fletched unmanaged/mixed mode builder. Doing the same from ModuleDefinition is a non-trivial task, which we plan to support in the future but will likely not be present in in the first release of v6.0.0.

Initial ARM64 support is implemented in #643. Statically, output binaries look fine, but have no way yet to dynamically verify this yet. I may look into setting up qemu-system-aarch64 later next week, as well as enabling arm64 ci pipelines.