Skip to content

ECall methods must be packaged into a system module

24 September 2008

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:

[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Assembly nLoad(
    AssemblyName fileName,
    String codeBase,
    Evidence assemblySecurity,
    Assembly locationHint,
    ref StackCrawlMark stackMark,
    bool throwOnFileNotFound,
    bool forIntrospection);

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

[MethodImplAttribute(MethodImplOptions.InternalCall)] meant.

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

[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static string GetFullName();

and call

Console.WriteLine(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.

From → code complete

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: