ECall methods must be packaged into a system module
After a long time, I’m writing a new technical post. Actually, I’m translating an older post I written in Romanian since the information about the exception is scarce. I stumbled upon the error while looking into the Assembly.Load method source code (/clr/src/bcl/system/reflection/Assembly.cs) which you can get through Rotor. I noticed that the method just calls another method, nLoad. In the same source file, nLoad is declared as:
private static extern Assembly nLoad(
ref StackCrawlMark stackMark,
I tried to call the same nLoad method by copying its declaration in my project but I quickly found out that it was harder than expected because StackCrawlMark, as it appears as a parameter, is actually declared as an alias:
using StackCrawlMark = System.Threading.StackCrawlMarl;
Where System.Threading.StackCrawlMark has an internal visibility so it can’t be used outside the assembly. Anyway, I was courious what
MSDN says it is a method implemented in the CLR itself. After a bit of research, I found out that all methods of this kind are implemented in the ecall.cpp file (/clr/src/vm/ecall.cpp), ecall probably standing for Engine Call. Although the Base Class Library is written in C#, the virtual machine is written in C++. The file contains quite a lot of methods which BCL calls using the above attribute.
Out of curiosity, I tried to call one of those methods myself – not nLoad because of the StackCrawlMark type, but I found something simpler: string GetFullName(). So I create the declaration
internal extern static string GetFullName();
Keep in mind, if you want to recreate the experiment, to also add using System.Runtime.CompilerServices; because that namespace contains the attribute MethodImpl.
The result of running the application was a System.Security.SecurityException: ECall methods must be packaged into a system module. This means all calls of the InternalCall kind can be made only from mscorlib.dll and such but no user created assembly.