Skip to content

System.BadImageFormatException when execute the local generic method #44720

@ww898

Description

@ww898

The application was already running, however I got System.BadImageFormatException during execute local method with generic argument. Crashed on:

  • .NET Core 3.1.300 x64
  • .NET Framework 4.8.03752 x64

The example to reproduce the issue CompilerBug.zip:

using System;
using System.Collections.Generic;
using System.Linq;

namespace CompilerBug
{
    internal static class Program
    {
        // Inline the method in `main()` fix the issue
        private static List<object> Create(DataConfig dataConfig, string name)
        {
            var tasks = new List<object>();
            foreach (var fieldInfo in typeof(DataConfig).GetFields())
            {
                // Move the method out of `foreach` fix the issue
                IReadOnlyCollection<TResult> Filter<TResult>(IEnumerable<KeyValuePair<string, TResult>> value)
                    where TResult : BaseConfig
                {
                    return value.Where(y => y.Key == name).Select(y => y.Value).ToList();
                }

                object CreateObject()
                {
                    if (fieldInfo.GetValue(dataConfig) is KeyValuePair<string, Config>[] value)
                        return new ConfigObject(Filter(value));
                    throw new NotSupportedException();
                }

                tasks.Add(CreateObject());
            }

            return tasks;
        }

        private static void Main()
        {
            const string key = "key";
            GC.KeepAlive(Create(new DataConfig {Config = new[] {new KeyValuePair<string, Config>(key, new Config())}}, key));
        }

        private abstract class BaseConfig
        {
        }

        private sealed class Config : BaseConfig
        {
        }

        private sealed class DataConfig
        {
            public KeyValuePair<string, Config>[] Config;
        }

        private sealed class ConfigObject
        {
            public ConfigObject(IReadOnlyCollection<Config> filter)
            {
            }
        }
    }
}

RoslynBug

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersBughelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions