Skip to content

Commit e0b65de

Browse files
Alearner12claude
andcommitted
node: bounds-check and OOM-guard in cmark_set_cstr
cmark_set_cstr backs every cmark string setter (cmark_node_set_url, _set_title, _set_literal, _set_fence_info, _set_on_enter, _set_on_exit). This change closes two paths to undefined behaviour: 1. The realloc result is not checked. mem->realloc can return NULL via stdlib OOM or a caller-supplied allocator (cmark exposes the allocator through cmark_node_new_with_mem). The next line dereferences it, so failure is UB inside memcpy rather than a defined abort. 2. The bufsize_t cast of strlen silently truncates. bufsize_t is int32_t; for strlen(src) > INT32_MAX the cast wraps and subsequent len + 1 and memcpy operate on a truncated count. Both now abort() with a diagnostic, matching the existing precedent in cmark_strbuf_grow (src/buffer.c). Co-Authored-By: Claude <noreply@anthropic.com>
1 parent b320f40 commit e0b65de

1 file changed

Lines changed: 19 additions & 3 deletions

File tree

src/node.c

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
#include <stdbool.h>
2+
#include <stdint.h>
3+
#include <stdio.h>
24
#include <stdlib.h>
35
#include <string.h>
46

@@ -270,9 +272,23 @@ static bufsize_t cmark_set_cstr(cmark_mem *mem, unsigned char **dst,
270272
bufsize_t len;
271273

272274
if (src && src[0]) {
273-
len = (bufsize_t)strlen(src);
274-
*dst = (unsigned char *)mem->realloc(NULL, len + 1);
275-
memcpy(*dst, src, len + 1);
275+
size_t srclen = strlen(src);
276+
if (srclen > (size_t)(INT32_MAX - 1)) {
277+
fprintf(stderr,
278+
"[cmark] cmark_set_cstr: input exceeds %d bytes, aborting\n",
279+
INT32_MAX - 1);
280+
abort();
281+
}
282+
len = (bufsize_t)srclen;
283+
unsigned char *buf =
284+
(unsigned char *)mem->realloc(NULL, (size_t)len + 1);
285+
if (buf == NULL) {
286+
fprintf(stderr,
287+
"[cmark] cmark_set_cstr: allocator returned NULL, aborting\n");
288+
abort();
289+
}
290+
memcpy(buf, src, (size_t)len + 1);
291+
*dst = buf;
276292
} else {
277293
len = 0;
278294
*dst = NULL;

0 commit comments

Comments
 (0)