You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生成动态方法时遇Common Language Runtime无效程序错误

MIPS JIT编译器移位指令触发CLR无效程序异常问题

我正在开发一款用于MIPS机器模拟的JIT编译器,负责将MIPS指令转换为CLI指令。在实现硬编码风格的Shift方法时,执行从内存加载值的移位操作指令会触发「Common Language Runtime detected an invalid program」异常。

触发异常的代码如下:

private unsafe bool Shift(ILGenerator il, MipsInstruction inst, OpCode ilOpCode)
{
    long baseAddress = (long)_cpu.RegisterFile.Regs;
    long regAddress = baseAddress + ((int)inst.RT * sizeof(T));

    // Push Address
    if (IntPtr.Size == 4) il.Emit(OpCodes.Ldc_I4, (int)regAddress);
    else il.Emit(OpCodes.Ldc_I8, regAddress);
    il.Emit(OpCodes.Conv_I);

    // Load the value from memory
    il.Emit(OpCodes.Ldind_U4);

    // Load shift amount
    il.Emit(OpCodes.Ldc_I4, inst.ShiftAmount);

    // Apply shift
    il.Emit(ilOpCode);

    // Pop value (not even trying to store yet)
    il.Emit(OpCodes.Pop);

    return false;
}

其中,_cpu.RegisterFile.Regs是T*类型,T会根据MIPS版本(32/64位)对应uint或ulong,测试时使用的是MIPS32R2,对应uint。

另外,以下两个方法不会触发异常:

private unsafe bool Shift(ILGenerator il, MipsInstruction inst, OpCode ilOpCode)
{
    il.Emit(OpCodes.Ldc_I4, inst.ShiftAmount);
    il.Emit(OpCodes.Ldc_I4, inst.ShiftAmount);
    il.Emit(ilOpCode);
    il.Emit(OpCodes.Pop);

    return false;
}
private unsafe bool Shift(ILGenerator il, MipsInstruction inst, OpCode ilOpCode)
{
    long baseAddress = (long)_cpu.RegisterFile.Regs;
    long regAddress = baseAddress + ((int)inst.RT * sizeof(T));

    // Push Address
    if (IntPtr.Size == 4) il.Emit(OpCodes.Ldc_I4, (int)regAddress);
    else il.Emit(OpCodes.Ldc_I8, regAddress);
    il.Emit(OpCodes.Conv_I);

    // Load the value from memory
    il.Emit(OpCodes.Ldind_U4);
    il.Emit(OpCodes.Pop);

    return false;
}

内容的提问来源于stack exchange,提问作者Avishai Dernis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 14:44:52