Commit efa9a642

efa9a64231c9Merged

Ori Pekelman <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

Add opt-in native backtrace: Exception#backtrace under --debug (item 4)

Roadmap item 4 — restore Ruby backtraces without the per-frame shadow stack the design note sketched. In a --debug build (-g, methods non-inlined) the sp_ symbols are present, so the runtime snapshots the live C stack at raise time and formats it into a Ruby backtrace — no codegen per-method push/pop injection at all.

  • lib/sp_runtime.h: sp_raise_cls (the central raise funnel — user raise and every runtime error route through it) captures backtrace() into sp_bt_buf when sp_bt_enabled. sp_backtrace_captured() formats it via backtrace_symbols: filters runtime helpers (denylist), demangles sp_add -> add and sp_Calc_divide -> Calc#divide, renders <src>:in \name'`. sp_caller_now() is ready for Kernel#caller. Gated by sp_bt_enabled (default 0) so non-debug is byte-for-byte unchanged; guarded by !_WIN32 (execinfo). Header-only — single TU, no lib rebuild.
  • spinel_codegen.rb: Exception#backtrace returns sp_backtrace_captured() when @debug (else the empty array as before); main() sets sp_bt_enabled and the source path in debug builds.

Verified: nested raise -> inner/outer/; ZeroDivisionError -> Calc#divide <- <main> (the sp_idiv helper filtered). Non-debug compiles clean under the suite's -Werror and backtrace stays empty; 8/8 sampled tests pass. ori fork (feat/typing).

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
efa9a64231c9
Parent
cc46c1a4533c

lib/sp_runtime.hmodifiedView file

