1 // Copyright 2013 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.
11 //! Language-level runtime services that should reasonably expected
12 //! to be available 'everywhere'. Local heaps, GC, unwinding,
13 //! local storage, and logging. Even a 'freestanding' Rust would likely want
14 //! to implement this.
16 use super::local_heap::LocalHeap;
24 use libc::{c_void, uintptr_t, c_char, size_t};
26 use option::{Option, Some, None};
27 use rt::borrowck::BorrowRecord;
29 use rt::context::Context;
33 use rt::logging::StdErrLogger;
34 use rt::sched::{Scheduler, SchedHandle};
35 use rt::stack::{StackSegment, StackPool};
36 use send_str::SendStr;
38 use unstable::finally::Finally;
39 use unstable::mutex::Mutex;
41 // The Task struct represents all state associated with a rust
42 // task. There are at this point two primary "subtypes" of task,
43 // however instead of using a subtype we just have a "task_type" field
44 // in the struct. This contains a pointer to another struct that holds
45 // the type-specific state.
49 priv gc: GarbageCollector,
50 storage: LocalStorage,
51 logger: Option<StdErrLogger>,
55 name: Option<SendStr>,
56 coroutine: Option<Coroutine>,
57 sched: Option<~Scheduler>,
59 // Dynamic borrowck debugging info
60 borrow_list: Option<~[BorrowRecord]>,
61 stdout_handle: Option<~Writer>,
63 // See the comments in the scheduler about why this is necessary
64 nasty_deschedule_lock: Mutex,
68 GreenTask(Option<SchedHome>),
72 /// A coroutine is nothing more than a (register context, stack) pair.
73 pub struct Coroutine {
74 /// The segment of stack on which the task is currently running or
75 /// if the task is blocked, on which the task will resume
78 /// Servo needs this to be public in order to tell SpiderMonkey
79 /// about the stack bounds.
80 current_stack_segment: StackSegment,
81 /// Always valid if the task is alive and not running.
82 saved_context: Context
85 /// Some tasks have a dedicated home scheduler that they must run on.
91 pub struct GarbageCollector;
92 pub struct LocalStorage(Option<local_data::Map>);
100 fn result(&mut self) -> TaskResult {
102 Err(self.cause.take().unwrap())
111 // A helper to build a new task using the dynamically found
112 // scheduler and task. Only works in GreenTask context.
113 pub fn build_homed_child(stack_size: Option<uint>,
117 let mut running_task = Local::borrow(None::<Task>);
118 let mut sched = running_task.get().sched.take_unwrap();
119 let new_task = ~running_task.get()
120 .new_child_homed(&mut sched.stack_pool,
124 running_task.get().sched = Some(sched);
128 pub fn build_child(stack_size: Option<uint>, f: proc()) -> ~Task {
129 Task::build_homed_child(stack_size, f, AnySched)
132 pub fn build_homed_root(stack_size: Option<uint>,
136 let mut running_task = Local::borrow(None::<Task>);
137 let mut sched = running_task.get().sched.take_unwrap();
138 let new_task = ~Task::new_root_homed(&mut sched.stack_pool,
142 running_task.get().sched = Some(sched);
146 pub fn build_root(stack_size: Option<uint>, f: proc()) -> ~Task {
147 Task::build_homed_root(stack_size, f, AnySched)
150 pub fn new_sched_task() -> Task {
152 heap: LocalHeap::new(),
153 gc: GarbageCollector,
154 storage: LocalStorage(None),
156 unwinder: Unwinder { unwinding: false, cause: None },
159 coroutine: Some(Coroutine::empty()),
162 task_type: SchedTask,
165 nasty_deschedule_lock: unsafe { Mutex::new() },
169 pub fn new_root(stack_pool: &mut StackPool,
170 stack_size: Option<uint>,
171 start: proc()) -> Task {
172 Task::new_root_homed(stack_pool, stack_size, AnySched, start)
175 pub fn new_child(&mut self,
176 stack_pool: &mut StackPool,
177 stack_size: Option<uint>,
178 start: proc()) -> Task {
179 self.new_child_homed(stack_pool, stack_size, AnySched, start)
182 pub fn new_root_homed(stack_pool: &mut StackPool,
183 stack_size: Option<uint>,
185 start: proc()) -> Task {
187 heap: LocalHeap::new(),
188 gc: GarbageCollector,
189 storage: LocalStorage(None),
191 unwinder: Unwinder { unwinding: false, cause: None },
195 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
197 task_type: GreenTask(Some(home)),
200 nasty_deschedule_lock: unsafe { Mutex::new() },
204 pub fn new_child_homed(&mut self,
205 stack_pool: &mut StackPool,
206 stack_size: Option<uint>,
208 start: proc()) -> Task {
210 heap: LocalHeap::new(),
211 gc: GarbageCollector,
212 storage: LocalStorage(None),
214 unwinder: Unwinder { unwinding: false, cause: None },
218 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
220 task_type: GreenTask(Some(home)),
223 nasty_deschedule_lock: unsafe { Mutex::new() },
227 pub fn give_home(&mut self, new_home: SchedHome) {
228 match self.task_type {
229 GreenTask(ref mut home) => {
230 *home = Some(new_home);
233 rtabort!("type error: used SchedTask as GreenTask");
238 pub fn take_unwrap_home(&mut self) -> SchedHome {
239 match self.task_type {
240 GreenTask(ref mut home) => {
241 let out = home.take_unwrap();
245 rtabort!("type error: used SchedTask as GreenTask");
250 pub fn run(&mut self, f: ||) {
251 rtdebug!("run called on task: {}", borrow::to_uint(self));
253 // The only try/catch block in the world. Attempt to run the task's
254 // client-specified code and catch any failures.
255 self.unwinder.try(|| {
257 // Run the task main function, then do some cleanup.
260 // First, destroy task-local storage. This may run user dtors.
262 // FIXME #8302: Dear diary. I'm so tired and confused.
263 // There's some interaction in rustc between the box
264 // annihilator and the TLS dtor by which TLS is
265 // accessed from annihilated box dtors *after* TLS is
266 // destroyed. Somehow setting TLS back to null, as the
267 // old runtime did, makes this work, but I don't currently
268 // understand how. I would expect that, if the annihilator
269 // reinvokes TLS while TLS is uninitialized, that
270 // TLS would be reinitialized but never destroyed,
271 // but somehow this works. I have no idea what's going
272 // on but this seems to make things magically work. FML.
274 // (added after initial comment) A possible interaction here is
275 // that the destructors for the objects in TLS themselves invoke
276 // TLS, or possibly some destructors for those objects being
277 // annihilated invoke TLS. Sadly these two operations seemed to
278 // be intertwined, and miraculously work for now...
281 // Destroy remaining boxes. Also may run user dtors.
282 unsafe { cleanup::annihilate(); }
284 // Finally flush and destroy any output handles which the task
285 // owns. There are no boxes here, and no user destructors should
286 // run after this any more.
287 match self.stdout_handle.take() {
289 let mut handle = handle;
298 // Cleanup the dynamic borrowck debugging info
299 borrowck::clear_task_borrow_list();
301 self.death.collect_failure(self.unwinder.result());
302 self.destroyed = true;
305 // New utility functions for homes.
307 pub fn is_home_no_tls(&self, sched: &~Scheduler) -> bool {
308 match self.task_type {
309 GreenTask(Some(AnySched)) => { false }
310 GreenTask(Some(Sched(SchedHandle { sched_id: ref id, .. }))) => {
311 *id == sched.sched_id()
314 rtabort!("task without home");
318 rtabort!("type error: expected: GreenTask, found: SchedTask");
323 pub fn homed(&self) -> bool {
324 match self.task_type {
325 GreenTask(Some(AnySched)) => { false }
326 GreenTask(Some(Sched(SchedHandle { .. }))) => { true }
328 rtabort!("task without home");
331 rtabort!("type error: expected: GreenTask, found: SchedTask");
336 // Grab both the scheduler and the task from TLS and check if the
337 // task is executing on an appropriate scheduler.
338 pub fn on_appropriate_sched() -> bool {
339 let mut task = Local::borrow(None::<Task>);
340 let sched_id = task.get().sched.get_ref().sched_id();
341 let sched_run_anything = task.get().sched.get_ref().run_anything;
342 match task.get().task_type {
343 GreenTask(Some(AnySched)) => {
344 rtdebug!("anysched task in sched check ****");
347 GreenTask(Some(Sched(SchedHandle { sched_id: ref id, ..}))) => {
348 rtdebug!("homed task in sched check ****");
352 rtabort!("task without home");
355 rtabort!("type error: expected: GreenTask, found: SchedTask");
363 rtdebug!("called drop for a task: {}", borrow::to_uint(self));
364 rtassert!(self.destroyed);
366 unsafe { self.nasty_deschedule_lock.destroy(); }
370 // Coroutines represent nothing more than a context and a stack
375 pub fn new(stack_pool: &mut StackPool,
376 stack_size: Option<uint>,
379 let stack_size = match stack_size {
381 None => env::min_stack()
383 let start = Coroutine::build_start_wrapper(start);
384 let mut stack = stack_pool.take_segment(stack_size);
385 let initial_context = Context::new(start, &mut stack);
387 current_stack_segment: stack,
388 saved_context: initial_context
392 pub fn empty() -> Coroutine {
394 current_stack_segment: StackSegment::new(0),
395 saved_context: Context::empty()
399 fn build_start_wrapper(start: proc()) -> proc() {
400 let wrapper: proc() = proc() {
401 // First code after swap to this new context. Run our
405 // Again - might work while safe, or it might not.
407 let mut sched = Local::borrow(None::<Scheduler>);
408 sched.get().run_cleanup_job();
411 // To call the run method on a task we need a direct
412 // reference to it. The task is in TLS, so we can
413 // simply unsafe_borrow it to get this reference. We
414 // need to still have the task in TLS though, so we
415 // need to unsafe_borrow.
416 let task: *mut Task = Local::unsafe_borrow();
418 let mut start_cell = Some(start);
420 // N.B. Removing `start` from the start wrapper
421 // closure by emptying a cell is critical for
422 // correctness. The ~Task pointer, and in turn the
423 // closure used to initialize the first call
424 // frame, is destroyed in the scheduler context,
425 // not task context. So any captured closures must
426 // not contain user-definable dtors that expect to
427 // be in task context. By moving `start` out of
428 // the closure, all the user code goes our of
429 // scope while the task is still running.
430 let start = start_cell.take_unwrap();
435 // We remove the sched from the Task in TLS right now.
436 let sched: ~Scheduler = Local::take();
437 // ... allowing us to give it away when performing a
438 // scheduling operation.
439 sched.terminate_current_task()
444 /// Destroy coroutine and try to reuse stack segment.
445 pub fn recycle(self, stack_pool: &mut StackPool) {
447 Coroutine { current_stack_segment, .. } => {
448 stack_pool.give_segment(current_stack_segment);
456 // Just a sanity check to make sure we are catching a Rust-thrown exception
457 static UNWIND_TOKEN: uintptr_t = 839147;
460 pub fn try(&mut self, f: ||) {
461 use unstable::raw::Closure;
464 let closure: Closure = transmute(f);
465 let code = transmute(closure.code);
466 let env = transmute(closure.env);
468 let token = rust_try(try_fn, code, env);
469 assert!(token == 0 || token == UNWIND_TOKEN);
472 extern fn try_fn(code: *c_void, env: *c_void) {
474 let closure: Closure = Closure {
475 code: transmute(code),
478 let closure: || = transmute(closure);
484 fn rust_try(f: extern "C" fn(*c_void, *c_void),
486 data: *c_void) -> uintptr_t;
490 pub fn begin_unwind(&mut self, cause: ~Any) -> ! {
491 self.unwinding = true;
492 self.cause = Some(cause);
494 rust_begin_unwind(UNWIND_TOKEN);
495 return transmute(());
498 fn rust_begin_unwind(token: uintptr_t);
503 /// This function is invoked from rust's current __morestack function. Segmented
504 /// stacks are currently not enabled as segmented stacks, but rather one giant
505 /// stack segment. This means that whenever we run out of stack, we want to
506 /// truly consider it to be stack overflow rather than allocating a new stack.
507 #[no_mangle] // - this is called from C code
508 #[no_split_stack] // - it would be sad for this function to trigger __morestack
509 #[doc(hidden)] // - Function must be `pub` to get exported, but it's
510 // irrelevant for documentation purposes.
511 #[cfg(not(test))] // in testing, use the original libstd's version
512 pub extern "C" fn rust_stack_exhausted() {
514 use rt::in_green_task_context;
516 use rt::local::Local;
517 use unstable::intrinsics;
520 // We're calling this function because the stack just ran out. We need
521 // to call some other rust functions, but if we invoke the functions
522 // right now it'll just trigger this handler being called again. In
523 // order to alleviate this, we move the stack limit to be inside of the
524 // red zone that was allocated for exactly this reason.
525 let limit = context::get_sp_limit();
526 context::record_sp_limit(limit - context::RED_ZONE / 2);
528 // This probably isn't the best course of action. Ideally one would want
529 // to unwind the stack here instead of just aborting the entire process.
530 // This is a tricky problem, however. There's a few things which need to
533 // 1. We're here because of a stack overflow, yet unwinding will run
534 // destructors and hence arbitrary code. What if that code overflows
535 // the stack? One possibility is to use the above allocation of an
536 // extra 10k to hope that we don't hit the limit, and if we do then
537 // abort the whole program. Not the best, but kind of hard to deal
538 // with unless we want to switch stacks.
540 // 2. LLVM will optimize functions based on whether they can unwind or
541 // not. It will flag functions with 'nounwind' if it believes that
542 // the function cannot trigger unwinding, but if we do unwind on
543 // stack overflow then it means that we could unwind in any function
544 // anywhere. We would have to make sure that LLVM only places the
545 // nounwind flag on functions which don't call any other functions.
547 // 3. The function that overflowed may have owned arguments. These
548 // arguments need to have their destructors run, but we haven't even
549 // begun executing the function yet, so unwinding will not run the
550 // any landing pads for these functions. If this is ignored, then
551 // the arguments will just be leaked.
553 // Exactly what to do here is a very delicate topic, and is possibly
554 // still up in the air for what exactly to do. Some relevant issues:
556 // #3555 - out-of-stack failure leaks arguments
557 // #3695 - should there be a stack limit?
558 // #9855 - possible strategies which could be taken
559 // #9854 - unwinding on windows through __morestack has never worked
560 // #2361 - possible implementation of not using landing pads
562 if in_green_task_context() {
563 let mut task = Local::borrow(None::<Task>);
567 .map(|n| n.as_slice())
568 .unwrap_or("<unnamed>");
570 // See the message below for why this is not emitted to the
571 // task's logger. This has the additional conundrum of the
572 // logger may not be initialized just yet, meaning that an FFI
573 // call would happen to initialized it (calling out to libuv),
574 // and the FFI call needs 2MB of stack when we just ran out.
575 rterrln!("task '{}' has overflowed its stack", n);
577 rterrln!("stack overflow in non-task context");
584 /// This is the entry point of unwinding for things like lang items and such.
585 /// The arguments are normally generated by the compiler, and need to
586 /// have static lifetimes.
587 pub fn begin_unwind_raw(msg: *c_char, file: *c_char, line: size_t) -> ! {
592 fn static_char_ptr(p: *c_char) -> &'static str {
593 let s = unsafe { CString::new(p, false) };
595 Some(s) => unsafe { transmute::<&str, &'static str>(s) },
596 None => rtabort!("message wasn't utf8?")
600 let msg = static_char_ptr(msg);
601 let file = static_char_ptr(file);
603 begin_unwind(msg, file, line as uint)
606 /// This is the entry point of unwinding for fail!() and assert!().
607 pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) -> ! {
609 use rt::in_green_task_context;
610 use rt::local::Local;
613 use unstable::intrinsics;
617 // Note that this should be the only allocation performed in this block.
618 // Currently this means that fail!() on OOM will invoke this code path,
619 // but then again we're not really ready for failing on OOM anyway. If
620 // we do start doing this, then we should propagate this allocation to
621 // be performed in the parent of this task instead of the task that's
623 let msg = ~msg as ~Any;
626 //let msg: &Any = msg;
627 let msg_s = match msg.as_ref::<&'static str>() {
629 None => match msg.as_ref::<~str>() {
630 Some(s) => s.as_slice(),
635 if !in_green_task_context() {
636 rterrln!("failed in non-task context at '{}', {}:{}",
641 task = Local::unsafe_borrow();
642 let n = (*task).name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
644 // XXX: this should no get forcibly printed to the console, this should
645 // either be sent to the parent task (ideally), or get printed to
646 // the task's logger. Right now the logger is actually a uvio
647 // instance, which uses unkillable blocks internally for various
648 // reasons. This will cause serious trouble if the task is failing
649 // due to mismanagment of its own kill flag, so calling our own
650 // logger in its current state is a bit of a problem.
652 rterrln!("task '{}' failed at '{}', {}:{}", n, msg_s, file, line);
654 if (*task).unwinder.unwinding {
655 rtabort!("unwinding again");
659 (*task).unwinder.begin_unwind(msg);
671 do run_in_newsched_task() {
682 do run_in_newsched_task() {
683 local_data_key!(key: @~str)
684 local_data::set(key, @~"data");
685 assert!(*local_data::get(key, |k| k.map(|k| *k)).unwrap() == ~"data");
686 local_data_key!(key2: @~str)
687 local_data::set(key2, @~"data");
688 assert!(*local_data::get(key2, |k| k.map(|k| *k)).unwrap() == ~"data");
694 do run_in_newsched_task() {
695 let result = spawntask_try(proc()());
696 rtdebug!("trying first assert");
697 assert!(result.is_ok());
698 let result = spawntask_try(proc() fail!());
699 rtdebug!("trying second assert");
700 assert!(result.is_err());
706 do run_in_uv_task() {
707 use rand::{rng, Rng};
709 let _ = r.next_u32();
715 do run_in_uv_task() {
716 info!("here i am. logging in a newsched task");
722 do run_in_newsched_task() {
723 let (port, chan) = Chan::new();
725 assert!(port.recv() == 10);
730 fn comm_shared_chan() {
731 do run_in_newsched_task() {
732 let (port, chan) = SharedChan::new();
734 assert!(port.recv() == 10);
740 use option::{Option, Some, None};
742 do run_in_newsched_task {
744 next: Option<@mut List>,
747 let a = @mut List { next: None };
748 let b = @mut List { next: Some(a) };
756 fn test_begin_unwind() { begin_unwind("cause", file!(), line!()) }