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.
19 use libc::{c_void, uintptr_t};
22 use option::{Option, Some, None};
26 use rt::logging::StdErrLogger;
27 use super::local_heap::LocalHeap;
28 use rt::sched::{Scheduler, SchedHandle};
29 use rt::stack::{StackSegment, StackPool};
30 use rt::context::Context;
31 use unstable::finally::Finally;
32 use task::spawn::Taskgroup;
35 // The Task struct represents all state associated with a rust
36 // task. There are at this point two primary "subtypes" of task,
37 // however instead of using a subtype we just have a "task_type" field
38 // in the struct. This contains a pointer to another struct that holds
39 // the type-specific state.
44 storage: LocalStorage,
47 taskgroup: Option<Taskgroup>,
50 // FIXME(#6874/#7599) use StringRef to save on allocations
52 coroutine: Option<Coroutine>,
53 sched: Option<~Scheduler>,
58 GreenTask(Option<~SchedHome>),
62 /// A coroutine is nothing more than a (register context, stack) pair.
63 pub struct Coroutine {
64 /// The segment of stack on which the task is currently running or
65 /// if the task is blocked, on which the task will resume
67 current_stack_segment: StackSegment,
68 /// Always valid if the task is alive and not running.
69 saved_context: Context
72 /// Some tasks have a dedicated home scheduler that they must run on.
78 pub struct GarbageCollector;
79 pub struct LocalStorage(*c_void, Option<extern "Rust" fn(*c_void)>);
87 // A helper to build a new task using the dynamically found
88 // scheduler and task. Only works in GreenTask context.
89 pub fn build_homed_child(stack_size: Option<uint>, f: ~fn(), home: SchedHome) -> ~Task {
91 let home = Cell::new(home);
92 do Local::borrow::<Task, ~Task> |running_task| {
93 let mut sched = running_task.sched.take_unwrap();
94 let new_task = ~running_task.new_child_homed(&mut sched.stack_pool,
98 running_task.sched = Some(sched);
103 pub fn build_child(stack_size: Option<uint>, f: ~fn()) -> ~Task {
104 Task::build_homed_child(stack_size, f, AnySched)
107 pub fn build_homed_root(stack_size: Option<uint>, f: ~fn(), home: SchedHome) -> ~Task {
108 let f = Cell::new(f);
109 let home = Cell::new(home);
110 do Local::borrow::<Task, ~Task> |running_task| {
111 let mut sched = running_task.sched.take_unwrap();
112 let new_task = ~Task::new_root_homed(&mut sched.stack_pool,
116 running_task.sched = Some(sched);
121 pub fn build_root(stack_size: Option<uint>, f: ~fn()) -> ~Task {
122 Task::build_homed_root(stack_size, f, AnySched)
125 pub fn new_sched_task() -> Task {
127 heap: LocalHeap::new(),
128 gc: GarbageCollector,
129 storage: LocalStorage(ptr::null(), None),
130 logger: StdErrLogger,
131 unwinder: Unwinder { unwinding: false },
135 coroutine: Some(Coroutine::empty()),
142 pub fn new_root(stack_pool: &mut StackPool,
143 stack_size: Option<uint>,
144 start: ~fn()) -> Task {
145 Task::new_root_homed(stack_pool, stack_size, AnySched, start)
148 pub fn new_child(&mut self,
149 stack_pool: &mut StackPool,
150 stack_size: Option<uint>,
151 start: ~fn()) -> Task {
152 self.new_child_homed(stack_pool, stack_size, AnySched, start)
155 pub fn new_root_homed(stack_pool: &mut StackPool,
156 stack_size: Option<uint>,
158 start: ~fn()) -> Task {
160 heap: LocalHeap::new(),
161 gc: GarbageCollector,
162 storage: LocalStorage(ptr::null(), None),
163 logger: StdErrLogger,
164 unwinder: Unwinder { unwinding: false },
169 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
171 task_type: GreenTask(Some(~home))
175 pub fn new_child_homed(&mut self,
176 stack_pool: &mut StackPool,
177 stack_size: Option<uint>,
179 start: ~fn()) -> Task {
181 heap: LocalHeap::new(),
182 gc: GarbageCollector,
183 storage: LocalStorage(ptr::null(), None),
184 logger: StdErrLogger,
185 unwinder: Unwinder { unwinding: false },
187 // FIXME(#7544) make watching optional
188 death: self.death.new_child(),
191 coroutine: Some(Coroutine::new(stack_pool, stack_size, start)),
193 task_type: GreenTask(Some(~home))
197 pub fn give_home(&mut self, new_home: SchedHome) {
198 match self.task_type {
199 GreenTask(ref mut home) => {
200 *home = Some(~new_home);
203 rtabort!("type error: used SchedTask as GreenTask");
208 pub fn take_unwrap_home(&mut self) -> SchedHome {
209 match self.task_type {
210 GreenTask(ref mut home) => {
211 let out = home.take_unwrap();
215 rtabort!("type error: used SchedTask as GreenTask");
220 pub fn run(&mut self, f: &fn()) {
221 rtdebug!("run called on task: %u", borrow::to_uint(self));
223 // The only try/catch block in the world. Attempt to run the task's
224 // client-specified code and catch any failures.
225 do self.unwinder.try {
227 // Run the task main function, then do some cleanup.
230 // Destroy task-local storage. This may run user dtors.
232 LocalStorage(ptr, Some(ref dtor)) => {
238 // FIXME #8302: Dear diary. I'm so tired and confused.
239 // There's some interaction in rustc between the box
240 // annihilator and the TLS dtor by which TLS is
241 // accessed from annihilated box dtors *after* TLS is
242 // destroyed. Somehow setting TLS back to null, as the
243 // old runtime did, makes this work, but I don't currently
244 // understand how. I would expect that, if the annihilator
245 // reinvokes TLS while TLS is uninitialized, that
246 // TLS would be reinitialized but never destroyed,
247 // but somehow this works. I have no idea what's going
248 // on but this seems to make things magically work. FML.
249 self.storage = LocalStorage(ptr::null(), None);
251 // Destroy remaining boxes. Also may run user dtors.
252 unsafe { cleanup::annihilate(); }
256 // NB. We pass the taskgroup into death so that it can be dropped while
257 // the unkillable counter is set. This is necessary for when the
258 // taskgroup destruction code drops references on KillHandles, which
259 // might require using unkillable (to synchronize with an unwrapper).
260 self.death.collect_failure(!self.unwinder.unwinding, self.taskgroup.take());
261 self.destroyed = true;
264 // New utility functions for homes.
266 pub fn is_home_no_tls(&self, sched: &~Scheduler) -> bool {
267 match self.task_type {
268 GreenTask(Some(~AnySched)) => { false }
269 GreenTask(Some(~Sched(SchedHandle { sched_id: ref id, _}))) => {
270 *id == sched.sched_id()
273 rtabort!("task without home");
277 rtabort!("type error: expected: GreenTask, found: SchedTask");
282 pub fn homed(&self) -> bool {
283 match self.task_type {
284 GreenTask(Some(~AnySched)) => { false }
285 GreenTask(Some(~Sched(SchedHandle { _ }))) => { true }
287 rtabort!("task without home");
290 rtabort!("type error: expected: GreenTask, found: SchedTask");
295 // Grab both the scheduler and the task from TLS and check if the
296 // task is executing on an appropriate scheduler.
297 pub fn on_appropriate_sched() -> bool {
298 do Local::borrow::<Task,bool> |task| {
299 let sched_id = task.sched.get_ref().sched_id();
300 let sched_run_anything = task.sched.get_ref().run_anything;
301 match task.task_type {
302 GreenTask(Some(~AnySched)) => {
303 rtdebug!("anysched task in sched check ****");
306 GreenTask(Some(~Sched(SchedHandle { sched_id: ref id, _ }))) => {
307 rtdebug!("homed task in sched check ****");
311 rtabort!("task without home");
314 rtabort!("type error: expected: GreenTask, found: SchedTask");
323 rtdebug!("called drop for a task: %u", borrow::to_uint(self));
324 rtassert!(self.destroyed)
328 // Coroutines represent nothing more than a context and a stack
333 pub fn new(stack_pool: &mut StackPool, stack_size: Option<uint>, start: ~fn()) -> Coroutine {
334 let stack_size = match stack_size {
336 None => env::min_stack()
338 let start = Coroutine::build_start_wrapper(start);
339 let mut stack = stack_pool.take_segment(stack_size);
340 let initial_context = Context::new(start, &mut stack);
342 current_stack_segment: stack,
343 saved_context: initial_context
347 pub fn empty() -> Coroutine {
349 current_stack_segment: StackSegment::new(0),
350 saved_context: Context::empty()
354 fn build_start_wrapper(start: ~fn()) -> ~fn() {
355 let start_cell = Cell::new(start);
356 let wrapper: ~fn() = || {
357 // First code after swap to this new context. Run our
361 // Again - might work while safe, or it might not.
362 do Local::borrow::<Scheduler,()> |sched| {
363 (sched).run_cleanup_job();
366 // To call the run method on a task we need a direct
367 // reference to it. The task is in TLS, so we can
368 // simply unsafe_borrow it to get this reference. We
369 // need to still have the task in TLS though, so we
370 // need to unsafe_borrow.
371 let task = Local::unsafe_borrow::<Task>();
374 // N.B. Removing `start` from the start wrapper
375 // closure by emptying a cell is critical for
376 // correctness. The ~Task pointer, and in turn the
377 // closure used to initialize the first call
378 // frame, is destroyed in the scheduler context,
379 // not task context. So any captured closures must
380 // not contain user-definable dtors that expect to
381 // be in task context. By moving `start` out of
382 // the closure, all the user code goes our of
383 // scope while the task is still running.
384 let start = start_cell.take();
389 // We remove the sched from the Task in TLS right now.
390 let sched = Local::take::<Scheduler>();
391 // ... allowing us to give it away when performing a
392 // scheduling operation.
393 sched.terminate_current_task()
398 /// Destroy coroutine and try to reuse stack segment.
399 pub fn recycle(self, stack_pool: &mut StackPool) {
401 Coroutine { current_stack_segment, _ } => {
402 stack_pool.give_segment(current_stack_segment);
410 // Just a sanity check to make sure we are catching a Rust-thrown exception
411 static UNWIND_TOKEN: uintptr_t = 839147;
414 pub fn try(&mut self, f: &fn()) {
415 use unstable::raw::Closure;
418 let closure: Closure = transmute(f);
419 let code = transmute(closure.code);
420 let env = transmute(closure.env);
422 let token = rust_try(try_fn, code, env);
423 assert!(token == 0 || token == UNWIND_TOKEN);
426 extern fn try_fn(code: *c_void, env: *c_void) {
428 let closure: Closure = Closure {
429 code: transmute(code),
432 let closure: &fn() = transmute(closure);
439 fn rust_try(f: *u8, code: *c_void, data: *c_void) -> uintptr_t;
443 pub fn begin_unwind(&mut self) -> ! {
444 #[fixed_stack_segment]; #[inline(never)];
446 self.unwinding = true;
448 rust_begin_unwind(UNWIND_TOKEN);
449 return transmute(());
452 fn rust_begin_unwind(token: uintptr_t);
463 do run_in_newsched_task() {
474 do run_in_newsched_task() {
475 static key: local_data::Key<@~str> = &local_data::Key;
476 local_data::set(key, @~"data");
477 assert!(*local_data::get(key, |k| k.map_move(|k| *k)).unwrap() == ~"data");
478 static key2: local_data::Key<@~str> = &local_data::Key;
479 local_data::set(key2, @~"data");
480 assert!(*local_data::get(key2, |k| k.map_move(|k| *k)).unwrap() == ~"data");
486 do run_in_newsched_task() {
487 let result = spawntask_try(||());
488 rtdebug!("trying first assert");
489 assert!(result.is_ok());
490 let result = spawntask_try(|| fail!());
491 rtdebug!("trying second assert");
492 assert!(result.is_err());
498 do run_in_newsched_task() {
499 use rand::{rng, Rng};
507 do run_in_newsched_task() {
508 info!("here i am. logging in a newsched task");
516 do run_in_newsched_task {
517 let (port, chan) = oneshot();
519 assert!(port.recv() == 10);
527 do run_in_newsched_task() {
528 let (port, chan) = stream();
530 assert!(port.recv() == 10);
535 fn comm_shared_chan() {
538 do run_in_newsched_task() {
539 let (port, chan) = stream();
540 let chan = SharedChan::new(chan);
542 assert!(port.recv() == 10);
547 fn linked_failure() {
548 do run_in_newsched_task() {
549 let res = do spawntask_try {
550 spawntask_random(|| fail!());
552 assert!(res.is_err());
558 use option::{Option, Some, None};
560 do run_in_newsched_task {
562 next: Option<@mut List>,
565 let a = @mut List { next: None };
566 let b = @mut List { next: Some(a) };
572 // XXX: This is a copy of test_future_result in std::task.
573 // It can be removed once the scheduler is turned on by default.
576 do run_in_newsched_task {
577 use option::{Some, None};
580 let mut result = None;
581 let mut builder = task();
582 builder.future_result(|r| result = Some(r));
584 assert_eq!(result.unwrap().recv(), Success);
587 let mut builder = task();
588 builder.future_result(|r| result = Some(r));
593 assert_eq!(result.unwrap().recv(), Failure);