Lokad / ILPack

Serialize .NET Core assemblies

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Undecompilable static constructor involving string field

Twinside opened this issue · comments

The following program:

using System;
using System.Reflection;
using System.Reflection.Emit;
using Lokad.ILPack;

namespace ilpack_repro
{
    sealed class Program
    {
        static void Main(string[] args)
        {
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
                new AssemblyName { Name = "Jot" },
                AssemblyBuilderAccess.Run);

            var moduleBuilder = assemblyBuilder.DefineDynamicModule("JotModule");

            var myType = moduleBuilder.DefineType(
                "Test.Type",
                TypeAttributes.Public | TypeAttributes.BeforeFieldInit,
                typeof(object),
                Array.Empty<Type>());

            var originalNameField = myType.DefineField(
                fieldName: "StringField",
                type: typeof(string),
                attributes: FieldAttributes.Public
                            | FieldAttributes.Static
                            | FieldAttributes.InitOnly);

            var ctorBuilder = myType.DefineConstructor(
                attributes: MethodAttributes.Public | MethodAttributes.Static,
                callingConvention: CallingConventions.Standard,
                parameterTypes: Array.Empty<Type>());

            var il = ctorBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldstr, "foobar");
            il.Emit(OpCodes.Stfld, originalNameField);
            il.Emit(OpCodes.Ret);


            var finalType = myType.CreateType();

            new AssemblyGenerator().GenerateAssembly(moduleBuilder.Assembly, "C:\\LokadData\\test.dll");
        }
    }
}

generates an assembly where various disassembler (dotnetpeek & ilspy) choke on, there is likely something weird behind it.