Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1209,8 +1209,7 @@ All entries in the table except the `Triple` field are optional. [Documentation]
Debugging
=========

Terra provides a few library functions to help debug and performance tune code. Except for `currenttimeinseconds`,
these debugging facilities are only available on OSX and Linux.
Terra provides a few library functions to help debug and performance tune code.

---

Expand All @@ -1222,7 +1221,7 @@ A Lua function that returns the current time in seconds since some fixed time in

terra terralib.traceback(uctx : &opaque)

A Terra function that can be called from Terra code to print a stack trace. If `uctx` is `nil` then this will print the current stack. `uctx` can also be a pointer to a `ucontext_t` object (see `ucontext.h`) and will print the stack trace for that context.
A Terra function that can be called from Terra code to print a stack trace. If `uctx` is `nil` then this will print the current stack. `uctx` can also be a pointer to a suspended context and will print the stack trace for that context: a `ucontext_t` object (see `ucontext.h`) on POSIX, or a `CONTEXT` record on Windows.
By default, the interpreter will print this information when a program segfaults.

---
Expand Down
63 changes: 53 additions & 10 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,25 +117,68 @@ void registerhandler() {
sigaction(SIGFPE, &sa, NULL);
}
#else
LONG WINAPI windowsheapcorruptionhandler(EXCEPTION_POINTERS *ExceptionInfo) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_HEAP_CORRUPTION) {
// The traceback is often useless, so make it clear what happened
// A fault, as opposed to the exception codes C++ and LuaJIT raise to unwind
// with, which are somebody's business to catch.
static bool isfault(DWORD code) {
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ILLEGAL_INSTRUCTION:
case EXCEPTION_PRIV_INSTRUCTION:
case EXCEPTION_DATATYPE_MISALIGNMENT:
case EXCEPTION_INT_DIVIDE_BY_ZERO:
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
case EXCEPTION_STACK_OVERFLOW:
return true;
default:
return false;
}
}

// Vectored handlers run before the search for a frame based one, which is the
// only reason a fault inside JIT'd code can be reported at all: that search
// walks the stack through .pdata, the JIT emits an ELF container and so has
// none, and the search runs off the frame instead of finding anything. The
// process dies there, before any unhandled exception filter is reached.
//
// So take a fault only where that search cannot get past it, and leave
// everything Windows can dispatch to the filter below. A frame with no unwind
// info is either JIT'd code or a leaf function, and nothing recovers from a
// fault in a leaf either, so claiming both is fine.
//
// Heap corruption is the exception: it is raised somewhere unrelated to the
// damage, so the traceback is usually useless and the point is to say what
// happened. See
// https://peteronprogramming.wordpress.com/2017/07/30/crashes-you-cant-handle-easily-3-status_heap_corruption-on-windows/
LONG WINAPI windowsvectoredhandler(EXCEPTION_POINTERS *ExceptionInfo) {
DWORD code = ExceptionInfo->ExceptionRecord->ExceptionCode;
if (code == STATUS_HEAP_CORRUPTION) {
printf("Heap corruption detected!\n");
if (terratraceback) terratraceback(ExceptionInfo->ContextRecord);
fflush(NULL);
TerminateProcess(GetCurrentProcess(),
ExceptionInfo->ExceptionRecord->ExceptionCode);
} else {
DWORD64 imagebase;
if (!isfault(code) ||
RtlLookupFunctionEntry(ExceptionInfo->ContextRecord->Rip, &imagebase, NULL))
return EXCEPTION_CONTINUE_SEARCH;
}
return EXCEPTION_CONTINUE_SEARCH;
// Cleared once shutdown has torn down the state it reads, which is exactly
// when heap corruption is most likely, so say so either way.
if (terratraceback) terratraceback(ExceptionInfo->ContextRecord);
fflush(NULL);
TerminateProcess(GetCurrentProcess(), code);
return EXCEPTION_CONTINUE_SEARCH; /* not reached */
}
LONG WINAPI windowsexceptionhandler(EXCEPTION_POINTERS *ExceptionInfo) {
if (terratraceback) terratraceback(ExceptionInfo->ContextRecord);
fflush(NULL);
return EXCEPTION_EXECUTE_HANDLER;
}
void registerhandler() {
// https://peteronprogramming.wordpress.com/2017/07/30/crashes-you-cant-handle-easily-3-status_heap_corruption-on-windows/
AddVectoredExceptionHandler(1, windowsheapcorruptionhandler);
// Reserve space on stack overflow so that we can still run the backtrace
// code in the handler.
ULONG guarantee = 64 * 1024;
SetThreadStackGuarantee(&guarantee);

AddVectoredExceptionHandler(1, windowsvectoredhandler);
SetUnhandledExceptionFilter(windowsexceptionhandler);
}
void releasesignalstack() {}
Expand Down
85 changes: 74 additions & 11 deletions src/tdebug.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
#else
#include "twindows.h"
#include <imagehlp.h>
#include <intrin.h>
#endif

