Skip to content

Commit 2074526

Browse files
committed
Implement libstd for CloudABI.
Though CloudABI is strongly inspired by POSIX, its absence of features that don't work well with capability-based sandboxing makes it different enough that adding bits to sys/unix will make things a mess. This change therefore adds CloudABI specific platform code under sys/cloudabi and borrows parts from sys/unix that can be used without changes. One of the goals of this implementation is to build as much as possible directly on top of CloudABI's system call layer, as opposed to using the C library. This is preferred, as the system call layer is supposed to be stable, whereas the C library ABI technically is not. An advantage of this approach is that it allows us to implement certain interfaces, such as mutexes and condition variables more optimally. They can be lighter than the ones provided by pthreads. This change disables some modules that cannot realistically be implemented right now. For example, libstd's pathname abstraction is not designed with POSIX *at() (e.g., openat()) in mind. The *at() functions are the only set of file system APIs available on CloudABI. There is no global file system namespace, nor a process working directory. Discussions on how to port these modules over are outside the scope of this change. Apart from this change, there are still some other minor fixups that need to be made to platform independent code to make things build. These will be sent out separately, so they can be reviewed more thoroughly.
1 parent 795e173 commit 2074526

File tree

15 files changed

+1165
-0
lines changed

15 files changed

+1165
-0
lines changed

src/libstd/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -473,16 +473,21 @@ pub mod f64;
473473
pub mod thread;
474474
pub mod ascii;
475475
pub mod collections;
476+
#[cfg(not(target_os = "cloudabi"))]
476477
pub mod env;
477478
pub mod error;
478479
pub mod ffi;
480+
#[cfg(not(target_os = "cloudabi"))]
479481
pub mod fs;
480482
pub mod io;
483+
#[cfg(not(target_os = "cloudabi"))]
481484
pub mod net;
482485
pub mod num;
483486
pub mod os;
484487
pub mod panic;
488+
#[cfg(not(target_os = "cloudabi"))]
485489
pub mod path;
490+
#[cfg(not(target_os = "cloudabi"))]
486491
pub mod process;
487492
pub mod sync;
488493
pub mod time;

src/libstd/sys/cloudabi/abi/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright 2018 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.
4+
//
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.
10+
11+
#[allow(warnings)]
12+
mod cloudabi;
13+
pub use self::cloudabi::*;

src/libstd/sys/cloudabi/args.rs

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2018 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.
4+
//
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.
10+
11+
#[allow(dead_code)]
12+
pub fn init(_: isize, _: *const *const u8) {}
13+
14+
#[allow(dead_code)]
15+
pub fn cleanup() {}

src/libstd/sys/cloudabi/backtrace.rs

