在阅读Win64结构化异常跟踪时(参见针对x64异常处理支持的编程,第7部分:将它们放在一起,或构建堆栈遍行例程),我转换了代码StackWalk64.cpp。
procedure DumpExceptionStack();
var
LContext : CONTEXT;
LUnwindHistoryTable : _UNWIND_HISTORY_TABLE;
LRuntimeFunction : Pointer;
LImageBase : ULONGLONG;
HandlerData : Pointer;
EstablisherFrame : ULONG64;
NvContext : KNONVOLATILE_CONTEXT_POINTERS;
LLineNumber : integer;
LModuleName : UnicodeString;
LPublicAddr : pointer;
LPublicName : UnicodeString;
LUnitName : UnicodeString;
begin
//
// First, we'll get the caller's context.
//
RtlCaptureContext(LContext);
//
// Initialize the (optional) unwind history table.
//
LUnwindHistoryTable := Default(_UNWIND_HISTORY_TABLE);
// LUnwindHistoryTable.Unwind := True;
//
// This unwind loop intentionally skips the first call frame, as it shall
// correspond to the call to StackTrace64, which we aren't interested in.
//
repeat
//
// Try to look up unwind metadata for the current function.
//
LRuntimeFunction := RtlLookupFunctionEntry(LContext.Rip,
LImageBase,
LUnwindHistoryTable);
NvContext := Default(KNONVOLATILE_CONTEXT_POINTERS);
if not Assigned(LRuntimeFunction) then
begin
//
// If we don't have a RUNTIME_FUNCTION, then we've encountered
// a leaf function. Adjust the stack approprately.
//
//LContext.Rip := (ULONG64)(*(PULONG64)Context.Rsp);
LContext.Rip := ULONG64(Pointer(LContext.Rsp)^);
LContext.Rsp := LContext.Rsp + 8;
end
else
begin
//
// Otherwise, call upon RtlVirtualUnwind to execute the unwind for
// us.
//
RtlVirtualUnwind(UNW_FLAG_NHANDLER,
LImageBase,
LContext.Rip,
LRuntimeFunction,
LContext,
HandlerData,
EstablisherFrame,
NvContext);
end;
//
// If we reach an RIP of zero, this means that we've walked off the end
// of the call stack and are done.
//
if LContext.Rip = 0 then
Break;
//
// Display the context. Note that we don't bother showing the XMM
// context, although we have the nonvolatile portion of it.
//
if madMapFile.GetMapFileInfos(Pointer(LContext.Rip),
LModuleName,
LUnitName,
LPublicName,
LPublicAddr,
LLineNumber) then
begin
Writeln(Format('%p %s.%s %d', [Pointer(LContext.Rip), LUnitName, LPublicName, LLineNumber{, LSEHType}]));
end;
until LContext.Rip = 0;
end;
然后我用下面的语句调用它:
procedure Main();
begin
try
try
try
try
DumpExceptionStack();
finally
//
end;
except
on E : Exception do
raise
end;
except
on E : Exception do
raise
end;
except
on E : Exception do
raise
end;
end;
当我运行应用程序(只是一个控制台应用程序)时,我只得到Main
的一个条目,但我期望有四个(三个嵌套异常和最后一个)。
可能是我误解了,DumpExceptionStack
只会在抛出异常时给出我感兴趣的结果吗?如果是这样,需要做什么更改才能获得所有异常堆栈(如果可能的话)-即。Main
有四个输出吗?
与基于堆栈的x86模型相反,x64异常模型是基于表的。这意味着异常堆栈不存在。在任何情况下,我从来没有见过一个跟踪行走例程试图包含异常和finally块。这次也不例外。它遍历函数调用堆栈。
单个函数中的异常流由作用域表控制。在函数中,如果代码在调用DumpExceptionStack
时引发异常,则多个作用域表项匹配异常位置。异常由最内层的匹配作用域处理。作用域的起始地址和结束地址之间的距离可以用来推断哪个作用域是最内层的。如果最内层作用域没有处理异常,或者重新引发异常,则要求下一个最内层作用域处理异常。以此类推,直到该函数的所有匹配作用域都用完。