using namespace llvm;
Expand Down Expand Up @@ -99,6 +98,71 @@ static int terra_backtrace(void **frames, int maxN, void *rip, void *rbp) {
return i;
}

#ifdef _WIN32
// Win64 keeps no frame pointer chain: rbp is an ordinary register there and
// native code is unwound from the RUNTIME_FUNCTION tables in .pdata. JIT'd code
// has no such tables, because the JIT emits an ELF container and ELF carries
// none, but under -g every Terra function keeps rbp, so a Terra frame can be
// stepped by hand instead. Walking both in one loop is what lets the stack
// cross between them in either direction: the hand written step also rebuilds
// the rsp and rbp that the table driven one needs to carry on above a Terra
// frame, and the table driven one restores whatever rbp the Terra frame below
// it was using.

// One table driven step, for a frame that is not Terra's. Returns false when
// there is nothing above that can be accounted for.
static bool unwindnative(CONTEXT *ctx, bool innermost) {
DWORD64 imagebase;
PRUNTIME_FUNCTION rf = RtlLookupFunctionEntry(ctx->Rip, &imagebase, NULL);
if (!rf) {
// No entry at all is how the ABI spells a leaf function: it saved
// nothing, so the return address is still on top of the stack. Only the
// innermost frame can be a leaf though. Anywhere else this is code the
// walk cannot account for, another JIT's say, and reading the stack as
// if it were a leaf would print noise.
if (!innermost || IsBadReadPtr((void *)ctx->Rsp, sizeof(void *))) return false;
ctx->Rip = *(DWORD64 *)ctx->Rsp;
ctx->Rsp += sizeof(void *);
return true;
}
PVOID handlerdata;
DWORD64 establisher;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, imagebase, ctx->Rip, rf, ctx, &handlerdata,
&establisher, NULL);
return true;
}

// Runs from an exception handler, so it must not allocate. The context is
// consumed.
static int terra_backtrace_context(terra_CompilerState *C, void **frames, int maxN,
CONTEXT *ctx) {
int i = 0;
while (i < maxN && ctx->Rip) {
bool innermost = i == 0;
frames[i++] = (void *)ctx->Rip;
DWORD64 rsp = ctx->Rsp;
const TerraFunctionInfo *fi;
if (stacktrace_findsymbol(C, (uintptr_t)ctx->Rip, &fi)) {
// Without -g there is no frame record to read, and rbp holds
// whatever the register allocator put there, so stop rather than
// follow it. printstacktrace says so afterwards.
if (!C->debug) break;
// The prologue is push rbp; mov rbp, rsp, so the frame record is
// the two words at rbp and the caller resumes just above them.
Frame *frame = (Frame *)ctx->Rbp;
if (!frame || IsBadReadPtr(frame, sizeof(Frame)) || !frame->addr) break;
ctx->Rip = (DWORD64)frame->addr;
ctx->Rsp = (DWORD64)(frame + 1);
ctx->Rbp = (DWORD64)frame->next;
} else if (!unwindnative(ctx, innermost)) {
break;
}
if (ctx->Rsp <= rsp) break; // a step has to shrink the stack, or it is junk
}
return i;
}
#endif

static void stacktrace_printsourceline(const char *filename, size_t lineno) {
FILE *file = fopen(filename, "r");
if (!file) return;
Expand Down Expand Up @@ -141,10 +205,9 @@ static void printstacktrace(void *uap, void *data) {
const int maxN = 128;
void *frames[maxN];
bool anyterra = false;
void *rip;
void *rbp;

#ifndef _WIN32
void *rip, *rbp;
if (uap == NULL) {
rip = __builtin_return_address(0);
rbp = __builtin_frame_address(1);
Expand Down Expand Up @@ -178,19 +241,19 @@ static void printstacktrace(void *uap, void *data) {
#endif
#endif
}
int N = terra_backtrace(frames, maxN, rip, rbp);
#else
CONTEXT context;
if (uap == NULL) {
CONTEXT cur_context;
RtlCaptureContext(&cur_context);
rbp = (void *)cur_context.Rbp;
rip = _ReturnAddress();
RtlCaptureContext(&context);
// Step out of this function first, so that the walk starts in the frame
// that asked for the traceback, as it does on POSIX.
if (!unwindnative(&context, true)) return;
} else {
CONTEXT *context = (CONTEXT *)uap;
rip = (void *)context->Rip;
rbp = (void *)context->Rbp;
context = *(CONTEXT *)uap;
}
int N = terra_backtrace_context(C, frames, maxN, &context);
#endif
int N = terra_backtrace(frames, maxN, rip, rbp);

#ifndef _WIN32
char **symbols = backtrace_symbols(frames, N);
Expand Down
11 changes: 3 additions & 8 deletions tests/jitlineinfo.t
Original file line number Diff line number Diff line change
Expand Up @@ -125,18 +125,13 @@ for i = 0, size - 1 do
end
end

-- Ensure we actually get line info (except where not supported).
local located = 0
for _ in pairs(lines) do located = located + 1 end

-- Reading the line table takes either a copy of the emitted object with its
-- debug sections relocated to where the code was loaded, which RuntimeDyld
-- only builds for ELF, or the object's own sections read as emitted and
-- addresses biased by where the code landed, which is what MachO needs. A
-- platform with neither has nothing to read and nothing to check.
if located == 0 then
assert(ffi.os ~= "Linux" and ffi.os ~= "BSD" and ffi.os ~= "OSX",
assert(ffi.os == "Windows" and terralib.llvmversion < 120,
"no address in work() has line info, out of " .. size .. " bytes")
print("skipping: " .. ffi.os .. " JIT objects carry no usable debug info")
print("skipping: LLVM 11 on Windows reads back no line table")
return
end

Expand Down
19 changes: 10 additions & 9 deletions tests/traceframes.t
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,6 @@ if not terralib.traceback then
return
end

-- The walk follows the frame pointer chain from RtlCaptureContext().Rbp, but
-- Win64 keeps no such chain: rbp is a general register there and unwinding goes
-- through .pdata instead. Only the innermost frame is recoverable, so there is
-- nothing here to check. See windows-traceback-plan.md.
if ffi.os == "Windows" then
print("skipping: Win64 keeps no frame pointer chain to walk")
return
end

local scriptpath = arg[0]
local terracmd = terralib.terrahome .. "/bin/terra"

Expand Down Expand Up @@ -118,11 +109,21 @@ local function reports(out, marker)
return out:find(basename .. ":" .. line .. "%)") ~= nil, line
end

local function haslineinfo(out)
return out:find(basename .. ":%d+%)") ~= nil
end

local function checkchain(out, mode, markers)
local n = terraframes(out)
assert(n == #markers,
mode .. " with -g reported " .. n .. " Terra frames, expected "
.. #markers .. ":\n" .. out)
if not haslineinfo(out) then
assert(ffi.os == "Windows" and terralib.llvmversion < 120,
mode .. " with -g reported no source line for any frame:\n" .. out)
print("skipping line checks: LLVM 11 on Windows reads back no line table")
return
end
for _, m in ipairs(markers) do
local found, line = reports(out, m)
assert(found, mode .. " with -g does not report " .. basename .. ":" .. line
Expand Down