Skip to content

Commit 5ad1728

Browse files
committed
test: increase snprintf safety
Detected by CodeQL scanning; only in test harness, not used in main codebase. Signed-off-by: Robin H. Johnson <[email protected]>
1 parent f60e47c commit 5ad1728

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

test/print_safe_buffer.c

+18-7
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,30 @@ void print_safe_buffer(struct safe_buffer const *sb)
1515
size_t snprint_safe_buffer(char *s, size_t size, struct safe_buffer const *sb)
1616
{
1717
size_t count = 0;
18+
int n;
1819

19-
count += snprintf((s + count), (size - count), "unsigned char expected[] = { /* sb.allocated = %ld, sb.used = %ld */", sb->allocated, sb->used);
20+
n = snprintf((s + count), (size - count), "unsigned char expected[] = { /* sb.allocated = %ld, sb.used = %ld */", sb->allocated, sb->used);
21+
if (n < 0 || n >= size - count) {
22+
return count;
23+
}
24+
count += n;
2025

26+
char* nextline = "\n\t";
27+
char* nextbyte = " ";
2128
for (size_t i = 0; i < sb->used; ++i) {
22-
if (i % 8 == 0) {
23-
count += snprintf((s + count), (size - count), "\n\t0x%02x,", sb->buffer[i]);
24-
} else {
25-
count += snprintf((s + count), (size - count), " 0x%02x,", sb->buffer[i]);
29+
char* nextspace = (i % 8 == 0) ? nextline : nextbyte;
30+
n = snprintf((s + count), (size - count), "%s0x%02x,", nextspace, sb->buffer[i]);
31+
if (n < 0 || n >= size - count) {
32+
return count;
2633
}
34+
count += n;
2735
}
2836
/* Do not remove the final byte's comma. Only JSON requires the comma is
2937
* removed, and this is not JSON. */
30-
31-
count += snprintf((s + count), (size - count), "\n};\n");
38+
n = snprintf((s + count), (size - count), "\n};\n");
39+
if (n < 0 || n >= size - count) {
40+
return count;
41+
}
42+
count += n;
3243
return count;
3344
}

0 commit comments

Comments
 (0)