8000 log: replace NUL bytes in a message instead of panicking by benface · Pull Request #685 · not-fl3/miniquad · GitHub
[go: up one dir, main page]

Skip to content
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
19 changes: 14 additions & 5 deletions src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,6 @@ pub fn __private_api_log_lit(
&(_target, _module_path, _file, _line): &(&str, &'static str, &'static str, u32),
) {
use crate::native::wasm;
use std::ffi::CString;

let log_fn = match level {
Level::Debug => wasm::console_debug,
Expand All @@ -203,7 +202,7 @@ pub fn __private_api_log_lit(
Level::Trace => wasm::console_debug,
Level::Error => wasm::console_error,
};
let msg = CString::new(message).unwrap_or_else(|_| panic!());
let msg = c_string(message);

unsafe { log_fn(msg.as_ptr()) };
}
Expand All @@ -214,20 +213,25 @@ pub fn __private_api_log_lit(
level: Level,
&(_target, _module_path, _file, _line): &(&str, &'static str, &'static str, u32),
) {
use std::ffi::CString;

let log_fn = match level {
Level::Debug => crate::native::android::console_debug,
Level::Warn => crate::native::android::console_warn,
Level::Info => crate::native::android::console_info,
Level::Trace => crate::native::android::console_debug,
Level::Error => crate::native::android::console_error,
};
let msg = CString::new(message).unwrap_or_else(|_| panic!());
let msg = c_string(message);

unsafe { log_fn(msg.as_ptr()) };
}

/// Android's log and the browser's console take C strings, which end at the
/// first NUL, so each NUL in `message` is replaced instead of panicking.
#[cfg(any(target_arch = "wasm32", target_os = "android", test))]
fn c_string(message: &str) -> std::ffi::CString {
std::ffi::CString::new(message.replace('\0', "\u{FFFD}")).unwrap()
}

#[cfg(target_os = "ios")]
pub fn __private_api_log_lit(
message: &str,
Expand All @@ -254,3 +258,8 @@ fn test_logs() {
error!("info");
error!("info: {}", 1);
}

#[test]
fn test_c_string_replaces_nul() {
assert_eq!(c_string("a\0b").to_str(), Ok("a\u{FFFD}b"));
}
Loading
0