1 // Copyright 2013-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.
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.
22 use iter::{Iterator, Take};
25 use option::{Option, Some, None};
27 use result::{Result, Ok, Err};
30 use rt::local_heap::LocalHeap;
31 use rt::rtio::LocalIo;
32 use rt::unwind::Unwinder;
34 use sync::arc::UnsafeArc;
35 use sync::atomics::{AtomicUint, SeqCst};
36 use task::{TaskResult, TaskOpts};
37 use unstable::finally::Finally;
39 /// The Task struct represents all state associated with a rust
40 /// task. There are at this point two primary "subtypes" of task,
41 /// however instead of using a subtype we just have a "task_type" field
42 /// in the struct. This contains a pointer to another struct that holds
43 /// the type-specific state.
47 storage: LocalStorage,
51 name: Option<SendStr>,
53 stdout: Option<~Writer>,
54 stderr: Option<~Writer>,
56 priv imp: Option<~Runtime>,
59 pub struct GarbageCollector;
60 pub struct LocalStorage(Option<local_data::Map>);
62 /// A handle to a blocked task. Usually this means having the ~Task pointer by
63 /// ownership, but if the task is killable, a killer can steal it at any time.
64 pub enum BlockedTask {
66 Shared(UnsafeArc<AtomicUint>),
69 pub enum DeathAction {
70 /// Action to be done with the exit code. If set, also makes the task wait
71 /// until all its watched children exit before collecting the status.
72 Execute(proc(TaskResult)),
73 /// A channel to send the result of the task on when the task exits
74 SendMessage(Sender<TaskResult>),
77 /// Per-task state related to task death, killing, failure, etc.
79 on_exit: Option<DeathAction>,
82 pub struct BlockedTasks {
83 priv inner: UnsafeArc<AtomicUint>,
87 pub fn new() -> Task {
89 heap: LocalHeap::new(),
91 storage: LocalStorage(None),
92 unwinder: Unwinder::new(),
102 /// Executes the given closure as if it's running inside this task. The task
103 /// is consumed upon entry, and the destroyed task is returned from this
104 /// function in order for the caller to free. This function is guaranteed to
105 /// not unwind because the closure specified is run inside of a `rust_try`
106 /// block. (this is the only try/catch block in the world).
108 /// This function is *not* meant to be abused as a "try/catch" block. This
109 /// is meant to be used at the absolute boundaries of a task's lifetime, and
110 /// only for that purpose.
111 pub fn run(~self, f: ||) -> ~Task {
112 // Need to put ourselves into TLS, but also need access to the unwinder.
113 // Unsafely get a handle to the task so we can continue to use it after
114 // putting it in tls (so we can invoke the unwinder).
115 let handle: *mut Task = unsafe {
116 *cast::transmute::<&~Task, &*mut Task>(&self)
120 // The only try/catch block in the world. Attempt to run the task's
121 // client-specified code and catch any failures.
124 // Run the task main function, then do some cleanup.
126 #[allow(unused_must_use)]
128 let mut task = Local::borrow(None::<Task>);
129 let stderr = task.get().stderr.take();
130 let stdout = task.get().stdout.take();
132 match stdout { Some(mut w) => { w.flush(); }, None => {} }
133 match stderr { Some(mut w) => { w.flush(); }, None => {} }
136 // First, flush/destroy the user stdout/logger because these
137 // destructors can run arbitrary code.
140 // First, destroy task-local storage. This may run user dtors.
142 // FIXME #8302: Dear diary. I'm so tired and confused.
143 // There's some interaction in rustc between the box
144 // annihilator and the TLS dtor by which TLS is
145 // accessed from annihilated box dtors *after* TLS is
146 // destroyed. Somehow setting TLS back to null, as the
147 // old runtime did, makes this work, but I don't currently
148 // understand how. I would expect that, if the annihilator
149 // reinvokes TLS while TLS is uninitialized, that
150 // TLS would be reinitialized but never destroyed,
151 // but somehow this works. I have no idea what's going
152 // on but this seems to make things magically work. FML.
154 // (added after initial comment) A possible interaction here is
155 // that the destructors for the objects in TLS themselves invoke
156 // TLS, or possibly some destructors for those objects being
157 // annihilated invoke TLS. Sadly these two operations seemed to
158 // be intertwined, and miraculously work for now...
159 let mut task = Local::borrow(None::<Task>);
161 let task = task.get();
162 let LocalStorage(ref mut optmap) = task.storage;
168 // Destroy remaining boxes. Also may run user dtors.
169 unsafe { cleanup::annihilate(); }
171 // Finally, just in case user dtors printed/logged during TLS
172 // cleanup and annihilation, re-destroy stdout and the logger.
173 // Note that these will have been initialized with a
174 // runtime-provided type which we have control over what the
180 unsafe { (*handle).unwinder.try(try_block); }
182 // Here we must unsafely borrow the task in order to not remove it from
183 // TLS. When collecting failure, we may attempt to send on a channel (or
184 // just run aribitrary code), so we must be sure to still have a local
187 let me: *mut Task = Local::unsafe_borrow();
188 (*me).death.collect_failure((*me).unwinder.result());
190 let mut me: ~Task = Local::take();
195 /// Inserts a runtime object into this task, transferring ownership to the
196 /// task. It is illegal to replace a previous runtime object in this task
197 /// with this argument.
198 pub fn put_runtime(&mut self, ops: ~Runtime) {
199 assert!(self.imp.is_none());
200 self.imp = Some(ops);
203 /// Attempts to extract the runtime as a specific type. If the runtime does
204 /// not have the provided type, then the runtime is not removed. If the
205 /// runtime does have the specified type, then it is removed and returned
206 /// (transfer of ownership).
208 /// It is recommended to only use this method when *absolutely necessary*.
209 /// This function may not be available in the future.
210 pub fn maybe_take_runtime<T: 'static>(&mut self) -> Option<~T> {
211 // This is a terrible, terrible function. The general idea here is to
212 // take the runtime, cast it to ~Any, check if it has the right type,
213 // and then re-cast it back if necessary. The method of doing this is
214 // pretty sketchy and involves shuffling vtables of trait objects
215 // around, but it gets the job done.
217 // FIXME: This function is a serious code smell and should be avoided at
218 // all costs. I have yet to think of a method to avoid this
219 // function, and I would be saddened if more usage of the function
222 let imp = self.imp.take_unwrap();
223 let &(vtable, _): &(uint, uint) = cast::transmute(&imp);
224 match imp.wrap().move::<T>() {
227 let (_, obj): (uint, uint) = cast::transmute(t);
228 let obj: ~Runtime = cast::transmute((vtable, obj));
229 self.put_runtime(obj);
236 /// Spawns a sibling to this task. The newly spawned task is configured with
237 /// the `opts` structure and will run `f` as the body of its code.
238 pub fn spawn_sibling(mut ~self, opts: TaskOpts, f: proc()) {
239 let ops = self.imp.take_unwrap();
240 ops.spawn_sibling(self, opts, f)
243 /// Deschedules the current task, invoking `f` `amt` times. It is not
244 /// recommended to use this function directly, but rather communication
245 /// primitives in `std::comm` should be used.
246 pub fn deschedule(mut ~self, amt: uint,
247 f: |BlockedTask| -> Result<(), BlockedTask>) {
248 let ops = self.imp.take_unwrap();
249 ops.deschedule(amt, self, f)
252 /// Wakes up a previously blocked task, optionally specifying whether the
253 /// current task can accept a change in scheduling. This function can only
254 /// be called on tasks that were previously blocked in `deschedule`.
255 pub fn reawaken(mut ~self) {
256 let ops = self.imp.take_unwrap();
260 /// Yields control of this task to another task. This function will
261 /// eventually return, but possibly not immediately. This is used as an
262 /// opportunity to allow other tasks a chance to run.
263 pub fn yield_now(mut ~self) {
264 let ops = self.imp.take_unwrap();
268 /// Similar to `yield_now`, except that this function may immediately return
269 /// without yielding (depending on what the runtime decides to do).
270 pub fn maybe_yield(mut ~self) {
271 let ops = self.imp.take_unwrap();
272 ops.maybe_yield(self);
275 /// Acquires a handle to the I/O factory that this task contains, normally
276 /// stored in the task's runtime. This factory may not always be available,
277 /// which is why the return type is `Option`
278 pub fn local_io<'a>(&'a mut self) -> Option<LocalIo<'a>> {
279 self.imp.get_mut_ref().local_io()
282 /// Returns the stack bounds for this task in (lo, hi) format. The stack
283 /// bounds may not be known for all tasks, so the return value may be
285 pub fn stack_bounds(&self) -> (uint, uint) {
286 self.imp.get_ref().stack_bounds()
289 /// Returns whether it is legal for this task to block the OS thread that it
291 pub fn can_block(&self) -> bool {
292 self.imp.get_ref().can_block()
298 rtdebug!("called drop for a task: {}", self as *mut Task as uint);
299 rtassert!(self.destroyed);
303 impl Iterator<BlockedTask> for BlockedTasks {
304 fn next(&mut self) -> Option<BlockedTask> {
305 Some(Shared(self.inner.clone()))
310 /// Returns Some if the task was successfully woken; None if already killed.
311 pub fn wake(self) -> Option<~Task> {
313 Owned(task) => Some(task),
314 Shared(arc) => unsafe {
315 match (*arc.get()).swap(0, SeqCst) {
317 n => Some(cast::transmute(n)),
323 // This assertion has two flavours because the wake involves an atomic op.
324 // In the faster version, destructors will fail dramatically instead.
325 #[cfg(not(test))] pub fn trash(self) { }
326 #[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); }
328 /// Create a blocked task, unless the task was already killed.
329 pub fn block(task: ~Task) -> BlockedTask {
333 /// Converts one blocked task handle to a list of many handles to the same.
334 pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks>
336 let arc = match self {
338 let flag = unsafe { AtomicUint::new(cast::transmute(task)) };
341 Shared(arc) => arc.clone(),
343 BlockedTasks{ inner: arc }.take(num_handles)
346 /// Convert to an unsafe uint value. Useful for storing in a pipe's state
349 pub unsafe fn cast_to_uint(self) -> uint {
352 let blocked_task_ptr: uint = cast::transmute(task);
353 rtassert!(blocked_task_ptr & 0x1 == 0);
357 let blocked_task_ptr: uint = cast::transmute(~arc);
358 rtassert!(blocked_task_ptr & 0x1 == 0);
359 blocked_task_ptr | 0x1
364 /// Convert from an unsafe uint value. Useful for retrieving a pipe's state
367 pub unsafe fn cast_from_uint(blocked_task_ptr: uint) -> BlockedTask {
368 if blocked_task_ptr & 0x1 == 0 {
369 Owned(cast::transmute(blocked_task_ptr))
371 let ptr: ~UnsafeArc<AtomicUint> =
372 cast::transmute(blocked_task_ptr & !1);
379 pub fn new() -> Death {
380 Death { on_exit: None, }
383 /// Collect failure exit codes from children and propagate them to a parent.
384 pub fn collect_failure(&mut self, result: TaskResult) {
385 match self.on_exit.take() {
386 Some(Execute(f)) => f(result),
387 Some(SendMessage(ch)) => { ch.try_send(result); }
393 impl Drop for Death {
395 // make this type noncopyable
416 local_data_key!(key: @~str)
417 local_data::set(key, @~"data");
418 assert!(*local_data::get(key, |k| k.map(|k| *k)).unwrap() == ~"data");
419 local_data_key!(key2: @~str)
420 local_data::set(key2, @~"data");
421 assert!(*local_data::get(key2, |k| k.map(|k| *k)).unwrap() == ~"data");
426 let result = task::try(proc()());
427 rtdebug!("trying first assert");
428 assert!(result.is_ok());
429 let result = task::try::<()>(proc() fail!());
430 rtdebug!("trying second assert");
431 assert!(result.is_err());
436 use rand::{Rng, task_rng};
437 let mut r = task_rng();
438 let _ = r.next_u32();
443 info!("here i am. logging in a newsched task");
448 let (tx, rx) = channel();
450 assert!(rx.recv() == 10);
454 fn comm_shared_chan() {
455 let (tx, rx) = channel();
457 assert!(rx.recv() == 10);
463 use option::{Option, Some, None};
466 next: Option<@RefCell<List>>,
469 let a = @RefCell::new(List { next: None });
470 let b = @RefCell::new(List { next: Some(a) });
473 let mut a = a.borrow_mut();
480 fn test_begin_unwind() {
481 use rt::unwind::begin_unwind;
482 begin_unwind("cause", file!(), line!())
485 // Task blocking tests
488 fn block_and_wake() {
489 let task = ~Task::new();
490 let mut task = BlockedTask::block(task).wake().unwrap();
491 task.destroyed = true;