1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use alloc::boxed::Box;
14 use any::{Any, AnyRefExt};
16 use io::{Writer, IoResult};
18 use option::{Some, None};
21 use rt::{Stderr, Stdio};
22 use rustrt::local::Local;
23 use rustrt::task::Task;
27 // Defined in this module instead of io::stdio so that the unwinding
28 local_data_key!(pub local_stderr: Box<Writer + Send>)
30 impl Writer for Stdio {
31 fn write(&mut self, bytes: &[u8]) -> IoResult<()> {
32 fn fmt_write<F: fmt::FormatWriter>(f: &mut F, bytes: &[u8]) {
33 let _ = f.write(bytes);
35 fmt_write(self, bytes);
40 pub fn on_fail(obj: &Any + Send, file: &'static str, line: uint) {
41 let msg = match obj.as_ref::<&'static str>() {
43 None => match obj.as_ref::<String>() {
44 Some(s) => s.as_slice(),
50 // It is assumed that all reasonable rust code will have a local task at
51 // all times. This means that this `exists` will return true almost all of
52 // the time. There are border cases, however, when the runtime has
53 // *almost* set up the local task, but hasn't quite gotten there yet. In
54 // order to get some better diagnostics, we print on failure and
55 // immediately abort the whole process if there is no local task
57 if !Local::exists(None::<Task>) {
58 let _ = writeln!(&mut err, "failed at '{}', {}:{}", msg, file, line);
59 if backtrace::log_enabled() {
60 let _ = backtrace::write(&mut err);
62 let _ = writeln!(&mut err, "run with `RUST_BACKTRACE=1` to \
68 // Peel the name out of local task so we can print it. We've got to be sure
69 // that the local task is in TLS while we're printing as I/O may occur.
70 let (name, unwinding) = {
71 let mut t = Local::borrow(None::<Task>);
72 (t.name.take(), t.unwinder.unwinding())
75 let n = name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
77 match local_stderr.replace(None) {
79 // FIXME: what to do when the task printing fails?
80 let _ = writeln!(stderr,
81 "task '{}' failed at '{}', {}:{}\n",
83 if backtrace::log_enabled() {
84 let _ = backtrace::write(stderr);
86 local_stderr.replace(Some(stderr));
89 let _ = writeln!(&mut err, "task '{}' failed at '{}', {}:{}",
91 if backtrace::log_enabled() {
92 let _ = backtrace::write(&mut err);
97 // If this is a double failure, make sure that we printed a backtrace
99 if unwinding && !backtrace::log_enabled() {
100 let _ = backtrace::write(&mut err);
103 Local::borrow(None::<Task>).name = name;