@@ -193,7 +193,7 @@ void sdsclear(sds s) {
193
193
*
194
194
* Note: this does not change the *length* of the sds string as returned
195
195
* by sdslen(), but only the free buffer space we have. */
196
- sds sdsMakeRoomFor (sds s , size_t addlen ) {
196
+ sds sdsMakeRoomFor (sds s , size_t addlen ) {
197
197
void * sh , * newsh ;
198
198
size_t avail = sdsavail (s );
199
199
size_t len , newlen ;
@@ -204,8 +204,12 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
204
204
if (avail >= addlen ) return s ;
205
205
206
206
len = sdslen (s );
207
- sh = (char * )s - sdsHdrSize (oldtype );
208
- newlen = (len + addlen );
207
+ sh = (char * )s - sdsHdrSize (oldtype );
208
+
209
+ /* Fix: Prevent Integer Overflow */
210
+ if (addlen > SIZE_MAX - len ) return NULL ; /* Prevent overflow */
211
+ newlen = len + addlen ;
212
+
209
213
if (newlen < SDS_MAX_PREALLOC )
210
214
newlen *= 2 ;
211
215
else
@@ -219,25 +223,34 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
219
223
if (type == SDS_TYPE_5 ) type = SDS_TYPE_8 ;
220
224
221
225
hdrlen = sdsHdrSize (type );
222
- if (oldtype == type ) {
223
- newsh = s_realloc (sh , hdrlen + newlen + 1 );
226
+
227
+ /* Fix: Ensure safe memory allocation */
228
+ if (hdrlen + newlen + 1 < newlen ) return NULL ; /* Prevent overflow */
229
+
230
+ if (oldtype == type ) {
231
+ newsh = s_realloc (sh , hdrlen + newlen + 1 );
224
232
if (newsh == NULL ) return NULL ;
225
- s = (char * )newsh + hdrlen ;
233
+ s = (char * )newsh + hdrlen ;
226
234
} else {
227
235
/* Since the header size changes, need to move the string forward,
228
236
* and can't use realloc */
229
- newsh = s_malloc (hdrlen + newlen + 1 );
237
+ newsh = s_malloc (hdrlen + newlen + 1 );
230
238
if (newsh == NULL ) return NULL ;
231
- memcpy ((char * )newsh + hdrlen , s , len + 1 );
239
+ memcpy ((char * )newsh + hdrlen , s , len + 1 );
232
240
s_free (sh );
233
- s = (char * )newsh + hdrlen ;
241
+ s = (char * )newsh + hdrlen ;
234
242
s [-1 ] = type ;
235
243
sdssetlen (s , len );
236
244
}
245
+
246
+ /* Fix: Prevent setting a too-large allocation */
247
+ if (newlen > sdsTypeMaxSize (type )) newlen = sdsTypeMaxSize (type );
237
248
sdssetalloc (s , newlen );
249
+
238
250
return s ;
239
251
}
240
252
253
+
241
254
/* Reallocate the sds string so that it has no free space at the end. The
242
255
* contained string remains not altered, but next concatenation operations
243
256
* will require a reallocation.
0 commit comments