Detect Mono running in AOT mode

· March 18, 2015

So, for MoonSharp (which is evolving a lot more than it was suggested by posts on this blog – heck I should write MORE), I needed to know if my library was running in FullAOT or not.

For those not knowing, AOT means “ahead of time”. Under a FullAOT execution, JITting is disabled and code is compiled “ahead of time”; this means all those scenarios which involve creating code on the fly at runtime will not work. This can be used for some optimizing scenario or for embedded systems and such, but the real use case is iOS, as apps on iOS cannot (due to licensing) create code at runtime – weird Apple rules.

Now, while an app usually knows whether it’s running on AOT or not, a class library might not now beforehand and yet that information might be useful.

For example MoonSharp userdata do a lot of reflection and back-and-forth calls between script and native code. As an optimization, it uses LambdaExpression.Compile calls to create wrappers at runtime and have performances which are orders of magnitude faster than reflection. However those calls break with an ExecutionEngineException on Mono FullAOT.

Now, here we have a little weird Mono thing which comes to help us.. don’t know if it’s a bug or intentional.

As per MSDN documentation, managed code cannot catch an ExecutionEngineException. Turns out that Mono behaves differently – at the very least regarding those EEEs which are thrown due to a JIT request in FullAOT.

Then the detection code gets simple enough:

private static void AttemptJit()
 Expression e = Expression.Constant(5, typeof(int));
 var lambda = Expression.Lambda<Func<int>>(e);

private static bool IsRunningOnAOT()
 return false;
 catch (ExecutionEngineException)
 return true;

Hope this fact that EEE can be caught is not a Mono bug (or at least, it doesn’t get fixed ;) ).

Filed under: Uncategorized