@@ -27,6 +27,25 @@
2727 #include <errno.h>
2828 #include <sys/stat.h>
2929 #include <dirent.h>
30+
31+/* Opt-in native backtrace (spinel --debug). In a -g, non-inlined build the
32+ sp_<method> symbols are present, so sp_raise_cls can snapshot the live C
33+ stack at raise time and Exception#backtrace / caller format it into a
34+ Ruby-style backtrace — no per-method shadow frames needed. Off unless the
35+ generated main() sets sp_bt_enabled (debug builds), so non-debug behaviour
36+ and cost are unchanged. execinfo is POSIX-ish; absent on Windows. */
37+#if !defined(_WIN32)
38+#include <execinfo.h>
39+#define SP_BT_AVAILABLE 1
40+#else
41+#define SP_BT_AVAILABLE 0
42+#endif
43+static int sp_bt_enabled = 0; /* set to 1 by debug-build main() */
44+static const char *sp_bt_srcfile = ""; /* toplevel .rb path, set by debug main() */
45+#if SP_BT_AVAILABLE
46+static void *sp_bt_buf[256]; /* frames captured at the last raise */
47+static int sp_bt_n = 0;
48+#endif
3049 #ifdef _WIN32
3150 #include <windows.h>
3251 #include <process.h>
@@ -3318,7 +3337,107 @@
33183337 static volatile int sp_exc_top = 0;
33193338 static const char *sp_exc_cls[SP_EXC_STACK_MAX];
33203339 static volatile const char *sp_last_exc_cls = sp_str_empty;
3321-void sp_raise_cls(const char *cls, const char *msg) { if (sp_exc_top > 0) { sp_exc_msg[sp_exc_top-1] = msg; sp_exc_cls[sp_exc_top-1] = cls; sp_last_exc_cls = cls; longjmp(sp_exc_stack[sp_exc_top-1], 1); } fprintf(stderr, "unhandled exception: %s\n", msg); exit(1); }
3340+/* ---- Native backtrace formatting (spinel --debug) ---------------------- */
3341+/* True for sp_<name> symbols that are runtime helpers, not user Ruby methods.
3342+ A denylist of the lowercase runtime prefixes; user methods are sp_<rubyname>
3343+ (top-level) or sp_<Class>_<method>, which don't match. Heuristic — a leaf
3344+ runtime frame may occasionally slip through; refine with an emitted
3345+ user-method allowlist later. */
3346+#if SP_BT_AVAILABLE
3347+static int sp_bt_is_runtime(const char *n) {
3348+ static const char *pfx[] = {
3349+ "int_", "str_", "float_", "sym_", "gc_", "bigint", "sprintf", "raise",
3350+ "exc_", "range", "utf8", "oom", "bt_", "backtrace", "caller", "StrArray",
3351+ "IntArray", "FloatArray", "PtrArray", "PolyArray", "Str", "Int", "Float",
3352+ "Hash", "Range", "Complex", "Rational", "Sym", "alloc", "free", "to_s",
3353+ "dup", "new", "pack", "unpack", "regex", "re_",
3354+ /* arithmetic/runtime helpers that can raise and sit between the raise
3355+ and the user frame (ZeroDivisionError via sp_idiv/sp_imod, etc.) */
3356+ "idiv", "imod", "gcd", "fdiv", "ipow", "iclamp", "div_", "mod_", 0
3357+ };
3358+ for (int i = 0; pfx[i]; i++) {
3359+ size_t l = strlen(pfx[i]);
3360+ if (strncmp(n, pfx[i], l) == 0) return 1;
3361+ }
3362+ return 0;
3363+}
3364+
3365+/* macOS backtrace_symbols line: "<idx> <image> <addr> <symbol> + <off>".
3366+ Extract the symbol token; NULL if it isn't a keepable user frame. */
3367+static const char *sp_bt_symbol(const char *line) {
3368+ const char *p = strstr(line, "0x"); /* the address */
3369+ if (!p) return 0;
3370+ while (*p && *p != ' ') p++; /* skip the address */
3371+ while (*p == ' ') p++; /* to the symbol */
3372+ if (!*p) return 0;
3373+ const char *end = p;
3374+ while (*end && *end != ' ') end++; /* symbol ends at space/" +" */
3375+ size_t len = (size_t)(end - p);
3376+ if (len == 0 || len > 250) return 0;
3377+ char sym[256];
3378+ memcpy(sym, p, len); sym[len] = 0;
3379+ if (strcmp(sym, "main") == 0) return strdup("<main>");
3380+ if (strncmp(sym, "sp_", 3) != 0) return 0; /* skip non-Spinel frames */
3381+ const char *name = sym + 3;
3382+ if (sp_bt_is_runtime(name)) return 0;
3383+ /* sp_Class_method -> Class#method (heuristic: split first '_' after an
3384+ initial uppercase segment); else just the stripped name. */
3385+ char out[256];
3386+ if (name[0] >= 'A' && name[0] <= 'Z') {
3387+ const char *u = strchr(name, '_');
3388+ if (u) {
3389+ size_t cl = (size_t)(u - name);
3390+ memcpy(out, name, cl);
3391+ out[cl] = '#';
3392+ strcpy(out + cl + 1, u + 1);
3393+ return strdup(out);
3394+ }
3395+ }
3396+ return strdup(name);
3397+}
3398+
3399+static sp_StrArray *sp_bt_format(void **buf, int n) {
3400+ sp_StrArray *a = sp_StrArray_new();
3401+ if (!sp_bt_enabled || n <= 0) return a;
3402+ char **syms = backtrace_symbols(buf, n);
3403+ if (!syms) return a;
3404+ const char *src = (sp_bt_srcfile && sp_bt_srcfile[0]) ? sp_bt_srcfile : "(spinel)";
3405+ for (int i = 0; i < n; i++) {
3406+ const char *name = sp_bt_symbol(syms[i]);
3407+ if (!name) continue;
3408+ sp_StrArray_push(a, sp_sprintf("%s:in `%s'", src, name));
3409+ }
3410+ free(syms);
3411+ return a;
3412+}
3413+#endif
3414+
3415+/* Backtrace captured at the most recent raise (for Exception#backtrace). */
3416+static sp_StrArray *sp_backtrace_captured(void) {
3417+#if SP_BT_AVAILABLE
3418+ return sp_bt_format(sp_bt_buf, sp_bt_n);
3419+#else
3420+ return sp_StrArray_new();
3421+#endif
3422+}
3423+
3424+/* The current stack, captured now (for Kernel#caller). */
3425+static sp_StrArray *sp_caller_now(void) {
3426+#if SP_BT_AVAILABLE
3427+ if (!sp_bt_enabled) return sp_StrArray_new();
3428+ void *buf[256];
3429+ int n = backtrace(buf, 256);
3430+ return sp_bt_format(buf, n);
3431+#else
3432+ return sp_StrArray_new();
3433+#endif
3434+}
3435+
3436+void sp_raise_cls(const char *cls, const char *msg) {
3437+#if SP_BT_AVAILABLE
3438+ if (sp_bt_enabled) sp_bt_n = backtrace(sp_bt_buf, 256);
3439+#endif
3440+ if (sp_exc_top > 0) { sp_exc_msg[sp_exc_top-1] = msg; sp_exc_cls[sp_exc_top-1] = cls; sp_last_exc_cls = cls; longjmp(sp_exc_stack[sp_exc_top-1], 1); } fprintf(stderr, "unhandled exception: %s\n", msg); exit(1); }
33223441 static void sp_raise(const char *msg) { sp_raise_cls("RuntimeError", msg); }
33233442
33243443 /* Issue #781: bridge between the regex compile-error path (which lives