Dear friends, today I want to share with you an important error that you should always take care about: System.BadImageFormatException. Please, please please take care of this exception, especially on scenarios where you think that it is not part of the problem Sorriso. As usual, a very short background that can give you an idea of how important this exception is:

An ASP.NET application of my customer sometimes raises an exception of the following type System.NullReferenceException during its start-up. To be very very short, after hours and hours of debug, we found out that customer’s applications does not work properly (raising System.NullReferenceException) since during initial steps a System.BadImageFormatException occurs.

To figure out this was very complex: IIS by default handles the exception avoiding that w3wp.exe process crashes. Furthermore the System.NullReferenceException does not have any apparent relation with previous exception.

 

The question was: Why do we get a System.BadImageFormatException: Bad IL Range? According to our documentation, this exception comes out for the following scenarios:

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.

And Bad IL Range means that a section of IL code inside a specific dll is not valid.

How is it possible? Is there a bug on C# compiler or VB.NET one? Of course no! To avoid a file/dll corruption, I asked customer to generate the DLLs one more time but issue was always there. Typically this step is enough to solve this kind of trouble.

Problem was always there since customer’s compilation process includes a 3rd step. Typically we have two steps: .NET Language >> MS Intermediate Language >> native code. My customer does something more: .NET Language >> MS Intermediate Language >> Obfuscator >> native code.

Basically the managed dll (generated by C# compiler) was edited/recompiled by obfuscator application.

I do not want to mention here what obfuscator my customer was using. It is not relevant. The point was that this obfuscator generates an invalid IL so at runtime we got that exception System.BadImageFormatException.

Unfortunately application does not crash due to reason mentioned above so later on its execution time we got unpredictable behavior that generates a different exception System.NullReferenceException.

If you have this kind of issue, try to isolate the trouble reducing the external factors: in this case the obfuscator software.

Enjoy your .NET coding.Occhiolino

Carmelo