Skip to content

Commit 30d0d18

Browse files
committed
Free existing buffers before re-init in BSON value classes
phongo_binary_init, phongo_regex_init, and phongo_javascript_init overwrote heap-owned struct members without freeing what was already there. Re-init the slots cleanly so a second call (e.g. from a subclass that invokes parent::__unserialize twice) does not leak the prior allocation. As part of this, hoist the regex flags null-byte check above the pattern allocation so a flag rejection can no longer leave a stray pattern buffer behind.
1 parent 18bfce9 commit 30d0d18

3 files changed

Lines changed: 25 additions & 4 deletions

File tree

src/BSON/Binary.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ static bool phongo_binary_init(phongo_binary_t* intern, const char* data, size_t
5151
return false;
5252
}
5353

54+
if (intern->data) {
55+
efree(intern->data);
56+
}
57+
5458
intern->data = estrndup(data, data_len);
5559
intern->data_len = data_len;
5660
intern->type = (uint8_t) type;

src/BSON/Javascript.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ static bool phongo_javascript_init(phongo_javascript_t* intern, const char* code
4040
return false;
4141
}
4242

43+
if (intern->code) {
44+
efree(intern->code);
45+
}
46+
if (intern->scope) {
47+
bson_destroy(intern->scope);
48+
intern->scope = NULL;
49+
}
50+
4351
intern->code = estrndup(code, code_len);
4452
intern->code_len = code_len;
4553

src/BSON/Regex.c

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,23 @@ static bool phongo_regex_init(phongo_regex_t* intern, const char* pattern, size_
4242
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Pattern cannot contain null bytes");
4343
return false;
4444
}
45+
46+
if (flags && strlen(flags) != (size_t) flags_len) {
47+
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Flags cannot contain null bytes");
48+
return false;
49+
}
50+
51+
if (intern->pattern) {
52+
efree(intern->pattern);
53+
}
54+
if (intern->flags) {
55+
efree(intern->flags);
56+
}
57+
4558
intern->pattern = estrndup(pattern, pattern_len);
4659
intern->pattern_len = pattern_len;
4760

4861
if (flags) {
49-
if (strlen(flags) != (size_t) flags_len) {
50-
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Flags cannot contain null bytes");
51-
return false;
52-
}
5362
intern->flags = estrndup(flags, flags_len);
5463
intern->flags_len = flags_len;
5564
/* Ensure flags are alphabetized upon initialization */

0 commit comments

Comments
 (0)