+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// Copyright 2014-2018 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.
4+
//
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.
10+
11+
use error::Error;
12+
use ffi::CStr;
13+
use intrinsics;
14+
use io;
15+
use libc;
16+
use sys_common::backtrace::Frame;
17+
use unwind as uw;
18+
19+
pub struct BacktraceContext;
20+
21+
struct Context<'a> {
22+
idx: usize,
23+
frames: &'a mut [Frame],
24+
}
25+
26+
#[derive(Debug)]
27+
struct UnwindError(uw::_Unwind_Reason_Code);
28+
29+
impl Error for UnwindError {
30+
fn description(&self) -> &'static str {
31+
"unexpected return value while unwinding"
32+
}
33+
}
34+
35+
impl ::fmt::Display for UnwindError {
36+
fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result {
37+
write!(f, "{}: {:?}", self.description(), self.0)
38+
}
39+
}
40+
41+
#[inline(never)] // if we know this is a function call, we can skip it when
42+
// tracing
43+
pub fn unwind_backtrace(frames: &mut [Frame]) -> io::Result<(usize, BacktraceContext)> {
44+
let mut cx = Context { idx: 0, frames };
45+
let result_unwind =
46+
unsafe { uw::_Unwind_Backtrace(trace_fn, &mut cx as *mut Context as *mut libc::c_void) };
47+
// See libunwind:src/unwind/Backtrace.c for the return values.
48+
// No, there is no doc.
49+
match result_unwind {
50+
// These return codes seem to be benign and need to be ignored for backtraces
51+
// to show up properly on all tested platforms.
52+
uw::_URC_END_OF_STACK | uw::_URC_FATAL_PHASE1_ERROR | uw::_URC_FAILURE => {
53+
Ok((cx.idx, BacktraceContext))
54+
}
55+
_ => Err(io::Error::new(
56+
io::ErrorKind::Other,
57+
UnwindError(result_unwind),
58+
)),
59+
}
60+
}
61+
62+
extern "C" fn trace_fn(
63+
ctx: *mut uw::_Unwind_Context,
64+
arg: *mut libc::c_void,
65+
) -> uw::_Unwind_Reason_Code {
66+
let cx = unsafe { &mut *(arg as *mut Context) };
67+
let mut ip_before_insn = 0;
68+
let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void };
69+
if !ip.is_null() && ip_before_insn == 0 {
70+
// this is a non-signaling frame, so `ip` refers to the address
71+
// after the calling instruction. account for that.
72+
ip = (ip as usize - 1) as *mut _;
73+
}
74+
75+
let symaddr = unsafe { uw::_Unwind_FindEnclosingFunction(ip) };
76+
if cx.idx < cx.frames.len() {
77+
cx.frames[cx.idx] = Frame {
78+
symbol_addr: symaddr as *mut u8,
79+
exact_position: ip as *mut u8,
80+
};
81+
cx.idx += 1;
82+
}
83+
84+
uw::_URC_NO_REASON
85+
}
86+
87+
pub fn foreach_symbol_fileline<F>(_: Frame, _: F, _: &BacktraceContext) -> io::Result<bool>
88+
where
89+
F: FnMut(&[u8], u32) -> io::Result<()>,
90+
{
91+
// No way to obtain this information on CloudABI.
92+
Ok(false)
93+
}
94+
95+
pub fn resolve_symname<F>(frame: Frame, callback: F, _: &BacktraceContext) -> io::Result<()>
96+
where
97+
F: FnOnce(Option<&str>) -> io::Result<()>,
98+
{
99+
unsafe {
100+
let mut info: Dl_info = intrinsics::init();
101+
let symname =
102+
if dladdr(frame.exact_position as *mut _, &mut info) == 0 || info.dli_sname.is_null() {
103+
None
104+
} else {
105+
CStr::from_ptr(info.dli_sname).to_str().ok()
106+
};
107+
callback(symname)
108+
}
109+
}
110+
111+
#[repr(C)]
112+
struct Dl_info {
113+
dli_fname: *const libc::c_char,
114+
dli_fbase: *mut libc::c_void,
115+
dli_sname: *const libc::c_char,
116+
dli_saddr: *mut libc::c_void,
117+
}
118+
119+
extern "C" {
120+
fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int;
121+
}

src/libstd/sys/cloudabi/condvar.rs

