Weird runtime errors and the just in time compiler
There is an old compiler writer’s motto that says: Making a wrong program worse is no sin. There is another motto that says: A bug free program doesn’t exist.
Well it seems the Microsoft .NET runtime JIT team has combined the two motto’s allowing perfectly good code to go wrong :-( And I have recently been bitten multiple times by this.
So what happens? Well I have code that runs perfectly well from within Visual Studio 2005, both debug and release build that is. Now I run the release build as a standalone application on the same machine and it starts failing in strange ways. The sort of error you might get is invalid casts, I had one that claimed it couldn’t cast to System.__Canon. Now I have no idea what System.__Canon is used for but I am very sure I don’t use it in my code as it is an internal class in mscorelib.
So how do I work around these issues?
Well so far the only way I have found is to disable the JIT inlining for specific functions, usually a little higher up in the call stack, normally found by trial and error. Use the MethodImpl(MethodImplOptions.NoInlining) attribute on the function to disable the JIT.
So where does this leave me? Well with a certain distrust of the .NET runtime. Clearly I can’t trust the results after testing either in Visual Studio itself or a debug build. Now I am a fan of creating unit tests but being forced to run these outside the normal development environment and only on release builds is a major PITA. Not only does this waste a lot of time the very fact that it is needed makes me a little wary of releasing code to customers. After all I never know if some obscure JIT bug like this is going to be machine dependent and only bite me on the customer’s machine.