Commit 5cbc5877

5cbc5877096dMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified

Description

Merge pull request #182 from mame/pr/file-basename-gc-fix

fix(runtime): sp_file_basename returns fresh sp_str_alloc'd copy

Details

Commit
5cbc5877096d
Parent
e31ca942bc7e
Merge parent
763b70e3abb6

lib/sp_runtime.hmodifiedView file

@@ -810,7 +810,19 @@
810810 static mrb_bool sp_file_exist(const char *path) { FILE *f = fopen(path, "r"); if (f) { fclose(f); return TRUE; } return FALSE; }
811811 static void sp_file_delete(const char *path) { remove(path); }
812812 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; }
813-static const char *sp_file_basename(const char *path) { const char *s = strrchr(path, '/'); if (s) return s + 1; return path; }
813+static const char *sp_file_basename(const char *path) {
814+ const char *s = strrchr(path, '/');
815+ const char *base = s ? s + 1 : path;
816+ /* sp_gc_mark looks at byte[-1] to distinguish heap strings (`\xfe`)
817+ from literals (`\xff`). A `s+1` mid-path pointer has whatever the
818+ '/' was before it — and for an arbitrary string that's not a tag,
819+ so the GC tries to dereference it as a heap header and segfaults.
820+ Return a fresh sp_str_alloc'd copy so the prefix marker is right. */
821+ size_t n = strlen(base);
822+ char *buf = sp_str_alloc(n);
823+ memcpy(buf, base, n + 1);
824+ return buf;
825+}
814826
815827 typedef struct sp_Proc { void *fn; void *cap; void (*cap_scan)(void *); } sp_Proc;
816828 static void sp_Proc_scan(void *p) { sp_Proc *pr = (sp_Proc *)p; if (pr->cap && pr->cap_scan) pr->cap_scan(pr->cap); }