Skip to content

Commit

Permalink
Adding Rust-specific support (chatdbg crate).
Browse files Browse the repository at this point in the history
  • Loading branch information
emeryberger committed Oct 1, 2023
1 parent 031d94a commit 5cb016a
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
14 changes: 14 additions & 0 deletions rust-support/chatdbg/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "chatdbg"
version = "0.1.0"
edition = "2021"
description = "Rust-specific support for ChatDBG (https://github.com/plasma-umass/chatdbg)."
authors = ["Emery Berger <[email protected]>"]
license = "Apache 2.0"
readme = "https://github.com/plasma-umass/ChatDBG/README.md"
homepage = "https://github.com/plasma-umass/ChatDBG/"
repository = "https://github.com/plasma-umass/ChatDBG/"

[dependencies]
lazy_static = "1.4.0"

52 changes: 52 additions & 0 deletions rust-support/chatdbg/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::io;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::panic;
use std::sync::{Mutex, atomic::{AtomicBool, Ordering}};
use std::thread;

// Global Mutex to synchronize file writes across threads.
lazy_static::lazy_static! {
static ref FILE_MUTEX: Mutex<()> = Mutex::new(());
static ref FILE_CREATED: AtomicBool = AtomicBool::new(false);
}

pub fn chatdbg() {
// Set a custom panic hook.
panic::set_hook(Box::new(|info| {
let _guard = FILE_MUTEX.lock().unwrap(); // Lock Mutex to synchronize access.

// Format the panic message similarly to the default panic handler.
let payload = if let Some(s) = info.payload().downcast_ref::<&str>() {
*s
} else {
"Box<Any>"
};

let location = if let Some(location) = info.location() {
format!(" at '{}' line {}", location.file(), location.line())
} else {
String::from("")
};

let message = format!("thread '{}' panicked with '{}'{}", thread::current().name().unwrap_or("<unnamed>"), payload, location);

// Print to stderr.
eprintln!("{}", message);

// Specify the filename without including the process id.
let filename = "panic_log.txt";

// Open the file with appropriate options.
let mut file = if FILE_CREATED.swap(true, Ordering::SeqCst) {
// If the file is already created by another thread, open it in append mode.
OpenOptions::new().create(true).append(true).open(filename).expect("Unable to open file")
} else {
// If this is the first thread to create the file, overwrite any existing file.
File::create(filename).expect("Unable to create file")
};

// Write to the file.
writeln!(file, "{}", message).expect("Unable to write to file");
}));
}

0 comments on commit 5cb016a

Please sign in to comment.