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
4 changes: 4 additions & 0 deletions src/core/core.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ declare class Error {
public line?: int;
constructor(message?: string, filename?: string, line?: int);
public name: string;
private stackFrames: index[];
private stackText?: string;
public toString(): string;
public get stack(): string;
public set stack(value: string);
}

@owned
Expand Down
5 changes: 5 additions & 0 deletions src/core/core.os.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
@nodrops @owned declare function convertNumber(bufferSize: int, format: string, value: number): string;
@nodrops @owned declare function convertInteger(bufferSize: int, format: string, value: long): string;

// An Error's stack: the return addresses it was made from, and their text below its first line (into the os
// result buffer, wrappers/os.cpp). lib.win32.ts and lib.linux.ts call the wrappers; lib.wasm.ts has none (0).
@nodrops declare function error_stack_capture(pcs: Opaque, max: int): int;
@nodrops declare function error_stack_text(pcs: Opaque, count: int): int;

@nodrops declare function init_time();

@nodrops declare function getMilliseconds(): i64;
Expand Down
34 changes: 34 additions & 0 deletions src/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,20 @@ const LC_COLLATE = 1;
// subclass may set (`this.name = "ValidationError"`), as in JavaScript.
export class Error {
public constructor(public message?: string, public filename?: string, public line?: int) {
// where it is made: the return addresses, named only when `stack` is read. 32, as the library's own
// frames (the capture, the constructors) come first and are left out: the program's are after them
const frames: index[] = [];
frames.length = 32;
frames.length = error_stack_capture(<Opaque>Ref(frames[0]), 32);
this.stackFrames = frames;
}

public name: string = "Error";

private stackFrames: index[];

private stackText?: string;

// JavaScript's Error.prototype.toString: "Name: message", or the name alone when there is no message
public toString(): string {
const message = this.message;
Expand All @@ -18,6 +28,30 @@ export class Error {

return this.name + ": " + message;
}

// As V8 has it: the first line is toString()'s, then a line for each frame it was made from, the closest
// first (` at f (a.ts:7)`; a frame is named with --di on Windows, and by the JIT). The frames are
// named the first time it is read, and it may be given another text. wasm has no frames: the first line alone.
public get stack(): string {
let text = this.stackText;
if (text === undefined) {
const frames = this.stackFrames;
const length = frames.length > 0 ? error_stack_text(<Opaque>Ref(frames[0]), frames.length) : 0;
let lines = length > 0 ? __os_text(length) : "";
if (lines.endsWith("\n")) {
lines = lines.substring(0, lines.length - 1);
}

text = lines.length > 0 ? this.toString() + "\n" + lines : this.toString();
this.stackText = text;
}

return text;
}

public set stack(value: string) {
this.stackText = value;
}
}

export class RangeError extends Error {
Expand Down
16 changes: 15 additions & 1 deletion src/lib.linux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,18 @@ export function time_format_locale(maxsize: index, format: string, time: long, l
//freelocale(locale_t);

return s;
}
}

// an Error's stack (core/core.os.d.ts): the wrappers capture the return addresses and name them (wrappers/os.cpp)
@nodrops declare function tslang_stack_capture(pcs: Opaque, max: int): int;
@nodrops declare function tslang_stack_text(pcs: Opaque, count: int): int;

export function error_stack_capture(pcs: Opaque, max: int): int
{
return tslang_stack_capture(pcs, max);
}

export function error_stack_text(pcs: Opaque, count: int): int
{
return tslang_stack_text(pcs, count);
}
11 changes: 11 additions & 0 deletions src/lib.wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,14 @@ export function time_format(maxsize: index, format: string, time: long, isUtc: b
export function time_format_locale(maxsize: index, format: string, time: long, locale: string, isUtc: boolean): string {
return time_format(maxsize, format, time, isUtc);
}

// an Error's stack (core/core.os.d.ts): wasm has no stack to walk, so an Error's `stack` is its first line alone
export function error_stack_capture(pcs: Opaque, max: int): int
{
return 0;
}

export function error_stack_text(pcs: Opaque, count: int): int
{
return 0;
}
16 changes: 15 additions & 1 deletion src/lib.win32.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,18 @@ export function time_format_locale(maxsize: index, format: string, time: long, l
_free_locale(locale_t);

return s;
}
}

// an Error's stack (core/core.os.d.ts): the wrappers capture the return addresses and name them (wrappers/os.cpp)
@nodrops declare function tslang_stack_capture(pcs: Opaque, max: int): int;
@nodrops declare function tslang_stack_text(pcs: Opaque, count: int): int;

export function error_stack_capture(pcs: Opaque, max: int): int
{
return tslang_stack_capture(pcs, max);
}

export function error_stack_text(pcs: Opaque, count: int): int
{
return tslang_stack_text(pcs, count);
}
258 changes: 258 additions & 0 deletions src/wrappers/os.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -778,3 +778,261 @@ extern "C" TSLANG_EXPORT int tslang_fs_copy_file(const char *from, const char *t

return 0;
}

// ---- an Error's stack ----
//
// `new Error()` captures the return addresses it was made from (tslang_stack_capture), and its `stack`, when read,
// names them (tslang_stack_text): by the program's own runtime, which names frames as the report of an uncaught
// exception does (TypeScriptCompiler's `__tslang_stack_text`: the executable's runtime, or tslang itself for a
// program the JIT runs). A runtime without it - an older compiler's - leaves `module+0xoffset` lines.

#ifdef _WIN32
// the default library's own module: an Error's frames in it (its constructors, the capture) are left out at the
// top when it is a DLL, the JIT's
static HMODULE stackOwnModule()
{
HMODULE module = nullptr;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&stackOwnModule), &module);
return module;
}

