Commit b43af507
b43af50740fbMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
Raise TypeError for StringIO.new(nil)
StringIO.new(nil) compiled to sp_StringIO_new_s(NULL), which ran
strlen(NULL) (the C compiler even warned -Wnonnull) and would segfault.
CRuby rejects a nil initial string with TypeError ("no implicit conversion of nil into String"); the issue's "null device" framing is incorrect. Guard the NULL init in sp_StringIO_new_s and raise the same TypeError, matching CRuby and the existing nil-arg guards in sp_str_include / sp_str_ord. Runtime-only; no bootstrap.
StringIO.new(nil) # => TypeError (was: strlen(NULL) segfault)
Fixes #1137
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- b43af50740fb
- Parent
- 0f937b6405e9
lib/sp_runtime.hmodifiedView file
@@ -3768,7 +3768,7 @@
37683768
static void sio_grow(sp_StringIO *sio, int64_t need) { int64_t req = sio->pos + need; if (req <= sio->cap) return; int64_t nc = sio->cap ? sio->cap : 64; while (nc < req) nc *= 2; sio->buf = (char *)realloc(sio->buf, nc + 1); sio->cap = nc; }37693769
static int64_t sio_write(sp_StringIO *sio, const char *d, int64_t dl) { sio_grow(sio, dl); if (sio->pos > sio->len) memset(sio->buf + sio->len, 0, sio->pos - sio->len); memcpy(sio->buf + sio->pos, d, dl); sio->pos += dl; if (sio->pos > sio->len) sio->len = sio->pos; sio->buf[sio->len] = '\0'; return dl; }37703770
static sp_StringIO *sp_StringIO_new(void) { sp_StringIO *s = (sp_StringIO *)calloc(1, sizeof(sp_StringIO)); s->buf = (char *)calloc(1, 64); s->cap = 63; return s; }3771-
static sp_StringIO *sp_StringIO_new_s(const char *init) { sp_StringIO *s = (sp_StringIO *)calloc(1, sizeof(sp_StringIO)); int64_t l = (int64_t)strlen(init); int64_t c = l < 63 ? 63 : l; s->buf = (char*)malloc(c+1); memcpy(s->buf, init, l); s->buf[l]='\0'; s->len = l; s->cap = c; return s; }3771+
static sp_StringIO *sp_StringIO_new_s(const char *init) { if (!init) sp_raise_cls("TypeError", "no implicit conversion of nil into String"); sp_StringIO *s = (sp_StringIO *)calloc(1, sizeof(sp_StringIO)); int64_t l = (int64_t)strlen(init); int64_t c = l < 63 ? 63 : l; s->buf = (char*)malloc(c+1); memcpy(s->buf, init, l); s->buf[l]='\0'; s->len = l; s->cap = c; return s; }37723772
static const char *sp_StringIO_string(sp_StringIO *s) { return s->buf ? s->buf : sp_str_empty; }37733773
static int64_t sp_StringIO_pos(sp_StringIO *s) { return s->pos; }37743774
static int64_t sp_StringIO_size(sp_StringIO *s) { return s->len; }test/stringio_new_nil.rbaddedView file
Loading diff…
test/stringio_new_nil.rb.expectedaddedView file
Loading diff…