27

I need to find the assembly in which managed code execution started.

// using System.Reflection;
Assembly entryAssembly = Assembly.GetEntryAssembly();

This seems like the way to go, but the MSDN reference page for Assembly.GetEntryAssembly states that this method "[c]an return null when called from unmanaged code."

In that case, I would like to know which assembly was called by unmanaged code.

Is there a reliable way of doing this, i.e. one that always returns a non-null Assembly reference?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268

3 Answers3

23

The best I could think of so far is the following, which should work in a single-threaded scenario:

// using System.Diagnostics;
// using System.Linq; 
Assembly entryAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;

(The above snippet is optimized for ease of understanding, not for execution speed or memory efficiency.)

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
12

I tried both methods of stakx.

Method based on MainModule does not work in some special cases (dynamic assemblies for example).

Method based on StackTrace can return an assembly too high (or low) in the hierarchy, like mscorlib.

I made a little variant which works well in my use cases :

// using System.Diagnostics;
// using System.Linq;
var methodFrames = new StackTrace().GetFrames().Select(t => t?.GetMethod()).ToArray();
MethodBase entryMethod = null;
int firstInvokeMethod = 0;
for (int i = 0; i < methodFrames.Length; i++)
{
    var method = methodFrames[i] as MethodInfo;
    if (method == null)
        continue;
    if (method.IsStatic &&
        method.Name == "Main" &&
        (
            method.ReturnType == typeof(void) || 
            method.ReturnType == typeof(int) ||
            method.ReturnType == typeof(Task) ||
            method.ReturnType == typeof(Task<int>)
        ))
    {
        entryMethod = method;
    }
    else if (firstInvokeMethod == 0 &&
        method.IsStatic &&
        method.Name == "InvokeMethod" &&
        method.DeclaringType == typeof(RuntimeMethodHandle))
    {
        firstInvokeMethod = i;
    }
}

if (entryMethod == null)
    entryMethod = firstInvokeMethod != 0 ? methodFrames[firstInvokeMethod - 1] : methodFrames.LastOrDefault();

Assembly entryAssembly = entryMethod?.Module?.Assembly;

Basically, I walk the stack up until I find a conventional method named "Main" with void or int return type. If no such method is found, I look for a method invoked via reflection. For example, NUnit uses that invocation to load unit tests.

Of course, I do that only if Assembly.GetEntryAssembly() returns null.

Eric Boumendil
  • 2,318
  • 1
  • 27
  • 32
  • Main might return an `int` and there may be other Main methods in other classes, but a good start. – Rob Prouse Nov 28 '18 at 02:11
  • Correct, I updated my answer to reflect your suggestion for the return type (void, int, Task, Task). As for an homonym "Main" method, I suppose that it is a rare case, and the code above is only a best effort, not a guarantee. Also, I take into account not only the name of the method but the stacktrace. So an other method "Main" declared in a library is not sufficient to deceive that snippet. – Eric Boumendil Nov 29 '18 at 08:27
4

Another (largely untested) starting point for a working solution might be something like this:

// using System;
// using System.Diagnostics;
// using System.Linq;
ProcessModule mainModule = Process.GetCurrentProcess().MainModule;
Assembly entryAssembly = AppDomain.CurrentDomain.GetAssemblies()
                         .Single(assembly => assembly.Location == mainModule.FileName);

Some uncertainties remain:

  • Modules and assemblies are not the same thing. ProcessModule might even be conceptually different from Module. Would the above code always work in the presence of multi-module (i.e. multi-file) assemblies, especially when an assembly's entry point is not in the manifest module?

  • Is Process.MainModule guaranteed to always returns a non-null reference?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268