Commit 1e67c6df

1e67c6df7599Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(runtime): sp_utf8_decode_all checks malloc/realloc (#762)

On OOM, the initial malloc could return NULL and the decoder would then dereference it. realloc inside the loop had the same issue (it would overwrite the existing cps pointer with NULL, leaking the old buffer too).

Now: check malloc; return NULL with *out_n = 0 if it fails. Inside the loop, realloc through a temp; on failure, free the existing buffer and return NULL. Also guard against NULL s (was a latent bug -- the existing callers always pass non-NULL, but the guard is cheap insurance for new ones).

Closes #762

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

Details

Commit
1e67c6df7599
Parent
62b1437b1c78

lib/sp_runtime.hmodifiedView file

@@ -530,7 +530,9 @@
530530 if (p > end) p = end;
531531 return (size_t)(p - s);
532532 }
533-static uint32_t*sp_utf8_decode_all(const char*s,size_t*out_n){size_t cap=8,n=0;uint32_t*cps=(uint32_t*)malloc(cap*sizeof(uint32_t));const char*p=s;while(*p){if(n>=cap){cap*=2;cps=(uint32_t*)realloc(cps,cap*sizeof(uint32_t));}uint32_t cp;p+=sp_utf8_decode(p,&cp);cps[n++]=cp;}*out_n=n;return cps;}
533+/* Issue #762: check malloc/realloc returns. On OOM, return an empty
534+ array rather than dereferencing NULL. */
535+static uint32_t*sp_utf8_decode_all(const char*s,size_t*out_n){size_t cap=8,n=0;uint32_t*cps=(uint32_t*)malloc(cap*sizeof(uint32_t));if(!cps){*out_n=0;return NULL;}const char*p=s;while(s&&*p){if(n>=cap){size_t nc=cap*2;uint32_t*nx=(uint32_t*)realloc(cps,nc*sizeof(uint32_t));if(!nx){free(cps);*out_n=0;return NULL;}cps=nx;cap=nc;}uint32_t cp;p+=sp_utf8_decode(p,&cp);cps[n++]=cp;}*out_n=n;return cps;}
534536 static int sp_utf8_set_has(const uint32_t*cps,size_t n,uint32_t cp){for(size_t i=0;i<n;i++)if(cps[i]==cp)return 1;return 0;}
535537
536538 static inline void sp_mark_string(const char *s) {