Skip to content

Avoid panic on buffers with embedded nul bytes #90

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
24 changes: 22 additions & 2 deletions src/platform_log_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl PlatformLogWriter<'_> {
/// Output buffer up until the \0 which will be placed at `len` position.
///
/// # Safety
/// The first `len` bytes of `self.buffer` must be initialized.
/// The first `len` bytes of `self.buffer` must be initialized and not contain nullbytes.
unsafe fn output_specified_len(&mut self, len: usize) {
let mut last_byte = MaybeUninit::new(b'\0');

Expand Down Expand Up @@ -152,7 +152,13 @@ impl fmt::Write for PlatformLogWriter<'_> {
.zip(incoming_bytes)
.enumerate()
.fold(None, |acc, (i, (output, input))| {
output.write(*input);
if *input == b'\0' {
// Replace nullbytes with whitespace, so we can put the message in a CStr
// later to pass it through a const char*.
output.write(b' ');
} else {
output.write(*input);
}
if *input == b'\n' { Some(i) } else { acc }
});

Expand Down Expand Up @@ -297,6 +303,20 @@ pub mod tests {
);
}

#[test]
fn writer_substitutes_nullbytes_with_spaces() {
let test_string = "Test_string_with\0\0\0\0nullbytes\0";
let mut writer = get_tag_writer();
writer
.write_str(test_string)
.expect("Unable to write to PlatformLogWriter");

assert_eq!(
unsafe { slice_assume_init_ref(&writer.buffer[..test_string.len()]) },
test_string.replace("\0", " ").as_bytes()
);
}

fn get_tag_writer() -> PlatformLogWriter<'static> {
PlatformLogWriter::new(
None,
Expand Down