The coolest exception I've ever get : FatalExecutionError

I get the coolest exception from .Net FatalExecutionError. What is cool for that exception is that it is assuming that itself might be wrong. “This error may be a bug in the CLR.” So I might not be the one who generated, I can just blame CLR for doing that :)

FatalExecutionError

“The runtime has encountered a fatal error. The address of the error was at 0x79eebbc1, on thread 0x141c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.”

Luckily this is not a bug in the CLR. It was my fault. In this sample project, I try to generate a reflected dynamic IL function (I call it like that) to lower the execution time for the reflection. The sample works perfect with value types and reference types, however I have a problem with generic value types. Some boxing and unboxing operation might be faulty in this snippet. What is really causing that error is because I generate IL code dynamically and IL code is the compiled code, the runtime executes the statements of IL, and it gets an internal exception. Normally such a code wouldn’t compile that way so it will continue to operate normally. As a result it suspects from itself.

I will share more on dynamic execution in a later post when I get finished the code and solved my bug.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class DynamicReflectionHelper
{
    public delegate object GetPropertyFieldDelegate(object obj);
    public static GetPropertyFieldDelegate GetP(object o,string memberName)
    {
        Type v = o.GetType();
        PropertyInfo pi = v.GetProperty(memberName);
        FieldInfo fi = v.GetField(memberName);

        if (pi != null || fi != null)
        {   
            DynamicMethod dm = new DynamicMethod( "GetPropertyorField_" + memberName, typeof(object), new Type[] { typeof(object) }, v.Module);
            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);

            if (pi.PropertyType.IsValueType)
                il.Emit(OpCodes.Box, pi.PropertyType);
            if (pi.PropertyType.IsGenericType)
                il.Emit(OpCodes.Nop);

            if (pi != null)
                il.EmitCall(OpCodes.Callvirt,  pi.GetGetMethod(), null);
            else if (fi != null)
                il.Emit(OpCodes.Ldfld, fi);

            il.Emit(OpCodes.Ret);
            return (GetPropertyFieldDelegate) dm.CreateDelegate( typeof(GetPropertyFieldDelegate));
        }
        else
            throw new NullReferenceException("No property or Field");
    }
}