Commit 763b70e3
763b70e3abb6Merged
Yusuke Endoh <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified
Description
fix(runtime): sp_file_basename returns fresh sp_str_alloc'd copy
sp_gc_mark distinguishes heap-allocated strings (prefix byte
\xfe) from string literals (\xff) by reading byte[-1] of
the pointer. The previous sp_file_basename returned a mid-path
pointer (s + 1 where s was the last /), so byte[-1]
was whatever the / was before it — a path character, not a
tag. The GC then tried to dereference that byte as a heap header
and segfaulted on inputs the basename helper had touched.
Fix: copy the basename into a fresh sp_str_alloc'd buffer so
the byte[-1] tag is well-defined.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 763b70e3abb6
- Parent
- a09a6b8b339b
lib/sp_runtime.hmodifiedView file
@@ -781,7 +781,19 @@
781781
static mrb_bool sp_file_exist(const char *path) { FILE *f = fopen(path, "r"); if (f) { fclose(f); return TRUE; } return FALSE; }782782
static void sp_file_delete(const char *path) { remove(path); }783783
static const char *sp_backtick(const char *cmd) { FILE *p = popen(cmd, "r"); if (!p) return sp_str_empty; char *buf = sp_str_alloc_raw(4096); size_t n = fread(buf, 1, 4095, p); buf[n] = 0; pclose(p); return buf; }784-
static const char *sp_file_basename(const char *path) { const char *s = strrchr(path, '/'); if (s) return s + 1; return path; }784+
static const char *sp_file_basename(const char *path) {785+
const char *s = strrchr(path, '/');786+
const char *base = s ? s + 1 : path;787+
/* sp_gc_mark looks at byte[-1] to distinguish heap strings (`\xfe`)788+
from literals (`\xff`). A `s+1` mid-path pointer has whatever the789+
'/' was before it — and for an arbitrary string that's not a tag,790+
so the GC tries to dereference it as a heap header and segfaults.791+
Return a fresh sp_str_alloc'd copy so the prefix marker is right. */792+
size_t n = strlen(base);793+
char *buf = sp_str_alloc(n);794+
memcpy(buf, base, n + 1);795+
return buf;796+
}785797
786798
typedef struct sp_Proc { void *fn; void *cap; void (*cap_scan)(void *); } sp_Proc;787799
static void sp_Proc_scan(void *p) { sp_Proc *pr = (sp_Proc *)p; if (pr->cap && pr->cap_scan) pr->cap_scan(pr->cap); }test/file_basename_gc.rbaddedView file
Loading diff…