Skip to content

Commit

Permalink
Rollup merge of #128632 - joboet:dont_overwrite_style, r=Amanieu
Browse files Browse the repository at this point in the history
std: do not overwrite style in `get_backtrace_style`

If another thread calls `set_backtrace_style` while a `get_backtrace_style` is reading the environment variables, `get_backtrace_style` will overwrite the value. Use an atomic CAS to avoid this.
  • Loading branch information
GuillaumeGomez authored Aug 12, 2024
2 parents aea5087 + 8542cd6 commit aa6f240
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions library/std/src/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,13 +440,12 @@ impl BacktraceStyle {
}

fn from_u8(s: u8) -> Option<Self> {
Some(match s {
0 => return None,
1 => BacktraceStyle::Short,
2 => BacktraceStyle::Full,
3 => BacktraceStyle::Off,
_ => unreachable!(),
})
match s {
1 => Some(BacktraceStyle::Short),
2 => Some(BacktraceStyle::Full),
3 => Some(BacktraceStyle::Off),
_ => None,
}
}
}

Expand All @@ -465,7 +464,7 @@ static SHOULD_CAPTURE: AtomicU8 = AtomicU8::new(0);
pub fn set_backtrace_style(style: BacktraceStyle) {
if cfg!(feature = "backtrace") {
// If the `backtrace` feature of this crate is enabled, set the backtrace style.
SHOULD_CAPTURE.store(style.as_u8(), Ordering::Release);
SHOULD_CAPTURE.store(style.as_u8(), Ordering::Relaxed);
}
}

Expand Down Expand Up @@ -498,7 +497,9 @@ pub fn get_backtrace_style() -> Option<BacktraceStyle> {
// to optimize away callers.
return None;
}
if let Some(style) = BacktraceStyle::from_u8(SHOULD_CAPTURE.load(Ordering::Acquire)) {

let current = SHOULD_CAPTURE.load(Ordering::Relaxed);
if let Some(style) = BacktraceStyle::from_u8(current) {
return Some(style);
}

Expand All @@ -509,8 +510,11 @@ pub fn get_backtrace_style() -> Option<BacktraceStyle> {
None if crate::sys::FULL_BACKTRACE_DEFAULT => BacktraceStyle::Full,
None => BacktraceStyle::Off,
};
set_backtrace_style(format);
Some(format)

match SHOULD_CAPTURE.compare_exchange(0, format.as_u8(), Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => Some(format),
Err(new) => BacktraceStyle::from_u8(new),
}
}

#[cfg(test)]
Expand Down

0 comments on commit aa6f240

Please sign in to comment.