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;
35 use rt::logging::StdErrLogger;
36 use rt::sched::{Scheduler, SchedHandle};
37 use rt::stack::{StackSegment, StackPool};
38 use send_str::SendStr;
39 use unstable::finally::Finally;
40 use unstable::mutex::Mutex;
42 // The Task struct represents all state associated with a rust
43 // task. There are at this point two primary "subtypes" of task,
44 // however instead of using a subtype we just have a "task_type" field
45 // in the struct. This contains a pointer to another struct that holds
46 // the type-specific state.
50 priv gc: GarbageCollector,
51 storage: LocalStorage,
52 logger: Option<StdErrLogger>,
56 name: Option<SendStr>,
57 coroutine: Option<Coroutine>,
58 sched: Option<~Scheduler>,
60 // Dynamic borrowck debugging info
61 borrow_list: Option<~[BorrowRecord]>,
62 stdout_handle: Option<~Writer>,
64 // See the comments in the scheduler about why this is necessary
65 nasty_deschedule_lock: Mutex,
69 GreenTask(Option<SchedHome>),
73 /// A coroutine is nothing more than a (register context, stack) pair.
74 pub struct Coroutine {
75 /// The segment of stack on which the task is currently running or
76 /// if the task is blocked, on which the task will resume
79 /// Servo needs this to be public in order to tell SpiderMonkey
80 /// about the stack bounds.
81 current_stack_segment: StackSegment,
82 /// Always valid if the task is alive and not running.
83 saved_context: Context
86 /// Some tasks have a dedicated home scheduler that they must run on.
92 pub struct GarbageCollector;
93 pub struct LocalStorage(Option<local_data::Map>);
95 /// Represents the reason for the current unwinding process
96 pub enum UnwindResult {
97 /// The task is ending successfully
100 /// The Task is failing with reason `~Any`
105 /// Returns `true` if this `UnwindResult` is a failure
107 pub fn is_failure(&self) -> bool {
114 /// Returns `true` if this `UnwindResult` is a success
116 pub fn is_success(&self) -> bool {
124 pub struct Unwinder {
130 fn to_unwind_result(&mut self) -> UnwindResult {
132 Failure(self.cause.take().unwrap())
141 // A helper to build a new task using the dynamically found
142 // scheduler and task. Only works in GreenTask context.
143 pub fn build_homed_child(stack_size: Option<uint>,
147 let f = Cell::new(f);
148 let home = Cell::new(home);
149 Local::borrow(|running_task: &mut Task| {
150 let mut sched = running_task.sched.take_unwrap();
151 let new_task = ~running_task.new_child_homed(&mut sched.stack_pool,
155 running_task.sched = Some(sched);
160 pub fn build_child(stack_size: Option<uint>, f: proc()) -> ~Task {
161 Task::build_homed_child(stack_size, f, AnySched)
164 pub fn build_homed_root(stack_size: Option<uint>,
168 let f = Cell::new(f);
169 let home = Cell::new(home);
170 Local::borrow(|running_task: &mut Task| {
171 let mut sched = running_task.sched.take_unwrap();
172 let new_task = ~Task::new_root_homed(&mut sched.stack_pool,
176 running_task.sched = Some(sched);
181 pub fn build_root(stack_size: Option<uint>, f: proc()) -> ~Task {
182 Task::build_homed_root(stack_size, f, AnySched)
185 pub fn new_sched_task() -> Task {
187 heap: LocalHeap::new(),
188 gc: GarbageCollector,
189 storage: LocalStorage(None),
191 unwinder: Unwinder { unwinding: false, cause: None },
194 coroutine: Some(Coroutine::empty()),
197 task_type: SchedTask,
200 nasty_deschedule_lock: unsafe { Mutex::new() },
204 pub fn new_root(stack_pool: &mut StackPool,
205 stack_size: Option<uint>,
206 start: proc()) -> Task {
207 Task::new_root_homed(stack_pool, stack_size, AnySched, start)
210 pub fn new_child(&mut self,
211 stack_pool: &mut StackPool,
212 stack_size: Option<uint>,
213 start: proc()) -> Task {
214 self.new_child_homed(stack_pool, stack_size, AnySched, start)
217 pub fn new_root_homed(stack_pool: &mut StackPool,
218 stack_size: Option<uint>,
220 start: proc()) -> Task {
222 heap: LocalHeap::new(),
223 gc: GarbageCollector,
224 storage: LocalStorage(None),
226 unwinder: Unwinder { unwinding: false, cause: None },
230 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
232 task_type: GreenTask(Some(home)),
235 nasty_deschedule_lock: unsafe { Mutex::new() },
239 pub fn new_child_homed(&mut self,
240 stack_pool: &mut StackPool,
241 stack_size: Option<uint>,
243 start: proc()) -> Task {
245 heap: LocalHeap::new(),
246 gc: GarbageCollector,
247 storage: LocalStorage(None),
249 unwinder: Unwinder { unwinding: false, cause: None },
253 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
255 task_type: GreenTask(Some(home)),
258 nasty_deschedule_lock: unsafe { Mutex::new() },
262 pub fn give_home(&mut self, new_home: SchedHome) {
263 match self.task_type {
264 GreenTask(ref mut home) => {
265 *home = Some(new_home);
268 rtabort!("type error: used SchedTask as GreenTask");
273 pub fn take_unwrap_home(&mut self) -> SchedHome {
274 match self.task_type {
275 GreenTask(ref mut home) => {
276 let out = home.take_unwrap();
280 rtabort!("type error: used SchedTask as GreenTask");
285 pub fn run(&mut self, f: ||) {
286 rtdebug!("run called on task: {}", borrow::to_uint(self));
288 // The only try/catch block in the world. Attempt to run the task's
289 // client-specified code and catch any failures.
290 self.unwinder.try(|| {
292 // Run the task main function, then do some cleanup.
295 // First, destroy task-local storage. This may run user dtors.
297 // FIXME #8302: Dear diary. I'm so tired and confused.
298 // There's some interaction in rustc between the box
299 // annihilator and the TLS dtor by which TLS is
300 // accessed from annihilated box dtors *after* TLS is
301 // destroyed. Somehow setting TLS back to null, as the
302 // old runtime did, makes this work, but I don't currently
303 // understand how. I would expect that, if the annihilator
304 // reinvokes TLS while TLS is uninitialized, that
305 // TLS would be reinitialized but never destroyed,
306 // but somehow this works. I have no idea what's going
307 // on but this seems to make things magically work. FML.
309 // (added after initial comment) A possible interaction here is
310 // that the destructors for the objects in TLS themselves invoke
311 // TLS, or possibly some destructors for those objects being
312 // annihilated invoke TLS. Sadly these two operations seemed to
313 // be intertwined, and miraculously work for now...
316 // Destroy remaining boxes. Also may run user dtors.
317 unsafe { cleanup::annihilate(); }
319 // Finally flush and destroy any output handles which the task
320 // owns. There are no boxes here, and no user destructors should
321 // run after this any more.
322 match self.stdout_handle.take() {
324 let mut handle = handle;
333 // Cleanup the dynamic borrowck debugging info
334 borrowck::clear_task_borrow_list();
336 self.death.collect_failure(self.unwinder.to_unwind_result());
337 self.destroyed = true;
340 // New utility functions for homes.
342 pub fn is_home_no_tls(&self, sched: &~Scheduler) -> bool {
343 match self.task_type {
344 GreenTask(Some(AnySched)) => { false }
345 GreenTask(Some(Sched(SchedHandle { sched_id: ref id, .. }))) => {
346 *id == sched.sched_id()
349 rtabort!("task without home");
353 rtabort!("type error: expected: GreenTask, found: SchedTask");
358 pub fn homed(&self) -> bool {
359 match self.task_type {
360 GreenTask(Some(AnySched)) => { false }
361 GreenTask(Some(Sched(SchedHandle { .. }))) => { true }
363 rtabort!("task without home");
366 rtabort!("type error: expected: GreenTask, found: SchedTask");
371 // Grab both the scheduler and the task from TLS and check if the
372 // task is executing on an appropriate scheduler.
373 pub fn on_appropriate_sched() -> bool {
374 Local::borrow(|task: &mut Task| {
375 let sched_id = task.sched.get_ref().sched_id();
376 let sched_run_anything = task.sched.get_ref().run_anything;
377 match task.task_type {
378 GreenTask(Some(AnySched)) => {
379 rtdebug!("anysched task in sched check ****");
382 GreenTask(Some(Sched(SchedHandle { sched_id: ref id, ..}))) => {
383 rtdebug!("homed task in sched check ****");
387 rtabort!("task without home");
390 rtabort!("type error: expected: GreenTask, found: SchedTask");
399 rtdebug!("called drop for a task: {}", borrow::to_uint(self));
400 rtassert!(self.destroyed);
402 unsafe { self.nasty_deschedule_lock.destroy(); }
406 // Coroutines represent nothing more than a context and a stack
411 pub fn new(stack_pool: &mut StackPool,
412 stack_size: Option<uint>,
415 let stack_size = match stack_size {
417 None => env::min_stack()
419 let start = Coroutine::build_start_wrapper(start);
420 let mut stack = stack_pool.take_segment(stack_size);
421 let initial_context = Context::new(start, &mut stack);
423 current_stack_segment: stack,
424 saved_context: initial_context
428 pub fn empty() -> Coroutine {
430 current_stack_segment: StackSegment::new(0),
431 saved_context: Context::empty()
435 fn build_start_wrapper(start: proc()) -> proc() {
436 let start_cell = Cell::new(start);
437 let wrapper: proc() = proc() {
438 // First code after swap to this new context. Run our
442 // Again - might work while safe, or it might not.
443 Local::borrow(|sched: &mut Scheduler| {
444 sched.run_cleanup_job();
447 // To call the run method on a task we need a direct
448 // reference to it. The task is in TLS, so we can
449 // simply unsafe_borrow it to get this reference. We
450 // need to still have the task in TLS though, so we
451 // need to unsafe_borrow.
452 let task: *mut Task = Local::unsafe_borrow();
455 // N.B. Removing `start` from the start wrapper
456 // closure by emptying a cell is critical for
457 // correctness. The ~Task pointer, and in turn the
458 // closure used to initialize the first call
459 // frame, is destroyed in the scheduler context,
460 // not task context. So any captured closures must
461 // not contain user-definable dtors that expect to
462 // be in task context. By moving `start` out of
463 // the closure, all the user code goes our of
464 // scope while the task is still running.
465 let start = start_cell.take();
470 // We remove the sched from the Task in TLS right now.
471 let sched: ~Scheduler = Local::take();
472 // ... allowing us to give it away when performing a
473 // scheduling operation.
474 sched.terminate_current_task()
479 /// Destroy coroutine and try to reuse stack segment.
480 pub fn recycle(self, stack_pool: &mut StackPool) {
482 Coroutine { current_stack_segment, .. } => {
483 stack_pool.give_segment(current_stack_segment);
491 // Just a sanity check to make sure we are catching a Rust-thrown exception
492 static UNWIND_TOKEN: uintptr_t = 839147;
495 pub fn try(&mut self, f: ||) {
496 use unstable::raw::Closure;
499 let closure: Closure = transmute(f);
500 let code = transmute(closure.code);
501 let env = transmute(closure.env);
503 let token = rust_try(try_fn, code, env);
504 assert!(token == 0 || token == UNWIND_TOKEN);
507 extern fn try_fn(code: *c_void, env: *c_void) {
509 let closure: Closure = Closure {
510 code: transmute(code),
513 let closure: || = transmute(closure);
519 fn rust_try(f: extern "C" fn(*c_void, *c_void),
521 data: *c_void) -> uintptr_t;
525 pub fn begin_unwind(&mut self, cause: ~Any) -> ! {
526 self.unwinding = true;
527 self.cause = Some(cause);
529 rust_begin_unwind(UNWIND_TOKEN);
530 return transmute(());
533 fn rust_begin_unwind(token: uintptr_t);
538 /// This function is invoked from rust's current __morestack function. Segmented
539 /// stacks are currently not enabled as segmented stacks, but rather one giant
540 /// stack segment. This means that whenever we run out of stack, we want to
541 /// truly consider it to be stack overflow rather than allocating a new stack.
542 #[no_mangle] // - this is called from C code
543 #[no_split_stack] // - it would be sad for this function to trigger __morestack
544 #[doc(hidden)] // - Function must be `pub` to get exported, but it's
545 // irrelevant for documentation purposes.
546 #[cfg(not(test))] // in testing, use the original libstd's version
547 pub extern "C" fn rust_stack_exhausted() {
548 use rt::in_green_task_context;
550 use rt::local::Local;
551 use unstable::intrinsics;
554 // We're calling this function because the stack just ran out. We need
555 // to call some other rust functions, but if we invoke the functions
556 // right now it'll just trigger this handler being called again. In
557 // order to alleviate this, we move the stack limit to be inside of the
558 // red zone that was allocated for exactly this reason.
559 let limit = context::get_sp_limit();
560 context::record_sp_limit(limit - context::RED_ZONE / 2);
562 // This probably isn't the best course of action. Ideally one would want
563 // to unwind the stack here instead of just aborting the entire process.
564 // This is a tricky problem, however. There's a few things which need to
567 // 1. We're here because of a stack overflow, yet unwinding will run
568 // destructors and hence arbitrary code. What if that code overflows
569 // the stack? One possibility is to use the above allocation of an
570 // extra 10k to hope that we don't hit the limit, and if we do then
571 // abort the whole program. Not the best, but kind of hard to deal
572 // with unless we want to switch stacks.
574 // 2. LLVM will optimize functions based on whether they can unwind or
575 // not. It will flag functions with 'nounwind' if it believes that
576 // the function cannot trigger unwinding, but if we do unwind on
577 // stack overflow then it means that we could unwind in any function
578 // anywhere. We would have to make sure that LLVM only places the
579 // nounwind flag on functions which don't call any other functions.
581 // 3. The function that overflowed may have owned arguments. These
582 // arguments need to have their destructors run, but we haven't even
583 // begun executing the function yet, so unwinding will not run the
584 // any landing pads for these functions. If this is ignored, then
585 // the arguments will just be leaked.
587 // Exactly what to do here is a very delicate topic, and is possibly
588 // still up in the air for what exactly to do. Some relevant issues:
590 // #3555 - out-of-stack failure leaks arguments
591 // #3695 - should there be a stack limit?
592 // #9855 - possible strategies which could be taken
593 // #9854 - unwinding on windows through __morestack has never worked
594 // #2361 - possible implementation of not using landing pads
596 if in_green_task_context() {
597 Local::borrow(|task: &mut Task| {
598 let n = task.name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
600 // See the message below for why this is not emitted to the
601 // task's logger. This has the additional conundrum of the
602 // logger may not be initialized just yet, meaning that an FFI
603 // call would happen to initialized it (calling out to libuv),
604 // and the FFI call needs 2MB of stack when we just ran out.
605 rterrln!("task '{}' has overflowed its stack", n);
608 rterrln!("stack overflow in non-task context");
615 /// This is the entry point of unwinding for things like lang items and such.
616 /// The arguments are normally generated by the compiler, and need to
617 /// have static lifetimes.
618 pub fn begin_unwind_raw(msg: *c_char, file: *c_char, line: size_t) -> ! {
623 fn static_char_ptr(p: *c_char) -> &'static str {
624 let s = unsafe { CString::new(p, false) };
626 Some(s) => unsafe { transmute::<&str, &'static str>(s) },
627 None => rtabort!("message wasn't utf8?")
631 let msg = static_char_ptr(msg);
632 let file = static_char_ptr(file);
634 begin_unwind(msg, file, line as uint)
637 /// This is the entry point of unwinding for fail!() and assert!().
638 pub fn begin_unwind<M: Any + Send>(msg: M, file: &'static str, line: uint) -> ! {
640 use rt::in_green_task_context;
641 use rt::local::Local;
644 use unstable::intrinsics;
648 // Note that this should be the only allocation performed in this block.
649 // Currently this means that fail!() on OOM will invoke this code path,
650 // but then again we're not really ready for failing on OOM anyway. If
651 // we do start doing this, then we should propagate this allocation to
652 // be performed in the parent of this task instead of the task that's
654 let msg = ~msg as ~Any;
657 //let msg: &Any = msg;
658 let msg_s = match msg.as_ref::<&'static str>() {
660 None => match msg.as_ref::<~str>() {
661 Some(s) => s.as_slice(),
666 if !in_green_task_context() {
667 rterrln!("failed in non-task context at '{}', {}:{}",
672 task = Local::unsafe_borrow();
673 let n = (*task).name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
675 // XXX: this should no get forcibly printed to the console, this should
676 // either be sent to the parent task (ideally), or get printed to
677 // the task's logger. Right now the logger is actually a uvio
678 // instance, which uses unkillable blocks internally for various
679 // reasons. This will cause serious trouble if the task is failing
680 // due to mismanagment of its own kill flag, so calling our own
681 // logger in its current state is a bit of a problem.
683 rterrln!("task '{}' failed at '{}', {}:{}", n, msg_s, file, line);
685 if (*task).unwinder.unwinding {
686 rtabort!("unwinding again");
690 (*task).unwinder.begin_unwind(msg);
701 do run_in_newsched_task() {
712 do run_in_newsched_task() {
713 local_data_key!(key: @~str)
714 local_data::set(key, @~"data");
715 assert!(*local_data::get(key, |k| k.map(|k| *k)).unwrap() == ~"data");
716 local_data_key!(key2: @~str)
717 local_data::set(key2, @~"data");
718 assert!(*local_data::get(key2, |k| k.map(|k| *k)).unwrap() == ~"data");
724 do run_in_newsched_task() {
725 let result = spawntask_try(proc()());
726 rtdebug!("trying first assert");
727 assert!(result.is_ok());
728 let result = spawntask_try(proc() fail!());
729 rtdebug!("trying second assert");
730 assert!(result.is_err());
736 do run_in_uv_task() {
737 use rand::{rng, Rng};
739 let _ = r.next_u32();
745 do run_in_uv_task() {
746 info!("here i am. logging in a newsched task");
754 do run_in_newsched_task {
755 let (port, chan) = oneshot();
757 assert!(port.recv() == 10);
765 do run_in_newsched_task() {
766 let (port, chan) = stream();
768 assert!(port.recv() == 10);
773 fn comm_shared_chan() {
776 do run_in_newsched_task() {
777 let (port, chan) = stream();
778 let chan = SharedChan::new(chan);
780 assert!(port.recv() == 10);
786 use option::{Option, Some, None};
788 do run_in_newsched_task {
790 next: Option<@mut List>,
793 let a = @mut List { next: None };
794 let b = @mut List { next: Some(a) };
802 fn test_begin_unwind() { begin_unwind("cause", file!(), line!()) }