File tree Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Original file line number Diff line number Diff line change 11/*
22 * MIT License
33 *
4- * Copyright (c) 2019 Tskit Developers
4+ * Copyright (c) 2019-2021 Tskit Developers
55 *
66 * Permission is hereby granted, free of charge, to any person obtaining a copy
77 * of this software and associated documentation files (the "Software"), to deal
@@ -358,6 +358,19 @@ test_malloc_zero(void)
358358 free (p );
359359}
360360
361+ static void
362+ test_malloc_overflow (void )
363+ {
364+ #if TSK_MAX_SIZE > SIZE_MAX
365+ tsk_size_t size_max = SIZE_MAX ;
366+ void * p = tsk_malloc (size_max + 1 );
367+ CU_ASSERT_FATAL (p == NULL );
368+
369+ p = tsk_calloc (size_max + 1 , 1 );
370+ CU_ASSERT_FATAL (p == NULL );
371+ #endif
372+ }
373+
361374int
362375main (int argc , char * * argv )
363376{
@@ -369,6 +382,7 @@ main(int argc, char **argv)
369382 { "test_blkalloc" , test_blkalloc },
370383 { "test_unknown_time" , test_unknown_time },
371384 { "test_malloc_zero" , test_malloc_zero },
385+ { "test_malloc_overflow" , test_malloc_overflow },
372386 { NULL , NULL },
373387 };
374388
Original file line number Diff line number Diff line change @@ -717,9 +717,11 @@ tsk_malloc(tsk_size_t size)
717717 if (size == 0 ) {
718718 size = 1 ;
719719 }
720- /* TODO
721- * 1. check if size > SIZE_MAX on 32 bit
722- */
720+ #if TSK_MAX_SIZE > SIZE_MAX
721+ if (size > SIZE_MAX ) {
722+ return NULL ;
723+ }
724+ #endif
723725 return malloc ((size_t ) size );
724726}
725727
@@ -731,13 +733,23 @@ tsk_realloc(void *ptr, tsk_size_t size)
731733 return realloc (ptr , (size_t ) size );
732734}
733735
736+ /* We keep the size argument here as a size_t because we'd have to
737+ * cast the outputs of sizeof() otherwise, which would lead to
738+ * less readable code. We need to be careful to use calloc within
739+ * the library accordingly, so that size can't overflow on 32 bit.
740+ */
734741void *
735742tsk_calloc (tsk_size_t n , size_t size )
736743{
737744 /* Avoid calloc(0) as it's not portable */
738745 if (n == 0 ) {
739746 n = 1 ;
740747 }
748+ #if TSK_MAX_SIZE > SIZE_MAX
749+ if (n > SIZE_MAX ) {
750+ return NULL ;
751+ }
752+ #endif
741753 return calloc ((size_t ) n , size );
742754}
743755
You can’t perform that action at this time.
0 commit comments