+169
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// Copyright 2018 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.
4+
//
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.
10+
11+
use cell::UnsafeCell;
12+
use mem;
13+
use sync::atomic::{AtomicU32, Ordering};
14+
use sys::cloudabi::abi;
15+
use sys::mutex::{self, Mutex};
16+
use sys::time::dur2intervals;
17+
use time::Duration;
18+
19+
extern "C" {
20+
#[thread_local]
21+
static __pthread_thread_id: abi::tid;
22+
}
23+
24+
pub struct Condvar {
25+
condvar: UnsafeCell<AtomicU32>,
26+
}
27+
28+
unsafe impl Send for Condvar {}
29+
unsafe impl Sync for Condvar {}
30+
31+
impl Condvar {
32+
pub const fn new() -> Condvar {
33+
Condvar {
34+
condvar: UnsafeCell::new(AtomicU32::new(abi::CONDVAR_HAS_NO_WAITERS.0)),
35+
}
36+
}
37+
38+
pub unsafe fn init(&mut self) {}
39+
40+
pub unsafe fn notify_one(&self) {
41+
let condvar = self.condvar.get();
42+
if (*condvar).load(Ordering::Relaxed) != abi::CONDVAR_HAS_NO_WAITERS.0 {
43+
let ret = abi::condvar_signal(condvar as *mut abi::condvar, abi::scope::PRIVATE, 1);
44+
assert_eq!(
45+
ret,
46+
abi::errno::SUCCESS,
47+
"Failed to signal on condition variable"
48+
);
49+
}
50+
}
51+
52+
pub unsafe fn notify_all(&self) {
53+
let condvar = self.condvar.get();
54+
if (*condvar).load(Ordering::Relaxed) != abi::CONDVAR_HAS_NO_WAITERS.0 {
55+
let ret = abi::condvar_signal(
56+
condvar as *mut abi::condvar,
57+
abi::scope::PRIVATE,
58+
abi::nthreads::max_value(),
59+
);
60+
assert_eq!(
61+
ret,
62+
abi::errno::SUCCESS,
63+
"Failed to broadcast on condition variable"
64+
);
65+
}
66+
}
67+
68+
pub unsafe fn wait(&self, mutex: &Mutex) {
69+
let mutex = mutex::raw(mutex);
70+
assert_eq!(
71+
(*mutex).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0,
72+
__pthread_thread_id.0 | abi::LOCK_WRLOCKED.0,
73+
"This lock is not write-locked by this thread"
74+
);
75+
76+
// Call into the kernel to wait on the condition variable.
77+
let condvar = self.condvar.get();
78+
let subscription = abi::subscription {
79+
type_: abi::eventtype::CONDVAR,
80+
union: abi::subscription_union {
81+
condvar: abi::subscription_condvar {
82+
condvar: condvar as *mut abi::condvar,
83+
condvar_scope: abi::scope::PRIVATE,
84+
lock: mutex as *mut abi::lock,
85+
lock_scope: abi::scope::PRIVATE,
86+
},
87+
},
88+
..mem::zeroed()
89+
};
90+
let mut event: abi::event = mem::uninitialized();
91+
let mut nevents: usize = mem::uninitialized();
92+
let ret = abi::poll(&subscription, &mut event, 1, &mut nevents);
93+
assert_eq!(
94+
ret,
95+
abi::errno::SUCCESS,
96+
"Failed to wait on condition variable"
97+
);
98+
assert_eq!(
99+
event.error,
100+
abi::errno::SUCCESS,
101+
"Failed to wait on condition variable"
102+
);
103+
}
104+
105+
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
106+
let mutex = mutex::raw(mutex);
107+
assert_eq!(
108+
(*mutex).load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0,
109+
__pthread_thread_id.0 | abi::LOCK_WRLOCKED.0,
110+
"This lock is not write-locked by this thread"
111+
);
112+
113+
// Call into the kernel to wait on the condition variable.
114+
let condvar = self.condvar.get();
115+
let subscriptions = [
116+
abi::subscription {
117+
type_: abi::eventtype::CONDVAR,
118+
union: abi::subscription_union {
119+
condvar: abi::subscription_condvar {
120+
condvar: condvar as *mut abi::condvar,
121+
condvar_scope: abi::scope::PRIVATE,
122+
lock: mutex as *mut abi::lock,
123+
lock_scope: abi::scope::PRIVATE,
124+
},
125+
},
126+
..mem::zeroed()
127+
},
128+
abi::subscription {
129+
type_: abi::eventtype::CLOCK,
130+
union: abi::subscription_union {
131+
clock: abi::subscription_clock {
132+
clock_id: abi::clockid::MONOTONIC,
133+
timeout: dur2intervals(&dur),
134+
..mem::zeroed()
135+
},
136+
},
137+
..mem::zeroed()
138+
},
139+
];
140+
let mut events: [abi::event; 2] = mem::uninitialized();
141+
let mut nevents: usize = mem::uninitialized();
142+
let ret = abi::poll(subscriptions.as_ptr(), events.as_mut_ptr(), 2, &mut nevents);
143+
assert_eq!(
144+
ret,
145+
abi::errno::SUCCESS,
146+
"Failed to wait on condition variable"
147+
);
148+
for i in 0..nevents {
149+
assert_eq!(
150+
events[i].error,
151+
abi::errno::SUCCESS,
152+
"Failed to wait on condition variable"
153+
);
154+
if events[i].type_ == abi::eventtype::CONDVAR {
155+
return true;
156+
}
157+
}
158+
false
159+
}
160+
161+
pub unsafe fn destroy(&self) {
162+
let condvar = self.condvar.get();
163+
assert_eq!(
164+
(*condvar).load(Ordering::Relaxed),
165+
abi::CONDVAR_HAS_NO_WAITERS.0,
166+
"Attempted to destroy a condition variable with blocked threads"
167+
);
168+
}
169+
}

0 commit comments

Comments
 (0)