Skip to content

Commit 7627081

Browse files
committed
std: Make logging safely implemented
This commit fixes the logging function to be safely implemented, as well as forcibly requiring a task to be present to use logging macros. This is safely implemented by transferring ownership of the logger from the task to the local stack frame in order to perform the print. This means that if a logger does more logging while logging a new one will be initialized and then will get overwritten once the initial logging function returns. Without a scheme such as this, it is possible to unsafely alias two loggers by logging twice (unsafely borrows from the task twice).
1 parent dd19785 commit 7627081

File tree

1 file changed

+11
-21
lines changed

1 file changed

+11
-21
lines changed

src/libstd/logging.rs

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -118,26 +118,16 @@ pub static ERROR: u32 = 1;
118118
/// It is not recommended to call this function directly, rather it should be
119119
/// invoked through the logging family of macros.
120120
pub fn log(_level: u32, args: &fmt::Arguments) {
121-
unsafe {
122-
let optional_task: Option<*mut Task> = Local::try_unsafe_borrow();
123-
match optional_task {
124-
Some(local) => {
125-
// Lazily initialize the local task's logger
126-
match (*local).logger {
127-
// Use the available logger if we have one
128-
Some(ref mut logger) => { logger.log(args); }
129-
None => {
130-
let mut logger = StdErrLogger::new();
131-
logger.log(args);
132-
(*local).logger = Some(logger);
133-
}
134-
}
135-
}
136-
// If there's no local task, then always log to stderr
137-
None => {
138-
let mut logger = StdErrLogger::new();
139-
logger.log(args);
140-
}
141-
}
121+
let mut logger = {
122+
let mut task = Local::borrow(None::<Task>);
123+
task.get().logger.take()
124+
};
125+
126+
if logger.is_none() {
127+
logger = Some(StdErrLogger::new());
142128
}
129+
logger.get_mut_ref().log(args);
130+
131+
let mut task = Local::borrow(None::<Task>);
132+
task.get().logger = logger;
143133
}

0 commit comments

Comments
 (0)