RyuJIT AccessViolationException when emitting line with bitwise operation
In the code sample below:
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Jit
{
class Program
{
static void Main()
{
var assemblyName = new AssemblyName("MyAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
var typeBuilder = moduleBuilder.DefineType("MyType");
var bitVector = typeBuilder.DefineField("bitVector", typeof(BitVector32), FieldAttributes.Private);
var method = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public, typeof(void), new[] { typeof(string), typeof(bool) });
method.DefineParameter(1, ParameterAttributes.None, "key");
method.DefineParameter(2, ParameterAttributes.None, "value");
var keys = new[] { "a", "b" };
var equality = typeof(string).GetMethod(
"op_Equality",
BindingFlags.Static | BindingFlags.Public,
null,
new[] { typeof(string), typeof(string) },
null);
var setItem = typeof(BitVector32).GetMethod(
"set_Item",
BindingFlags.Instance | BindingFlags.Public,
null,
new[] { typeof(int), typeof(bool) },
null);
var il = method.GetILGenerator();
il.DeclareLocal(typeof(string));
var labelDefault = il.DefineLabel();
var labels = keys.Select(_ => il.DefineLabel()).ToArray();
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Brfalse_S, labelDefault);
for (var i = 0; i < keys.Length; i++)
{
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldstr, keys[i]);
il.Emit(OpCodes.Call, equality);
il.Emit(OpCodes.Brtrue_S, labels[i]);
}
il.Emit(OpCodes.Br_S, labelDefault);
for (var i = 0; i < keys.Length; i++)
{
il.MarkLabel(labels[i]);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldflda, bitVector);
il.Emit(OpCodes.Ldc_I4, 1 << i);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, setItem);
il.Emit(OpCodes.Ret);
}
il.MarkLabel(labelDefault);
il.Emit(OpCodes.Ret);
typeBuilder.CreateType();
}
}
}
An AccessViolationException occurs on this line:
il.Emit(OpCodes.Ldc_I4, 1 << i)
The error occurs only when the code is optimized. The exception does not occur when doing one of the following:
- Building in debug/turning off optimizations
- Disabling RyuJIT in the registry
- Targeting x86 platform
- Changing the line to:
var x = 1 << i;
il.Emit(OpCodes.Ldc_I4, x);
Ouch, and good catch! :+1:
Simpler repro:
using System;
using System.Reflection.Emit;
class Program
{
static void Main()
{
Crash(new DynamicMethod("Foo", typeof(void), Type.EmptyTypes).GetILGenerator());
}
static void Crash(ILGenerator il)
{
Action x = () => il.DefineLabel();
for (int i = 0; i < 1; i++)
il.Emit(OpCodes.Ldc_I4, 1 << i);
}
}
Somehow a wrong value gets passed as this to Emit:
G_M55596_IG03:
488B4F08 mov rcx, gword ptr [rdi+8]
48BA281CF8467A000000 mov rdx, 0x7A46F81C28
488B12 mov rdx, gword ptr [rdx]
488B5208 mov rdx, qword ptr [rdx+8]
48894C2420 mov gword ptr [rsp+20H], rcx
8BCE mov ecx, esi
83E11F and ecx, 31
41B801000000 mov r8d, 1
41D3E0 shl r8d, cl
488B4C2420 mov rcx, gword ptr [rsp+20H] ; rcx = this = il
488B09 mov rcx, qword ptr [rcx] ; rcx = method table
488B4150 mov rax, qword ptr [rcx+80]
FF5008 call qword ptr [rax+8]System.Reflection.Emit.ILGenerator:Emit(struct,int):this
FFC6 inc esi
85F6 test esi, esi
7EC3 jle SHORT G_M55596_IG03
If desired the repro can be further simplified to not use System.Reflection.Emit as long as the following characteristics are preserved:
- A virtual
Emitlike method - The use of a shift operation
- A static field with an initializer. It can be of
inttype, it doesn't have to be a struct likeOpCode. - The lambda capture of
il. Such a simplified example may happen to run but it still generates bad code and asserts in debug builds of CoreCLR.
cc @CarolEidt
@mikedn: I can repro your example even without the lambda capture, or that entire line in fact. The loop seems to be the determining factor. Specifically i++ part.
for (int i = 456; true; i++)
il.Emit(OpCodes.Ldc_I4, 1 << i);
@leppie Indeed, if you change the loop condition like that the lambda capture isn't needed. And yes, the loop itself is needed, I wanted to mention that but I forgot. Thanks!
Thanks for reporting this - we'll have a look!
/cc @schellap
Assigning to Carol to take a look at the improper spill/reload. Adding notes from our discussion:
IN001e: 0000AB mov gword ptr [V07 rsp+28H], rcx ; putarg_reg's V07 spilled, NOT putarg_reg
IN001f: 0000B0 mov ecx, esi
IN0020: 0000B2 and ecx, 31
IN0021: 0000B5 mov r8d, 1
IN0022: 0000BB shl r8d, cl
IN0023: 0000BE mov rcx, gword ptr [V07 rsp+28H]
IN0024: 0000C3 mov rcx, qword ptr [rcx] ; control expr uses rcx
IN0025: 0000C6 mov rax, qword ptr [rcx+80] ; missing reload
IN0026: 0000CA call qword ptr [rax+8]System.Reflection.Emit.ILGenerator:Emit(struct,int):this
When will you release a fix for this? And what KB article number corresponds to this?
@riku76 - we have a 4.6 fix planned for release in the October hotfix rollup.
@leecow did this make it into October? If so, what was the KB#? It's not standing out to me on the list: http://blogs.msdn.com/b/winsdk/archive/2015/10/14/windows-hotfixes-for-october-2015.aspx
@CarolEidt @BruceForstall @jkotas Pinging again. These are critical bugs in the base framework - we have to have faith in the JIT and that's evaporating very quickly since all of the combined issues in .Net 4.6. We're hitting this issue at Stack Overflow randomly on builds and we're seeing reports of it from users of our various libraries. Can we please get some status information here?
@NickCraver This fix is included in .NET 4.6.1 RC. From .NET Framework 4.6.1 list of changes:
Fixed access violation caused by incorrect spill reload of putarg_reg(this) [134106]
.NET 4.6.1 RC has go-live license, so you can install it in production. It has fixes for all known RyuJIT compat issues. Please do let us know if you find any RyuJIT compat issues that are not fixed in .NET 4.6.1 RC.
More details about .NET 4.6.1 RC are in this blog post.
Had some conversations on this bug at Connect(); today - hoping we see a backport to 4.6 for all the users with crashing processes that can't upgrade for quite a while.
@NickCraver & @riku76 - A fix for this is included in the October Hotfix rollup for 4.6. Pre-Win10 KBs are 3095336 and 3095337. Unfortunately download links are not included on the KB pages so anyone needing the update will need to contact Product Support and reference the KB#. The Win10 update will be delivered automatically.