Commit 45d970a6

45d970a66922Merged

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

Description

runtime: String#* raises ArgumentError on huge / negative multiplier

"x" * (1 << 60) segfaulted because the existing overflow check covered only the multiply, not the subsequent malloc-NULL + memcpy chain. Add a 1 GiB cap (well above realistic Ruby use, below typical 2-3 GiB process limits) that raises ArgumentError, and route negative multipliers through ArgumentError too.

Refs #836

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

Details

Commit
45d970a66922
Parent
83eaa3f24d02

lib/sp_runtime.hmodifiedView file

@@ -1636,7 +1636,22 @@
16361636 static mrb_int sp_str_count(const char*s,const char*chars){if(!chars)return 0;size_t setn;uint32_t*set=sp_utf8_decode_charset(chars,&setn);mrb_int c=0;const char*p=s;while(*p){uint32_t cp;p+=sp_utf8_decode(p,&cp);if(sp_utf8_set_has(set,setn,cp))c++;}free(set);return c;}
16371637 /* Issue #800: clamp l*n so a malicious input can't allocate a tiny
16381638 buffer through size_t overflow. */
1639-static const char*sp_str_repeat(const char*s,mrb_int n){if(!s||n<=0)return sp_str_empty;size_t l=strlen(s);if(l>0&&(size_t)n>SIZE_MAX/l)return sp_str_empty;char*r=sp_str_alloc_raw(l*n+1);for(mrb_int i=0;i<n;i++)memcpy(r+l*i,s,l);r[l*n]=0;return r;}
1639+/* Issue #836: bound the multiplier so a wildly oversized request
1640+ raises ArgumentError rather than segfaulting when malloc returns
1641+ NULL and memcpy walks it. 1 GiB cap covers realistic use. */
1642+static const char*sp_str_repeat(const char*s,mrb_int n){
1643+ if(n<0) sp_raise_cls("ArgumentError","negative argument");
1644+ if(!s||n<=0)return sp_str_empty;
1645+ size_t l=strlen(s);
1646+ if(l==0) return sp_str_empty;
1647+ if((size_t)n>SIZE_MAX/l) sp_raise_cls("ArgumentError","string size too big");
1648+ size_t total=(size_t)n*l;
1649+ if(total>(size_t)(1u<<30)) sp_raise_cls("ArgumentError","string size too big");
1650+ char*r=sp_str_alloc_raw(total+1);
1651+ for(mrb_int i=0;i<n;i++)memcpy(r+l*i,s,l);
1652+ r[total]=0;
1653+ return r;
1654+}
16401655 static sp_IntArray*sp_str_bytes(const char*s){sp_IntArray*a=sp_IntArray_new();if(!s)return a;size_t n=sp_str_byte_len(s);for(size_t i=0;i<n;i++)sp_IntArray_push(a,(mrb_int)(unsigned char)s[i]);return a;}
16411656 /* Issue #903: String#codepoints -- one IntArray entry per UTF-8
16421657 codepoint (not byte). Replacement-character behaviour mirrors