Skip to content

Commit

Permalink
utils: Move panic string logging to a separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
MarijnS95 committed Aug 4, 2023
1 parent 7b81320 commit 66701ee
Showing 1 changed file with 18 additions and 25 deletions.
43 changes: 18 additions & 25 deletions ndk/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,43 +29,36 @@ pub(crate) fn android_log(level: Level, tag: &CStr, msg: &CStr) {
}

pub(crate) fn log_panic(panic: Box<dyn std::any::Any + Send>) {
let rust_panic = unsafe { CStr::from_bytes_with_nul_unchecked(b"RustPanic\0") };
fn log_panic(panic_str: Option<&str>) {
const RUST_PANIC_TAG: &CStr =
unsafe { CStr::from_bytes_with_nul_unchecked(b"RustPanic\0") };
let panic_str = panic_str
.and_then(|panic_str| CString::new(panic_str).ok())
.unwrap_or_default();

// Use the Rust logger if installed and enabled, otherwise fall back to the Android system
// logger so there is at least some record of the panic
let use_log = log_enabled!(Level::Error);
// Use the Rust logger if installed and enabled, otherwise fall back to the Android system
// logger so there is at least some record of the panic
if log_enabled!(Level::Error) {
error!("RustPanic: {}", panic_str.to_string_lossy());
log::logger().flush();
} else {
android_log(Level::Error, RUST_PANIC_TAG, &panic_str);
}
}

match panic.downcast::<String>() {
Ok(panic_string) => {
if use_log {
error!("RustPanic: {}", panic_string);
} else if let Ok(msg) = CString::new(*panic_string) {
android_log(Level::Error, rust_panic, &msg);
}
log_panic(Some(&panic_string));
}
Err(panic) => match panic.downcast::<&str>() {
Ok(panic_str) => {
if use_log {
error!("RustPanic: {}", panic_str);
} else if let Ok(msg) = CString::new(*panic_str) {
android_log(Level::Error, rust_panic, &msg);
}
log_panic(Some(&panic_str));
}
Err(_) => {
if use_log {
error!("UnknownPanic");
} else {
let unknown_panic =
unsafe { CStr::from_bytes_with_nul_unchecked(b"UnknownPanic\0") };
android_log(Level::Error, unknown_panic, Default::default());
}
log_panic(Some("Unknown panic message type"));
}
},
}

if use_log {
log::logger().flush();
}
}

/// Run a closure and abort the program if it panics.
Expand Down

0 comments on commit 66701ee

Please sign in to comment.