Skip to content

Commit 2d54c0e

Browse files
author
David LeBlanc
committed
Change integer overflow check to conform with spec
1 parent fadc615 commit 2d54c0e

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed

src/unpack.c

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -189,19 +189,17 @@ static inline int template_callback_false(unpack_user* u, msgpack_object* o)
189189

190190
static inline int template_callback_array(unpack_user* u, unsigned int n, msgpack_object* o)
191191
{
192-
unsigned int size;
193-
unsigned long long tmp;
192+
// Let's leverage the fact that sizeof(msgpack_object) is a compile time constant
193+
// to check for int overflows.
194+
// Note - while n is constrained to 32-bit, the product of n * sizeof(msgpack_object)
195+
// might not be constrained to 4GB on 64-bit systems
196+
if( n > SIZE_MAX/sizeof(msgpack_object))
197+
return MSGPACK_UNPACK_NOMEM_ERROR;
194198

195199
o->type = MSGPACK_OBJECT_ARRAY;
196200
o->via.array.size = 0;
197-
tmp = (unsigned long long)n * sizeof(msgpack_object);
198201

199-
if (tmp & 0xffffffff00000000) {
200-
// integer overflow
201-
return MSGPACK_UNPACK_NOMEM_ERROR;
202-
}
203-
204-
size = (unsigned int)tmp;
202+
size_t size = n * sizeof(msgpack_object);
205203

206204
if (*u->z == NULL) {
207205
*u->z = msgpack_zone_new(MSGPACK_ZONE_CHUNK_SIZE);
@@ -230,19 +228,18 @@ static inline int template_callback_array_item(unpack_user* u, msgpack_object* c
230228

231229
static inline int template_callback_map(unpack_user* u, unsigned int n, msgpack_object* o)
232230
{
233-
unsigned int size;
234-
unsigned long long tmp;
231+
// Let's leverage the fact that sizeof(msgpack_object_kv) is a compile time constant
232+
// to check for int overflows
233+
// Note - while n is constrained to 32-bit, the product of n * sizeof(msgpack_object)
234+
// might not be constrained to 4GB on 64-bit systems
235+
236+
if(n > SIZE_MAX/sizeof(msgpack_object_kv))
237+
return MSGPACK_UNPACK_NOMEM_ERROR;
235238

236239
o->type = MSGPACK_OBJECT_MAP;
237240
o->via.map.size = 0;
238-
tmp = (unsigned long long)n * sizeof(msgpack_object_kv);
239-
240-
if (tmp & 0xffffffff00000000) {
241-
// integer overflow
242-
return MSGPACK_UNPACK_NOMEM_ERROR;
243-
}
244241

245-
size = (unsigned int)tmp;
242+
size_t size = n * sizeof(msgpack_object_kv);
246243

247244
if (*u->z == NULL) {
248245
*u->z = msgpack_zone_new(MSGPACK_ZONE_CHUNK_SIZE);

0 commit comments

Comments
 (0)