From 1055002684ad758a9584ecf4c32340b974cf174a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 30 Nov 2026 21:14:43 +0000 Subject: [PATCH] Error has a stack: where it was made, as V8 says it - `new Error()` captures the return addresses it was made from (wrappers/os.cpp tslang_stack_capture: on Windows unwound by the function tables, which the JIT's code has too; on Linux _Unwind_Backtrace); in the DLL or shared object the JIT loads, the library's own frames are left out - `stack`, read: toString()'s first line, then ` at f (a.ts:7)` lines, at most 10. Named by the program's runtime (the compiler's `__tslang_stack_text`: the executable's runtime, or tslang for the JIT), as the report of an uncaught exception names frames; a runtime without it (an older compiler's) leaves `module+0xoffset` lines. It may be given another text. - wasm has no frames: its `stack` is the first line alone (lib.wasm.ts) - the platform layers give core.ts error_stack_capture / error_stack_text (core/core.os.d.ts) Co-Authored-By: Claude Opus 5.5 --- src/core/core.d.ts | 4 + src/core/core.os.d.ts | 5 + src/core/core.ts | 34 ++++++ src/lib.linux.ts | 16 ++- src/lib.wasm.ts | 11 ++ src/lib.win32.ts | 16 ++- src/wrappers/os.cpp | 258 ++++++++++++++++++++++++++++++++++++++++++ tests/error_stack.ts | 55 +++++++++ 8 files changed, 397 insertions(+), 2 deletions(-) create mode 100644 tests/error_stack.ts diff --git a/src/core/core.d.ts b/src/core/core.d.ts index 8c2fa7d..ca910a4 100644 --- a/src/core/core.d.ts +++ b/src/core/core.d.ts @@ -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 diff --git a/src/core/core.os.d.ts b/src/core/core.os.d.ts index a811516..3b07a7c 100644 --- a/src/core/core.os.d.ts +++ b/src/core/core.os.d.ts @@ -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; diff --git a/src/core/core.ts b/src/core/core.ts index 965c8ca..d002d60 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -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(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; @@ -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(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 { diff --git a/src/lib.linux.ts b/src/lib.linux.ts index a9f6478..fa037f3 100644 --- a/src/lib.linux.ts +++ b/src/lib.linux.ts @@ -171,4 +171,18 @@ export function time_format_locale(maxsize: index, format: string, time: long, l //freelocale(locale_t); return s; -} \ No newline at end of file +} + +// 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); +} diff --git a/src/lib.wasm.ts b/src/lib.wasm.ts index f7fb7e3..567aed2 100644 --- a/src/lib.wasm.ts +++ b/src/lib.wasm.ts @@ -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; +} diff --git a/src/lib.win32.ts b/src/lib.win32.ts index 0e31d1d..48ef648 100644 --- a/src/lib.win32.ts +++ b/src/lib.win32.ts @@ -148,4 +148,18 @@ export function time_format_locale(maxsize: index, format: string, time: long, l _free_locale(locale_t); return s; -} \ No newline at end of file +} + +// 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); +} diff --git a/src/wrappers/os.cpp b/src/wrappers/os.cpp index fd70caa..6b38fef 100644 --- a/src/wrappers/os.cpp +++ b/src/wrappers/os.cpp @@ -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(&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(pc), &module); + return module; +} +#else +#include +#include +#include + +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(argument); + auto pc = static_cast(_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(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(&stackModuleOf)); + auto *program = stackModuleOf(static_cast(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(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(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(RtlCaptureStackBackTrace(1, static_cast(max), reinterpret_cast(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(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(sizeof(text))); + if (said >= static_cast(sizeof(text))) + { + std::vector larger(said + 1); + said = stackText(pcs, count, larger.data(), static_cast(larger.size())); + result.assign(larger.data(), said > 0 ? said : 0); + return static_cast(result.size()); + } + } +#else + if (__tslang_stack_text) + { + said = __tslang_stack_text(pcs, count, text, static_cast(sizeof(text))); + if (said >= static_cast(sizeof(text))) + { + std::vector larger(said + 1); + said = __tslang_stack_text(pcs, count, larger.data(), static_cast(larger.size())); + result.assign(larger.data(), said > 0 ? said : 0); + return static_cast(result.size()); + } + } +#endif + + if (said >= 0) + { + result.assign(text, said); + return static_cast(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(pc - reinterpret_cast(module))); + } +#else + Dl_info info; + if (dladdr(reinterpret_cast(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(pc - reinterpret_cast(info.dli_fbase))); + } +#endif + else + { + snprintf(line, sizeof(line), " at 0x%llx\n", static_cast(pc)); + } + + result += line; + } + + return static_cast(result.size()); +} diff --git a/tests/error_stack.ts b/tests/error_stack.ts new file mode 100644 index 0000000..41e986b --- /dev/null +++ b/tests/error_stack.ts @@ -0,0 +1,55 @@ +// An Error's `stack`, as V8 has it: toString()'s first line, then a ` at ...` line for each frame it was made +// from, the closest first. The names depend on the build (a frame is named with --di on Windows, and by the +// JIT; otherwise `program.exe+0x1a2b`), and wasm has no frames, so only the shape is checked here. + +class ValidationError extends Error { + constructor(message: string) { + super(message); + this.name = "ValidationError"; + } +} + +function check(condition: boolean, message: string) { + if (!condition) { + console.log("fail:", message); + assert(false, message); + } +} + +function makeError(n: number): Error { + return n > 0 ? new RangeError("too far: " + n) : new ValidationError("empty"); +} + +function checkShape(e: Error, firstLine: string) { + const lines = e.stack.split("\n"); + check(lines[0] == firstLine, "the first line is toString()'s: " + lines[0]); + for (let i = 1; i < lines.length; i++) { + check(lines[i].startsWith(" at "), "a frame's line: " + lines[i]); + } + + check(lines.length <= 11, "at most 10 frames"); +} + +function main() { + const range = makeError(3); + checkShape(range, "RangeError: too far: 3"); + check(range.stack == range.stack, "read twice, the same text"); + + const validation = makeError(0); + checkShape(validation, "ValidationError: empty"); + + try { + throw makeError(1); + } catch (caught) { + checkShape(caught, "RangeError: too far: 1"); + } + + checkShape(new Error(), "Error"); + + const replaced = new Error("x"); + replaced.stack = "my own text"; + check(replaced.stack == "my own text", "stack can be given another text"); + + // (not printed: tests.sh takes a run that prints "Error" as failed) + console.log("ALL DONE"); +}