Skip to content

Commit c9e7a96

Browse files
daviesrobwhitwham
authored andcommitted
Harden string pool allocation against overflow
Adjust test to see if the new allocation fits in the existing pool so that it works for very long lengths. Use hts_malloc() in case the caller used hts_alloc saturating arithmetic functions. Don't update string_alloc_t::max_length unless the malloc for the pool works. Signed-off-by: Rob Davies <rmd+git@sanger.ac.uk>
1 parent e68e30b commit c9e7a96

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

cram/string_alloc.c

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ string_alloc_t *string_pool_create(size_t max_length) {
7373

7474
/* internal function to do the actual memory allocation */
7575

76-
static string_t *new_string_pool(string_alloc_t *a_str) {
76+
static string_t *new_string_pool(string_alloc_t *a_str, size_t length) {
7777
string_t *str;
7878

7979
if (a_str->nstrings == a_str->max_strings) {
@@ -88,11 +88,15 @@ static string_t *new_string_pool(string_alloc_t *a_str) {
8888

8989
str = &a_str->strings[a_str->nstrings];
9090

91-
str->str = malloc(a_str->max_length);
91+
// increase the max length if needs be
92+
size_t new_length = length > a_str->max_length ? length : a_str->max_length;
93+
94+
str->str = hts_malloc(new_length);
9295

9396
if (NULL == str->str) return NULL;
9497

9598
str->used = 0;
99+
a_str->max_length = new_length;
96100
a_str->nstrings++;
97101

98102
return str;
@@ -125,18 +129,17 @@ char *string_alloc(string_alloc_t *a_str, size_t length) {
125129
if (a_str->nstrings) {
126130
str = &a_str->strings[a_str->nstrings - 1];
127131

128-
if (str->used + length < a_str->max_length) {
132+
if (length < a_str->max_length - str->used) {
129133
ret = str->str + str->used;
130134
str->used += length;
131135
return ret;
132136
}
133137
}
134138

135-
// increase the max length if needs be
136139
if (length > a_str->max_length) a_str->max_length = length;
137140

138141
// need a new string pool
139-
str = new_string_pool(a_str);
142+
str = new_string_pool(a_str, length);
140143

141144
if (NULL == str) return NULL;
142145

0 commit comments

Comments
 (0)