static HMODULE stackModuleOf(uintptr_t pc)
{
HMODULE module = nullptr;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(pc), &module);
return module;
}
#else
#include <dlfcn.h>
#include <sys/auxv.h>
#include <unwind.h>

struct StackCapture
{
uintptr_t *pcs;
int max;
int count;
int skip;
};

static _Unwind_Reason_Code stackCaptureFrame(_Unwind_Context *context, void *argument)
{
auto *capture = static_cast<StackCapture *>(argument);
auto pc = static_cast<uintptr_t>(_Unwind_GetIP(context));
if (!pc)
{
return _URC_END_OF_STACK;
}

if (capture->skip > 0)
{
capture->skip--;
return _URC_NO_REASON;
}

if (capture->count >= capture->max)
{
return _URC_END_OF_STACK;
}

capture->pcs[capture->count++] = pc;
return _URC_NO_REASON;
}

static const void *stackModuleOf(uintptr_t pc)
{
Dl_info info;
return dladdr(reinterpret_cast<void *>(pc), &info) ? info.dli_fbase : nullptr;
}

// the library's own module when it is a shared object of its own (the JIT's); null when it is linked into the
// executable, whose frames are the program's too
static const void *stackOwnModule()
{
auto *own = stackModuleOf(reinterpret_cast<uintptr_t>(&stackModuleOf));
auto *program = stackModuleOf(static_cast<uintptr_t>(getauxval(AT_PHDR)));
return own == program ? nullptr : own;
}

// the program's runtime's, when it has one: weak, so an executable whose runtime has none still links
extern "C" __attribute__((weak)) int __tslang_stack_text(const uintptr_t *pcs, int count, char *out, int size);
#endif

// The return addresses the caller was called from, outward: at most `max`, into `pcs`; how many
extern "C" TSLANG_EXPORT int tslang_stack_capture(uintptr_t *pcs, int max)
{
if (pcs == nullptr || max <= 0)
{
return 0;
}

#if defined(_WIN32) && (defined(_M_X64) || defined(_M_ARM64))
// unwound by the function tables, as the report of an uncaught exception walks: RtlCaptureStackBackTrace stops
// at code no image holds, the JIT's (which registers its tables). The first pc is this function's own.
CONTEXT context;
RtlCaptureContext(&context);
auto count = 0;
auto skip = 1;
while (count < max)
{
#ifdef _M_X64
auto pc = context.Rip;
#else
auto pc = context.Pc;
#endif
if (!pc)
{
break;
}

if (skip > 0)
{
skip--;
}
else
{
pcs[count++] = static_cast<uintptr_t>(pc);
}

DWORD64 imageBase;
auto *function = RtlLookupFunctionEntry(pc, &imageBase, nullptr);
if (function)
{
void *handlerData;
DWORD64 establisherFrame;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, imageBase, pc, function, &context, &handlerData, &establisherFrame, nullptr);
}
else
{
// a leaf function: where it returns to is on top of the stack, or in the link register
#ifdef _M_X64
context.Rip = *reinterpret_cast<DWORD64 *>(context.Rsp);
context.Rsp += 8;
#else
context.Pc = context.Lr;
#endif
}
}
#elif defined(_WIN32)
// this function's own frame is not one of them
auto count = static_cast<int>(RtlCaptureStackBackTrace(1, static_cast<DWORD>(max), reinterpret_cast<PVOID *>(pcs), nullptr));
#else
StackCapture capture{pcs, max, 0, 1};
_Unwind_Backtrace(stackCaptureFrame, &capture);
auto count = capture.count;
#endif

