Catch size_t overflows in sds.c

Equivalent changes introduced to redis sds.c via:
https://github.com/redis/redis/pull/8522
https://github.com/redis/redis/pull/9584
master
Björn Svensson 2022-02-01 14:48:42 +01:00
parent 066c6de79e
commit 64062a1d40
1 changed files with 5 additions and 2 deletions

7
sds.c
View File

@ -90,6 +90,7 @@ sds sdsnewlen(const void *init, size_t initlen) {
int hdrlen = sdsHdrSize(type); int hdrlen = sdsHdrSize(type);
unsigned char *fp; /* flags pointer. */ unsigned char *fp; /* flags pointer. */
assert(initlen + hdrlen + 1 > initlen); /* Catch size_t overflow */
sh = s_malloc(hdrlen+initlen+1); sh = s_malloc(hdrlen+initlen+1);
if (sh == NULL) return NULL; if (sh == NULL) return NULL;
if (!init) if (!init)
@ -196,7 +197,7 @@ void sdsclear(sds s) {
sds sdsMakeRoomFor(sds s, size_t addlen) { sds sdsMakeRoomFor(sds s, size_t addlen) {
void *sh, *newsh; void *sh, *newsh;
size_t avail = sdsavail(s); size_t avail = sdsavail(s);
size_t len, newlen; size_t len, newlen, reqlen;
char type, oldtype = s[-1] & SDS_TYPE_MASK; char type, oldtype = s[-1] & SDS_TYPE_MASK;
int hdrlen; int hdrlen;
@ -205,7 +206,8 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
len = sdslen(s); len = sdslen(s);
sh = (char*)s-sdsHdrSize(oldtype); sh = (char*)s-sdsHdrSize(oldtype);
newlen = (len+addlen); reqlen = newlen = (len+addlen);
assert(newlen > len); /* Catch size_t overflow */
if (newlen < SDS_MAX_PREALLOC) if (newlen < SDS_MAX_PREALLOC)
newlen *= 2; newlen *= 2;
else else
@ -219,6 +221,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
if (type == SDS_TYPE_5) type = SDS_TYPE_8; if (type == SDS_TYPE_5) type = SDS_TYPE_8;
hdrlen = sdsHdrSize(type); hdrlen = sdsHdrSize(type);
assert(hdrlen + newlen + 1 > reqlen); /* Catch size_t overflow */
if (oldtype==type) { if (oldtype==type) {
newsh = s_realloc(sh, hdrlen+newlen+1); newsh = s_realloc(sh, hdrlen+newlen+1);
if (newsh == NULL) return NULL; if (newsh == NULL) return NULL;