Skip to content
Merged
Show file tree
Hide file tree
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
12 changes: 8 additions & 4 deletions src/libstd/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,10 +792,14 @@ fn print_to<T>(
{
let result = local_s
.try_with(|s| {
if let Ok(mut borrowed) = s.try_borrow_mut() {
if let Some(w) = borrowed.as_mut() {
return w.write_fmt(args);
}
// Note that we completely remove a local sink to write to in case
// our printing recursively panics/prints, so the recursive
// panic/print goes to the global sink instead of our local sink.
let prev = s.borrow_mut().take();
if let Some(mut w) = prev {
let result = w.write_fmt(args);
*s.borrow_mut() = Some(w);
return result;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to make sure I'm understanding correctly, the reason this does not need a try_borrow_mut anymore is because there's no possibility of a recursive lock, right? I believe the try_borrow was added in e2fd2df FWIW.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right yeah the scope of the borrow should always be one line of code which doesn't execute other arbitrary lines of code (e.g. an arbitrary Write implementation). As a result we should be guaranteed that it always succeeds.

}
global_s().write_fmt(args)
})
Expand Down
24 changes: 24 additions & 0 deletions src/test/ui/panic-while-printing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// run-pass
// ignore-emscripten no subprocess support

#![feature(set_stdio)]

use std::fmt;
use std::fmt::{Display, Formatter};
use std::io::set_panic;

pub struct A;

impl Display for A {
fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result {
panic!();
}
}

fn main() {
set_panic(Some(Box::new(Vec::new())));
assert!(std::panic::catch_unwind(|| {
eprintln!("{}", A);
})
.is_err());
}
24 changes: 24 additions & 0 deletions src/test/ui/test-panic-while-printing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// compile-flags:--test
// run-pass
// ignore-emscripten no subprocess support

use std::fmt;
use std::fmt::{Display, Formatter};

pub struct A(Vec<u32>);

impl Display for A {
fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result {
self.0[0];
Ok(())
}
}

#[test]
fn main() {
let result = std::panic::catch_unwind(|| {
let a = A(vec![]);
eprintln!("{}", a);
});
assert!(result.is_err());
}