为什么'unbox.any'没有像'castclass'一样提供有用的异常文本?

26

为了说明我的问题,考虑以下简单的例子(C#):

object reference = new StringBuilder();
object box = 42;
object unset = null;

// CASE ONE: bad reference conversions (CIL instrcution 0x74 'castclass')
try
{
  string s = (string)reference;
}
catch (InvalidCastException ice)
{
  Console.WriteLine(ice.Message); // Unable to cast object of type 'System.Text.StringBuilder' to type 'System.String'.
}
try
{
  string s = (string)box;
}
catch (InvalidCastException ice)
{
  Console.WriteLine(ice.Message); // Unable to cast object of type 'System.Int32' to type 'System.String'.
}

// CASE TWO: bad unboxing conversions (CIL instrcution 0xA5 'unbox.any')
try
{
  long l = (long)reference;
}
catch (InvalidCastException ice)
{
  Console.WriteLine(ice.Message); // Specified cast is not valid.
}
try
{
  long l = (long)box;
}
catch (InvalidCastException ice)
{
  Console.WriteLine(ice.Message); // Specified cast is not valid.
}
try
{
  long l = (long)unset;
}
catch (NullReferenceException nre)
{
  Console.WriteLine(nre.Message); // Object reference not set to an instance of an object.
}
在尝试引用转换(对应于CIL指令castclass)的情况下,所抛出的异常包含以下格式的优秀消息:

无法将类型为'X'的对象转换为类型'Y'。

实证证据表明,此文本消息对于需要解决问题的(有经验或无经验的)开发人员(错误修复程序员)通常非常有帮助。 相比之下,当尝试取消装箱(unbox.any)失败时,我们得到的消息相当不具信息性。有什么技术原因必须如此吗?

指定的强制转换无效。[NOT HELPFUL]

换句话说,为什么我们不会收到像这样的消息(我的话):

无法将类型为'X'的对象取消装箱为类型为'Y'的值; 两种类型必须一致。

或者(我的话):

无法将null引用取消装箱为不可为空的类型'Y'的值。

那么重复一遍我的问题: 在一个情况下,错误消息好而且有信息,而在另一个情况下则很差? 或者是否存在技术上的原因使运行时无法提供第二种情况中遇到的实际类型的详细信息,或者代价昂贵? (我在这里看到了几个主题,如果取消装箱失败的异常文本更好,我肯定不会问。)
更新: Daniel Frederico Lins Leite的答案导致他在CLR Github上开放了一个问题(请参见下文)。 发现这是一个早期问题的重复(由Jon Skeet提出,人们几乎猜到了!)。 因此,在第二种情况下,差的异常消息没有充分的理由,而且人们已经在CLR中进行了修复。 因此,我并不是第一个想知道这个问题的人。 我们可以期待这项改进在.NET Framework中发布的那一天。

1
Jon已经在stackoverflow上问过这个问题了。大致原因是,在.NET 1.x时代,必须生成紧凑且快速的代码。如果你想要一个好的异常消息,那么你就需要编写Convert.ToInt64(reference)的代码。虽然仍然很紧凑,但不如之前快速。 - Hans Passant
1
@HansPassant 所以你引用的问题是关于为什么模式 var nullable = box as int?; if (nullable.HasValue) { /* use nullable.Value */ } 比模式 if (box is int) { var value = (int)box; /* use value */ } 慢得多。我知道后者示例中使用的 CIL 指令 unbox.any 将会很快,因为不涉及复制。而在 .NET 1 时代,简单值经常被装箱到非泛型集合中,因此必须快速。但是它如何回答我的问题呢?在类型检查失败的“分支”中,我们不能将更多详细信息放入异常中吗? - Jeppe Stig Nielsen
此外,castclass CIL 指令被期望非常快速,在那些集合没有强类型的 ArrayListHashtable 时代必须如此。castclass 不进行复制,只进行类型检查,引用指向同一位置。那么区别在哪里呢?当类型检查失败时,castclass 会导致一个“丰富”的异常,其中包含了异常消息中的源类型和目标类型。 - Jeppe Stig Nielsen
1个回答

6

简述:

我认为运行时拥有改进消息所需的所有信息。也许一些JIT开发人员可以提供帮助,因为不必说JIT代码非常敏感,有时会因为性能或安全原因做出决策,这对外部人员来说非常难以理解。

详细说明

为了简化问题,我将方法更改为:

C#

void StringBuilderCast()
{
    object sbuilder = new StringBuilder();
    string s = (string)sbuilder;
}

IL

.method private hidebysig 
    instance void StringBuilderCast() cil managed 
{
    // Method begins at RVA 0x214c
    // Code size 15 (0xf)
    .maxstack 1
    .locals init (
        [0] object sbuilder,
        [1] string s
    )

    IL_0000: nop
    IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()
    IL_0006: stloc.0
    IL_0007: ldloc.0
    IL_0008: castclass [mscorlib]System.String
    IL_000d: stloc.1
    IL_000e: ret
} // end of method Program::StringBuilderCast

这里重要的操作码是:

http://msdn.microsoft.com/library/system.reflection.emit.opcodes.newobj.aspx http://msdn.microsoft.com/library/system.reflection.emit.opcodes.castclass.aspx

而一般的内存布局是:

Thread Stack                        Heap
+---------------+          +---+---+----------+
| some variable |    +---->| L | T |   DATA   |
+---------------+    |     +---+---+----------+
|   sbuilder2   |----+
+---------------+

T = Instance Type  
L = Instance Lock  
Data = Instance Data

在这种情况下,运行时知道它拥有一个指向StringBuilder的指针,并且应该将其转换为字符串。在这种情况下,它具有提供最佳异常所需的所有信息。
如果我们看一下JIT https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/interpreter.cpp#L6137,我们会看到类似于这样的东西。
CORINFO_CLASS_HANDLE cls = GetTypeFromToken(m_ILCodePtr + 1, CORINFO_TOKENKIND_Casting  InterpTracingArg(RTK_CastClass));
Object * pObj = OpStackGet<Object*>(idx);
ObjIsInstanceOf(pObj, TypeHandle(cls), TRUE)) //ObjIsInstanceOf will throw if cast can't be done

