Skip to content

Commit 7c34461

Browse files
CDRIVER-5552 more robust string handling (#1593)
Co-authored-by: Kevin Albertson <[email protected]>
1 parent adf78f2 commit 7c34461

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/libbson/src/bson/bson-string.c

+22-5
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
#include <bson/bson-compat.h>
2222
#include <bson/bson-config.h>
23+
#include <bson/bson-cmp.h>
2324
#include <bson/bson-string.h>
2425
#include <bson/bson-memory.h>
2526
#include <bson/bson-utf8.h>
@@ -61,16 +62,25 @@ bson_string_t *
6162
bson_string_new (const char *str) /* IN */
6263
{
6364
bson_string_t *ret;
65+
size_t len_sz;
6466

6567
ret = bson_malloc0 (sizeof *ret);
66-
ret->len = str ? (int) strlen (str) : 0;
68+
if (str) {
69+
len_sz = strlen (str);
70+
BSON_ASSERT (len_sz <= UINT32_MAX);
71+
ret->len = (uint32_t) len_sz;
72+
} else {
73+
ret->len = 0;
74+
}
6775
ret->alloc = ret->len + 1;
6876

6977
if (!bson_is_power_of_two (ret->alloc)) {
70-
ret->alloc = (uint32_t) bson_next_power_of_two ((size_t) ret->alloc);
78+
len_sz = bson_next_power_of_two ((size_t) ret->alloc);
79+
BSON_ASSERT (len_sz <= UINT32_MAX);
80+
ret->alloc = (uint32_t) len_sz;
7181
}
7282

73-
BSON_ASSERT (ret->alloc >= 1);
83+
BSON_ASSERT (ret->alloc >= ret->len + 1);
7484

7585
ret->str = bson_malloc (ret->alloc);
7686

@@ -126,17 +136,24 @@ bson_string_append (bson_string_t *string, /* IN */
126136
const char *str) /* IN */
127137
{
128138
uint32_t len;
139+
size_t len_sz;
129140

130141
BSON_ASSERT (string);
131142
BSON_ASSERT (str);
132143

133-
len = (uint32_t) strlen (str);
144+
len_sz = strlen (str);
145+
BSON_ASSERT (bson_in_range_unsigned (uint32_t, len_sz));
146+
len = (uint32_t) len_sz;
134147

135148
if ((string->alloc - string->len - 1) < len) {
149+
BSON_ASSERT (string->alloc <= UINT32_MAX - len);
136150
string->alloc += len;
137151
if (!bson_is_power_of_two (string->alloc)) {
138-
string->alloc = (uint32_t) bson_next_power_of_two ((size_t) string->alloc);
152+
len_sz = bson_next_power_of_two ((size_t) string->alloc);
153+
BSON_ASSERT (len_sz <= UINT32_MAX);
154+
string->alloc = (uint32_t) len_sz;
139155
}
156+
BSON_ASSERT (string->alloc >= string->len + len);
140157
string->str = bson_realloc (string->str, string->alloc);
141158
}
142159

0 commit comments

Comments
 (0)