Jep*_*sen 23 .net c# clr unboxing cil
为了说明我的问题,请考虑这些简单的例子(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.
}
Run Code Online (Sandbox Code Playgroud)
因此,在我们尝试引用转换(对应于CIL指令castclass)的情况下,抛出的异常包含以下形式的优秀消息:
无法将"X"类型的对象强制转换为"Y".
经验证据表明,对于需要处理问题的(有经验或缺乏经验的)开发人员(错误修复程序),此文本消息通常非常有用.
相反,我们在尝试取消装箱(unbox.any)失败时得到的消息是非信息性的.技术上有什么原因必须这样吗?
指定演员表无效.[没有帮助]
换句话说,为什么我们没有收到像(我的话)这样的信息:
无法将类型为"X"的对象拆分为"Y"类型的值; 这两种类型必须达成一致.
分别(我的话):
无法将空引用拆分为非可空类型"Y"的值.
所以重复一下我的问题:在一个案例中,错误信息是好的和信息性的,而在另一种情况下是差的,这是"偶然的"吗?或者是否存在技术上的原因导致运行时提供第二种情况中遇到的实际类型的详细信息是不可能的,或者说是非常困难的?
(我在SO上看到了几个线程,我确信永远不会被问到失败的取消装置的异常文本是否更好.)
更新:Daniel Frederico Lins Leite的回答导致他在CLR Github上开启了一个问题(见下文).这被发现是早期问题的重复(由Jon Skeet提出,人们几乎猜到了它!).所以没有充分的理由可以解决这个糟糕的异常消息,人们已经在CLR中修复了它.所以我不是第一个对此感到疑惑的人.我们可以期待这一改进在.NET Framework中出现的那一天.
TL; DR;
我认为运行时具有改进消息所需的所有信息.也许一些JIT开发人员可以提供帮助,因为不用说JIT代码是非常敏感的,有时候由于性能或安全原因而做出决定,这对外人来说很难理解.
详细说明
为了简化问题,我将方法更改为:
C#
void StringBuilderCast()
{
object sbuilder = new StringBuilder();
string s = (string)sbuilder;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这里重要的操作码是:
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
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下,运行时知道它有一个指向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
Run Code Online (Sandbox Code Playgroud)
如果我们深入研究这种方法
而重要的部分是:
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);
}
Run Code Online (Sandbox Code Playgroud)
这里的重要部分是抛出异常的方法.如您所见,它接收当前对象和您尝试强制转换的类型.
最后,Throw方法调用此方法:
COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode());
Run Code Online (Sandbox Code Playgroud)
Wich为您提供了带有类型名称的漂亮异常消息.
但是当您将对象转换为值类型时
C#
void StringBuilderToLong()
{
object sbuilder = new StringBuilder();
long s = (long)sbuilder;
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
这里重要的操作码是: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;
}
}
Run Code Online (Sandbox Code Playgroud)
好吧......至少,似乎可以提供更好的异常消息.如果你还记得异常有一个很好的消息,那么调用是:
COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strCastFromName.GetUnicode(), strCastToName.GetUnicode());
Run Code Online (Sandbox Code Playgroud)
这是一个不那么有趣的信息:
COMPlusThrow(kInvalidCastException);
Run Code Online (Sandbox Code Playgroud)
所以我认为可以改进消息
auto thCastFrom = obj->GetTypeHandle();
auto thCastTo = TypeHandle(boxTypeClsHnd);
RealCOMPlusThrowInvalidCastException(thCastFrom, thCastTo);
Run Code Online (Sandbox Code Playgroud)
我在coreclr github上创建了以下问题,以了解Microsoft开发人员的意见.
https://github.com/dotnet/coreclr/issues/7655
| 归档时间: |
|
| 查看次数: |
691 次 |
| 最近记录: |