如果我们深入研究这个方法

https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/eedbginterfaceimpl.cpp#L1633

而重要的部分是:

BOOL fCast = FALSE;
TypeHandle fromTypeHnd = obj->GetTypeHandle();
 if (fromTypeHnd.CanCastTo(toTypeHnd))
    {
        fCast = TRUE;
    }
if (Nullable::IsNullableForType(toTypeHnd, obj->GetMethodTable()))
    {
        // allow an object of type T to be cast to Nullable<T> (they have the same representation)
        fCast = TRUE;
    }
    // If type implements ICastable interface we give it a chance to tell us if it can be casted 
    // to a given type.
    else if (toTypeHnd.IsInterface() && fromTypeHnd.GetMethodTable()->IsICastable())
    {
    ...
    }
 if (!fCast && throwCastException) 
    {
        COMPlusThrowInvalidCastException(&obj, toTypeHnd);
    } 

这里重要的部分是抛出异常的方法。您可以看到,它接收当前对象和您尝试转换的类型。
最后,Throw方法调用此方法:

https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/excep.cpp#L13997

COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode());

这将为您提供带有类型名称的良好异常消息。

但是,当您将对象强制转换为值类型时

C#

void StringBuilderToLong()
{
    object sbuilder = new StringBuilder();
    long s = (long)sbuilder;
}

IL

.method private hidebysig 
    instance void StringBuilderToLong () cil managed 
{
    // Method begins at RVA 0x2168
    // Code size 15 (0xf)
    .maxstack 1
    .locals init (
        [0] object sbuilder,
        [1] int64 s
    )

    IL_0000: nop
    IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()
    IL_0006: stloc.0
    IL_0007: ldloc.0
    IL_0008: unbox.any [mscorlib]System.Int64
    IL_000d: stloc.1
    IL_000e: ret
}

这里的重要操作码是:
http://msdn.microsoft.com/library/system.reflection.emit.opcodes.unbox_any.aspx 我们可以在这里看到UnboxAny的行为: https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/vm/interpreter.cpp#L8766
//GET THE BOXED VALUE FROM THE STACK
Object* obj = OpStackGet<Object*>(tos);

