Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: increase snprintf safety #251

Merged
merged 1 commit into from
Jan 2, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading