Skip to content

Commit

Permalink
Merge pull request #251 from radvd-project/robbat2/20250102-snprintf
Browse files Browse the repository at this point in the history
test: increase snprintf safety
  • Loading branch information
robbat2 authored Jan 2, 2025
2 parents f4d1568 + 5ad1728 commit 5ef8642
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions test/print_safe_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,30 @@ void print_safe_buffer(struct safe_buffer const *sb)
size_t snprint_safe_buffer(char *s, size_t size, struct safe_buffer const *sb)
{
size_t count = 0;
int n;

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

char* nextline = "\n\t";
char* nextbyte = " ";
for (size_t i = 0; i < sb->used; ++i) {
if (i % 8 == 0) {
count += snprintf((s + count), (size - count), "\n\t0x%02x,", sb->buffer[i]);
} else {
count += snprintf((s + count), (size - count), " 0x%02x,", sb->buffer[i]);
char* nextspace = (i % 8 == 0) ? nextline : nextbyte;
n = snprintf((s + count), (size - count), "%s0x%02x,", nextspace, sb->buffer[i]);
if (n < 0 || n >= size - count) {
return count;
}
count += n;
}
/* Do not remove the final byte's comma. Only JSON requires the comma is
* removed, and this is not JSON. */

count += snprintf((s + count), (size - count), "\n};\n");
n = snprintf((s + count), (size - count), "\n};\n");
if (n < 0 || n >= size - count) {
return count;
}
count += n;
return count;
}

0 comments on commit 5ef8642

Please sign in to comment.