Commit 9f791ea9

9f791ea97aa9Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · ~3 modified

Description

Merge pull request #1300 from OriPekelman/pr/native-backtrace

Add native Exception#backtrace under --debug (macOS + Linux)

Details

Commit
9f791ea97aa9
Parent
4da406718b05
Merge parent
b861755e4333

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>
@@ -3398,7 +3417,143 @@
33983417 static volatile int sp_exc_top = 0;
33993418 static const char *sp_exc_cls[SP_EXC_STACK_MAX];
34003419 static volatile const char *sp_last_exc_cls = sp_str_empty;
3401-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); }
3420+/* ---- Native backtrace formatting (spinel --debug) ---------------------- */
3421+/* True for sp_<name> symbols that are runtime helpers, not user Ruby methods.
3422+ A denylist of the lowercase runtime prefixes; user methods are sp_<rubyname>
3423+ (top-level) or sp_<Class>_<method>, which don't match. Heuristic — a leaf
3424+ runtime frame may occasionally slip through; refine with an emitted
3425+ user-method allowlist later. */
3426+#if SP_BT_AVAILABLE
3427+static int sp_bt_is_runtime(const char *n) {
3428+ static const char *pfx[] = {
3429+ "int_", "str_", "float_", "sym_", "gc_", "bigint", "sprintf", "raise",
3430+ "exc_", "range", "utf8", "oom", "bt_", "backtrace", "caller", "StrArray",
3431+ "IntArray", "FloatArray", "PtrArray", "PolyArray", "Str", "Int", "Float",
3432+ "Hash", "Range", "Complex", "Rational", "Sym", "alloc", "free", "to_s",
3433+ "dup", "new", "pack", "unpack", "regex", "re_",
3434+ /* arithmetic/runtime helpers that can raise and sit between the raise
3435+ and the user frame (ZeroDivisionError via sp_idiv/sp_imod, etc.) */
3436+ "idiv", "imod", "gcd", "fdiv", "ipow", "iclamp", "div_", "mod_", 0
3437+ };
3438+ for (int i = 0; pfx[i]; i++) {
3439+ size_t l = strlen(pfx[i]);
3440+ if (strncmp(n, pfx[i], l) == 0) return 1;
3441+ }
3442+ return 0;
3443+}
3444+
3445+/* Extract the symbol token from a backtrace_symbols line. Two formats:
3446+ - glibc/Linux: "<module>(<symbol>+0x<off>) [0x<addr>]". The symbol is
3447+ empty for unresolved frames (static or stripped fns) -> skip.
3448+ - macOS: "<idx> <image> <addr> <symbol> + <off>".
3449+ Returns NULL if it isn't a keepable user frame. Detect Linux by the '('
3450+ that delimits the symbol (the macOS format has none). */
3451+static const char *sp_bt_symbol(const char *line) {
3452+ char sym[256];
3453+ const char *lp = strchr(line, '(');
3454+ if (lp) { /* glibc/Linux paren form */
3455+ const char *p = lp + 1;
3456+ const char *end = p;
3457+ while (*end && *end != '+' && *end != ')') end++;
3458+ size_t len = (size_t)(end - p);
3459+ if (len == 0 || len > 250) return 0; /* unresolved (static/stripped) */
3460+ memcpy(sym, p, len); sym[len] = 0;
3461+ } else { /* macOS: "<idx> <image> <addr> <symbol> + <off>" */
3462+ /* The symbol is the token just before the " + <off>" delimiter. Parse
3463+ backward from the last " + " rather than forward from "0x" — an image
3464+ path containing "0x" (e.g. /path/0x_proj/bin) would otherwise misparse. */
3465+ const char *plus = 0, *q = line;
3466+ while ((q = strstr(q, " + ")) != 0) { plus = q; q += 3; }
3467+ if (!plus) return 0;
3468+ const char *end = plus;
3469+ const char *p = end;
3470+ while (p > line && p[-1] != ' ') p--; /* back up to the symbol's start */
3471+ size_t len = (size_t)(end - p);
3472+ if (len == 0 || len > 250) return 0;
3473+ memcpy(sym, p, len); sym[len] = 0;
3474+ }
3475+ if (strcmp(sym, "main") == 0) return strdup("<main>");
3476+ if (strncmp(sym, "sp_", 3) != 0) return 0; /* skip non-Spinel frames */
3477+ const char *name = sym + 3;
3478+ if (sp_bt_is_runtime(name)) return 0;
3479+ /* De-mangle sp_<Class>_<method> back to Ruby. A Spinel symbol is a path of
3480+ CamelCase class segments (each from a `::`, joined by `_`) followed by the
3481+ method; the method is the first segment that starts lowercase. A literal
3482+ `cls` segment marks a singleton method:
3483+ sp_Helper_cls_boom -> Helper.boom
3484+ sp_Tep_Url_parse_query -> Tep::Url#parse_query
3485+ sp_Tep_AuthOAuth2_cls_find -> Tep::AuthOAuth2.find
3486+ sp_toplevel -> toplevel (top-level method, no class)
3487+ (Method names stay sanitized — e.g. enabled? is enabled_p; reversing that
3488+ needs the emitted name table, a separate refinement.) */
3489+ const char *mstart = 0; /* first lowercase-starting segment = the method */
3490+ for (const char *p = name; *p; p++) {
3491+ int seg_start = (p == name) || (p[-1] == '_');
3492+ if (seg_start && *p >= 'a' && *p <= 'z') { mstart = p; break; }
3493+ }
3494+ if (!mstart) return strdup(name); /* all-uppercase: leave as-is */
3495+ if (mstart == name) { /* no class path: top-level */
3496+ if (strncmp(name, "cls_", 4) == 0) return strdup(name + 4); /* top-level singleton */
3497+ return strdup(name);
3498+ }
3499+ char out[256]; size_t o = 0;
3500+ const char *meth; char sep;
3501+ if (strncmp(mstart, "cls_", 4) == 0) { meth = mstart + 4; sep = '.'; } /* singleton */
3502+ else { meth = mstart; sep = '#'; } /* instance */
3503+ for (const char *p = name; p < mstart - 1 && o + 2 < sizeof(out); p++) {
3504+ if (*p == '_') { out[o++] = ':'; out[o++] = ':'; } /* class-path `_` was a `::` */
3505+ else out[o++] = *p;
3506+ }
3507+ if (o + 1 < sizeof(out)) out[o++] = sep;
3508+ size_t ml = strlen(meth);
3509+ if (o + ml < sizeof(out)) { memcpy(out + o, meth, ml); o += ml; }
3510+ out[o] = 0;
3511+ return strdup(out);
3512+}
3513+
3514+static sp_StrArray *sp_bt_format(void **buf, int n) {
3515+ sp_StrArray *a = sp_StrArray_new();
3516+ if (!sp_bt_enabled || n <= 0) return a;
3517+ char **syms = backtrace_symbols(buf, n);
3518+ if (!syms) return a;
3519+ const char *src = (sp_bt_srcfile && sp_bt_srcfile[0]) ? sp_bt_srcfile : "(spinel)";
3520+ for (int i = 0; i < n; i++) {
3521+ char *name = (char *)sp_bt_symbol(syms[i]); /* always strdup'd; free after use */
3522+ if (!name) continue;
3523+ sp_StrArray_push(a, sp_sprintf("%s:in `%s'", src, name));
3524+ free(name);
3525+ }
3526+ free(syms);
3527+ return a;
3528+}
3529+#endif
3530+
3531+/* Backtrace captured at the most recent raise (for Exception#backtrace). */
3532+static sp_StrArray *sp_backtrace_captured(void) {
3533+#if SP_BT_AVAILABLE
3534+ return sp_bt_format(sp_bt_buf, sp_bt_n);
3535+#else
3536+ return sp_StrArray_new();
3537+#endif
3538+}
3539+
3540+/* The current stack, captured now (for Kernel#caller). */
3541+static sp_StrArray *sp_caller_now(void) {
3542+#if SP_BT_AVAILABLE
3543+ if (!sp_bt_enabled) return sp_StrArray_new();
3544+ void *buf[256];
3545+ int n = backtrace(buf, 256);
3546+ return sp_bt_format(buf, n);
3547+#else
3548+ return sp_StrArray_new();
3549+#endif
3550+}
3551+
3552+void sp_raise_cls(const char *cls, const char *msg) {
3553+#if SP_BT_AVAILABLE
3554+ if (sp_bt_enabled) sp_bt_n = backtrace(sp_bt_buf, 256);
3555+#endif
3556+ 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); }
34023557 static void sp_raise(const char *msg) { sp_raise_cls("RuntimeError", msg); }
34033558
34043559 /* Issue #781: bridge between the regex compile-error path (which lives