1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
From 7c34461863211be172e6317221d72e4429bed45e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Roberto=20C=2E=20S=C3=A1nchez?= <roberto@connexer.com>
Date: Fri, 3 May 2024 15:30:45 -0400
Subject: [PATCH] CDRIVER-5552 more robust string handling (#1593)
Co-authored-by: Kevin Albertson <kevin.albertson@10gen.com>
Origin: https://github.com/mongodb/mongo-c-driver/commit/7c34461863211be172e6317221d72e4429bed45e
---
src/libbson/src/bson/bson-string.c | 27 +++++++++++++++++++++------
1 file changed, 21 insertions(+), 6 deletions(-)
--- a/src/libbson/src/bson/bson-string.c
+++ b/src/libbson/src/bson/bson-string.c
@@ -20,6 +20,7 @@
#include "bson-compat.h"
#include "bson-config.h"
+#include "bson-cmp.h"
#include "bson-string.h"
#include "bson-memory.h"
#include "bson-utf8.h"
@@ -61,16 +62,25 @@
bson_string_new (const char *str) /* IN */
{
bson_string_t *ret;
+ size_t len_sz;
ret = bson_malloc0 (sizeof *ret);
- ret->len = str ? (int) strlen (str) : 0;
+ if (str) {
+ len_sz = strlen (str);
+ BSON_ASSERT (len_sz <= UINT32_MAX);
+ ret->len = (uint32_t) len_sz;
+ } else {
+ ret->len = 0;
+ }
ret->alloc = ret->len + 1;
if (!bson_is_power_of_two (ret->alloc)) {
- ret->alloc = (uint32_t) bson_next_power_of_two ((size_t) ret->alloc);
+ len_sz = bson_next_power_of_two ((size_t) ret->alloc);
+ BSON_ASSERT (len_sz <= UINT32_MAX);
+ ret->alloc = (uint32_t) len_sz;
}
- BSON_ASSERT (ret->alloc >= 1);
+ BSON_ASSERT (ret->alloc >= ret->len + 1);
ret->str = bson_malloc (ret->alloc);
@@ -125,17 +135,22 @@
const char *str) /* IN */
{
uint32_t len;
+ size_t len_sz;
BSON_ASSERT (string);
BSON_ASSERT (str);
- len = (uint32_t) strlen (str);
+ len_sz = strlen (str);
+ BSON_ASSERT (bson_in_range_unsigned (uint32_t, len_sz));
+ len = (uint32_t) len_sz;
if ((string->alloc - string->len - 1) < len) {
+ BSON_ASSERT (string->alloc <= UINT32_MAX - len);
string->alloc += len;
if (!bson_is_power_of_two (string->alloc)) {
- string->alloc =
- (uint32_t) bson_next_power_of_two ((size_t) string->alloc);
+ len_sz = bson_next_power_of_two ((size_t) string->alloc);
+ BSON_ASSERT (len_sz <= UINT32_MAX);
+ string->alloc = (uint32_t) len_sz;
}
string->str = bson_realloc (string->str, string->alloc);
}
|