//GET THE TARGET TYPE METADATA
unsigned boxTypeTok = getU4LittleEndian(m_ILCodePtr + 1);
boxTypeClsHnd = boxTypeResolvedTok.hClass;
boxTypeAttribs = m_interpCeeInfo.getClassAttribs(boxTypeClsHnd);

//IF THE TARGET TYPE IS A REFERENCE TYPE
//NOTHING CHANGE FROM ABOVE
if ((boxTypeAttribs & CORINFO_FLG_VALUECLASS) == 0)
{
    !ObjIsInstanceOf(obj, TypeHandle(boxTypeClsHnd), TRUE)
}
//ELSE THE TARGET TYPE IS A REFERENCE TYPE
else
{
    unboxHelper = m_interpCeeInfo.getUnBoxHelper(boxTypeClsHnd);
    switch (unboxHelper)
        {
        case CORINFO_HELP_UNBOX:
                MethodTable* pMT1 = (MethodTable*)boxTypeClsHnd;
                MethodTable* pMT2 = obj->GetMethodTable();

                if (pMT1->IsEquivalentTo(pMT2))
                {
                    res = OpStackGet<Object*>(tos)->UnBox();
                }
                else
                {
                    CorElementType type1 = pMT1->GetInternalCorElementType();
                    CorElementType type2 = pMT2->GetInternalCorElementType();

                    // we allow enums and their primtive type to be interchangable
                    if (type1 == type2)
                    {
                          res = OpStackGet<Object*>(tos)->UnBox();
                    }
                }

        //THE RUNTIME DOES NOT KNOW HOW TO UNBOX THIS ITEM
                if (res == NULL)
                {
                    COMPlusThrow(kInvalidCastException);

                    //I INSERTED THIS COMMENTS
            //auto thCastFrom = obj->GetTypeHandle();
            //auto thCastTo = TypeHandle(boxTypeClsHnd);
            //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);
                }
                break;
        case CORINFO_HELP_UNBOX_NULLABLE:
                InterpreterType it = InterpreterType(&m_interpCeeInfo, boxTypeClsHnd);
                size_t sz = it.Size(&m_interpCeeInfo);
                if (sz > sizeof(INT64))
                {
                    void* destPtr = LargeStructOperandStackPush(sz);
                    if (!Nullable::UnBox(destPtr, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd))
                    {
                        COMPlusThrow(kInvalidCastException);
                    //I INSERTED THIS COMMENTS
            //auto thCastFrom = obj->GetTypeHandle();
            //auto thCastTo = TypeHandle(boxTypeClsHnd);
            //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);
                    }
                }
                else
                {
                    INT64 dest = 0;
                    if (!Nullable::UnBox(&dest, ObjectToOBJECTREF(obj), (MethodTable*)boxTypeClsHnd))
                    {
                        COMPlusThrow(kInvalidCastException);
                    //I INSERTED THIS COMMENTS
            //auto thCastFrom = obj->GetTypeHandle();
            //auto thCastTo = TypeHandle(boxTypeClsHnd);
            //RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);
                    }
                }
            }
            break;
        }
}

好吧...至少,似乎有可能给出更好的异常消息。 如果你还记得当异常有一个好消息时的调用:

COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode());

而且信息较少的消息是:

COMPlusThrow(kInvalidCastException);

所以我认为可以通过改进来提高消息。
auto thCastFrom = obj->GetTypeHandle();
auto thCastTo = TypeHandle(boxTypeClsHnd);
RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);

我已在coreclr的github上创建了以下问题,以了解微软开发人员的意见。

https://github.com/dotnet/coreclr/issues/7655


感谢您的分析。如果您在Github上创建了一个问题,那就太好了,然后您可以链接到这个Stack Overflow线程,我也可以从这里链接到Github。 - Jeppe Stig Nielsen
1
我已经创建了这个问题并在此处插入了链接。感谢您的建议。 - Daniel Frederico Lins Leite
1
你的 Github 问题收到了一条有趣的评论。我已经在我的问题文本中添加了更新。 - Jeppe Stig Nielsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接