Fix val_mem_copy overflow bounds checking#41
Conversation
There was a problem hiding this comment.
Pull request overview
This PR enhances the val_mem_copy function to prevent buffer overflows by adding destination buffer size awareness. The function signature is updated to include a dest_size parameter, and the implementation now validates inputs and clamps the copy length to prevent writing beyond the destination buffer boundaries.
Key changes:
- Added
dest_sizeparameter toval_mem_copyfor bounds checking - Implemented input validation (null checks) and length clamping logic
- Updated the single call site in
val_common_log.cto pass the destination buffer size
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
inc/val_common_framework.h |
Updated function declaration to include dest_size parameter |
src/val_common_framework.c |
Added input validation, bounds checking, and length clamping to prevent buffer overflows |
src/val_common_log.c |
Updated call site to provide destination buffer size |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| return; | ||
|
|
||
| /* Clamp requested length so we never write beyond the destination buffer */ | ||
| size_t bytes_to_copy = len < dest_size ? len : dest_size; |
There was a problem hiding this comment.
The clamping logic should be len < dest_size ? len : dest_size - 1 to reserve space for null termination if dest is used as a string buffer. Without this, copying exactly dest_size bytes leaves no room for a null terminator, potentially causing issues in string operations. Alternatively, if this function is not meant for string copying, consider documenting that null termination is the caller's responsibility.
| val_mem_copy(formatted_msg, sizeof(formatted_msg), msg, len - 1); | ||
| formatted_msg[len - 1] = '\r'; | ||
| formatted_msg[len] = '\n'; | ||
| formatted_msg[len + 1] = '\0'; |
There was a problem hiding this comment.
After calling val_mem_copy with length len - 1, the code writes to indices len - 1, len, and len + 1 without verifying these indices are within formatted_msg bounds. If the clamping in val_mem_copy reduces bytes_to_copy due to buffer size constraints, these subsequent writes could still overflow the buffer. Consider checking the return value or ensuring len + 1 < sizeof(formatted_msg) before these writes.
Summary
Testing