#if defined(TSLANG_WRAPPERS_DLL) || !defined(_WIN32)
// in a DLL or a shared object (the JIT's) the library's own frames - its Error constructors - are the first
// ones in its module; in an executable the program's are in the same module, and the runtime leaves them out
// by name
auto own = stackOwnModule();
auto first = 0;
while (first < count && own && stackModuleOf(pcs[first]) == own)
{
first++;
}

if (first > 0 && first < count)
{
memmove(pcs, pcs + first, (count - first) * sizeof(uintptr_t));
count -= first;
}
#endif

return count;
}

#ifdef _WIN32
using StackText = int (*)(const uintptr_t *, int, char *, int);

// the executable's exports have it: tslang's, for a program the JIT runs, or the program's own runtime's
// (an older one has none)
static StackText hostStackText()
{
return reinterpret_cast<StackText>(GetProcAddress(GetModuleHandleW(nullptr), "__tslang_stack_text"));
}
#endif

// The frames `pcs` (from tslang_stack_capture) as an Error's `stack` says them below its first line,
// ` at f (a.ts:7)` each, into the result buffer (tslang_os_result_copy_to); its length
extern "C" TSLANG_EXPORT int tslang_stack_text(const uintptr_t *pcs, int count)
{
result.clear();
if (pcs == nullptr || count <= 0)
{
return 0;
}

auto said = -1;
char text[4096];
#ifdef _WIN32
auto stackText = hostStackText();
if (stackText)
{
said = stackText(pcs, count, text, static_cast<int>(sizeof(text)));
if (said >= static_cast<int>(sizeof(text)))
{
std::vector<char> larger(said + 1);
said = stackText(pcs, count, larger.data(), static_cast<int>(larger.size()));
result.assign(larger.data(), said > 0 ? said : 0);
return static_cast<int>(result.size());
}
}
#else
if (__tslang_stack_text)
{
said = __tslang_stack_text(pcs, count, text, static_cast<int>(sizeof(text)));
if (said >= static_cast<int>(sizeof(text)))
{
std::vector<char> larger(said + 1);
said = __tslang_stack_text(pcs, count, larger.data(), static_cast<int>(larger.size()));
result.assign(larger.data(), said > 0 ? said : 0);
return static_cast<int>(result.size());
}
}
#endif

if (said >= 0)
{
result.assign(text, said);
return static_cast<int>(result.size());
}

// no runtime to name them: each frame's module and the offset in it, as a symbolizer takes them; 10 at most,
// as V8's Error.stackTraceLimit (the runtime's stops at main)
for (auto i = 0; i < count && i < 10; i++)
{
char line[600];
auto pc = pcs[i];
#ifdef _WIN32
auto module = stackModuleOf(pc);
char path[MAX_PATH];
auto length = module ? GetModuleFileNameA(module, path, MAX_PATH) : 0;
if (length > 0 && length < MAX_PATH)
{
auto *name = strrchr(path, '\\');
snprintf(line, sizeof(line), " at %s+0x%llx\n", name ? name + 1 : path,
static_cast<unsigned long long>(pc - reinterpret_cast<uintptr_t>(module)));
}
#else
Dl_info info;
if (dladdr(reinterpret_cast<void *>(pc), &info) && info.dli_fname)
{
auto *name = strrchr(info.dli_fname, '/');
snprintf(line, sizeof(line), " at %s+0x%llx\n", name ? name + 1 : info.dli_fname,
static_cast<unsigned long long>(pc - reinterpret_cast<uintptr_t>(info.dli_fbase)));
}
#endif
else
{
snprintf(line, sizeof(line), " at 0x%llx\n", static_cast<unsigned long long>(pc));
}

result += line;
}

return static_cast<int>(result.size());
}
Loading
Loading