Skip to content

Commit 42c3ef8

Browse files
committed
Auto merge of #30417 - alexcrichton:better-detect-elf-tls, r=alexcrichton
Currently a compiler can be built with the `--disable-elf-tls` option for compatibility with OSX 10.6 which doesn't have ELF TLS. This is unfortunate, however, as a whole new compiler must be generated which can take some time. These commits add a new (feature gated) `cfg(target_thread_local)` annotation set by the compiler which indicates whether `#[thread_local]` is available for use. The compiler now interprets `MACOSX_DEPLOYMENT_TARGET` (a standard environment variable) to set this flag on OSX. With this we may want to start compiling our OSX nightlies with `MACOSX_DEPLOYMENT_TARGET` set to 10.6 which would allow the compiler out-of-the-box to generate 10.6-compatible binaries. For now the compiler still by default targets OSX 10.7 by allowing ELF TLS by default (e.g. if `MACOSX_DEPLOYMENT_TARGET` isn't set).
2 parents 5178449 + cd74364 commit 42c3ef8

File tree

12 files changed

+103
-84
lines changed

12 files changed

+103
-84
lines changed

src/librustc/session/config.rs

+3
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,9 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
660660
"windows" | "unix" => ret.push(attr::mk_word_item(fam)),
661661
_ => (),
662662
}
663+
if sess.target.target.options.has_elf_tls {
664+
ret.push(attr::mk_word_item(InternedString::new("target_thread_local")));
665+
}
663666
if sess.opts.debug_assertions {
664667
ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
665668
}

src/librustc_back/target/aarch64_unknown_linux_gnu.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
use target::Target;
1212

1313
pub fn target() -> Target {
14-
let base = super::linux_base::opts();
14+
let mut base = super::linux_base::opts();
15+
base.has_elf_tls = false;
1516
Target {
1617
llvm_target: "aarch64-unknown-linux-gnu".to_string(),
1718
target_endian: "little".to_string(),

src/librustc_back/target/apple_base.rs

+22-1
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,30 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use std::env;
12+
1113
use target::TargetOptions;
12-
use std::default::Default;
1314

1415
pub fn opts() -> TargetOptions {
16+
// ELF TLS is only available in OSX 10.7+. If you try to compile for 10.6
17+
// either the linker will complain if it is used or the binary will end up
18+
// segfaulting at runtime when run on 10.6. Rust by default supports OSX
19+
// 10.7+, but there is a standard environment variable,
20+
// MACOSX_DEPLOYMENT_TARGET, which is used to signal targeting older
21+
// versions of OSX. For example compiling on 10.10 with
22+
// MACOSX_DEPLOYMENT_TARGET set to 10.6 will cause the linker to generate
23+
// warnings about the usage of ELF TLS.
24+
//
25+
// Here we detect what version is being requested, defaulting to 10.7. ELF
26+
// TLS is flagged as enabled if it looks to be supported.
27+
let deployment_target = env::var("MACOSX_DEPLOYMENT_TARGET").ok();
28+
let version = deployment_target.as_ref().and_then(|s| {
29+
let mut i = s.splitn(2, ".");
30+
i.next().and_then(|a| i.next().map(|b| (a, b)))
31+
}).and_then(|(a, b)| {
32+
a.parse::<u32>().and_then(|a| b.parse::<u32>().map(|b| (a, b))).ok()
33+
}).unwrap_or((10, 7));
34+
1535
TargetOptions {
1636
// OSX has -dead_strip, which doesn't rely on ffunction_sections
1737
function_sections: false,
@@ -25,6 +45,7 @@ pub fn opts() -> TargetOptions {
2545
archive_format: "bsd".to_string(),
2646
pre_link_args: Vec::new(),
2747
exe_allocation_crate: super::maybe_jemalloc(),
48+
has_elf_tls: version >= (10, 7),
2849
.. Default::default()
2950
}
3051
}

src/librustc_back/target/apple_ios_base.rs

+1
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ pub fn opts(arch: Arch) -> TargetOptions {
8888
dynamic_linking: false,
8989
executables: true,
9090
pre_link_args: pre_link_args(arch),
91+
has_elf_tls: false,
9192
.. super::apple_base::opts()
9293
}
9394
}

src/librustc_back/target/arm_linux_androideabi.rs

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use target::Target;
1313
pub fn target() -> Target {
1414
let mut base = super::android_base::opts();
1515
base.features = "+v7".to_string();
16+
base.has_elf_tls = false;
1617

1718
Target {
1819
llvm_target: "arm-linux-androideabi".to_string(),

src/librustc_back/target/linux_base.rs

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub fn opts() -> TargetOptions {
3030
position_independent_executables: true,
3131
archive_format: "gnu".to_string(),
3232
exe_allocation_crate: super::maybe_jemalloc(),
33+
has_elf_tls: true,
3334
.. Default::default()
3435
}
3536
}

src/librustc_back/target/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ pub struct TargetOptions {
195195
/// Default crate for allocation symbols to link against
196196
pub lib_allocation_crate: String,
197197
pub exe_allocation_crate: String,
198+
199+
/// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
200+
/// this target.
201+
pub has_elf_tls: bool,
198202
}
199203

200204
impl Default for TargetOptions {
@@ -240,6 +244,7 @@ impl Default for TargetOptions {
240244
lib_allocation_crate: "alloc_system".to_string(),
241245
exe_allocation_crate: "alloc_system".to_string(),
242246
allow_asm: true,
247+
has_elf_tls: false,
243248
}
244249
}
245250
}

src/librustc_driver/driver.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
606606
feature_gated_cfgs.sort();
607607
feature_gated_cfgs.dedup();
608608
for cfg in &feature_gated_cfgs {
609-
cfg.check_and_emit(sess.diagnostic(), &features);
609+
cfg.check_and_emit(sess.diagnostic(), &features, sess.codemap());
610610
}
611611
});
612612

src/libstd/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218
#![feature(borrow_state)]
219219
#![feature(box_syntax)]
220220
#![feature(cfg_target_vendor)]
221+
#![feature(cfg_target_thread_local)]
221222
#![feature(char_internals)]
222223
#![feature(clone_from_slice)]
223224
#![feature(collections)]

src/libstd/thread/local.rs

+44-76
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@
1515
use cell::UnsafeCell;
1616
use mem;
1717

18-
// Sure wish we had macro hygiene, no?
19-
#[doc(hidden)]
20-
pub use self::imp::Key as __KeyInner;
21-
2218
/// A thread local storage key which owns its contents.
2319
///
2420
/// This key uses the fastest possible implementation available to it for the
@@ -61,78 +57,42 @@ pub use self::imp::Key as __KeyInner;
6157
/// });
6258
/// ```
6359
#[stable(feature = "rust1", since = "1.0.0")]
64-
pub struct LocalKey<T:'static> {
65-
// The key itself may be tagged with #[thread_local], and this `Key` is
66-
// stored as a `static`, and it's not valid for a static to reference the
67-
// address of another thread_local static. For this reason we kinda wonkily
68-
// work around this by generating a shim function which will give us the
69-
// address of the inner TLS key at runtime.
60+
pub struct LocalKey<T: 'static> {
61+
// This outer `LocalKey<T>` type is what's going to be stored in statics,
62+
// but actual data inside will sometimes be tagged with #[thread_local].
63+
// It's not valid for a true static to reference a #[thread_local] static,
64+
// so we get around that by exposing an accessor through a layer of function
65+
// indirection (this thunk).
66+
//
67+
// Note that the thunk is itself unsafe because the returned lifetime of the
68+
// slot where data lives, `'static`, is not actually valid. The lifetime
69+
// here is actually `'thread`!
7070
//
71-
// This is trivially devirtualizable by LLVM because we never store anything
72-
// to this field and rustc can declare the `static` as constant as well.
73-
inner: fn() -> &'static __KeyInner<T>,
71+
// Although this is an extra layer of indirection, it should in theory be
72+
// trivially devirtualizable by LLVM because the value of `inner` never
73+
// changes and the constant should be readonly within a crate. This mainly
74+
// only runs into problems when TLS statics are exported across crates.
75+
inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
7476

7577
// initialization routine to invoke to create a value
7678
init: fn() -> T,
7779
}
7880

79-
// Macro pain #4586:
80-
//
81-
// When cross compiling, rustc will load plugins and macros from the *host*
82-
// platform before search for macros from the target platform. This is primarily
83-
// done to detect, for example, plugins. Ideally the macro below would be
84-
// defined once per module below, but unfortunately this means we have the
85-
// following situation:
86-
//
87-
// 1. We compile libstd for x86_64-unknown-linux-gnu, this thread_local!() macro
88-
// will inject #[thread_local] statics.
89-
// 2. We then try to compile a program for arm-linux-androideabi
90-
// 3. The compiler has a host of linux and a target of android, so it loads
91-
// macros from the *linux* libstd.
92-
// 4. The macro generates a #[thread_local] field, but the android libstd does
93-
// not use #[thread_local]
94-
// 5. Compile error about structs with wrong fields.
95-
//
96-
// To get around this, we're forced to inject the #[cfg] logic into the macro
97-
// itself. Woohoo.
98-
9981
/// Declare a new thread local storage key of type `std::thread::LocalKey`.
10082
///
10183
/// See [LocalKey documentation](thread/struct.LocalKey.html) for more
10284
/// information.
10385
#[macro_export]
10486
#[stable(feature = "rust1", since = "1.0.0")]
10587
#[allow_internal_unstable]
106-
#[cfg(not(no_elf_tls))]
107-
macro_rules! thread_local {
108-
(static $name:ident: $t:ty = $init:expr) => (
109-
static $name: $crate::thread::LocalKey<$t> =
110-
__thread_local_inner!($t, $init,
111-
#[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
112-
not(target_arch = "aarch64")),
113-
thread_local)]);
114-
);
115-
(pub static $name:ident: $t:ty = $init:expr) => (
116-
pub static $name: $crate::thread::LocalKey<$t> =
117-
__thread_local_inner!($t, $init,
118-
#[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
119-
not(target_arch = "aarch64")),
120-
thread_local)]);
121-
);
122-
}
123-
124-
#[macro_export]
125-
#[stable(feature = "rust1", since = "1.0.0")]
126-
#[allow_internal_unstable]
127-
#[cfg(no_elf_tls)]
12888
macro_rules! thread_local {
12989
(static $name:ident: $t:ty = $init:expr) => (
13090
static $name: $crate::thread::LocalKey<$t> =
131-
__thread_local_inner!($t, $init, #[]);
91+
__thread_local_inner!($t, $init);
13292
);
13393
(pub static $name:ident: $t:ty = $init:expr) => (
13494
pub static $name: $crate::thread::LocalKey<$t> =
135-
__thread_local_inner!($t, $init, #[]);
95+
__thread_local_inner!($t, $init);
13696
);
13797
}
13898

@@ -143,12 +103,25 @@ macro_rules! thread_local {
143103
#[macro_export]
144104
#[allow_internal_unstable]
145105
macro_rules! __thread_local_inner {
146-
($t:ty, $init:expr, #[$($attr:meta),*]) => {{
147-
$(#[$attr])*
148-
static __KEY: $crate::thread::__LocalKeyInner<$t> =
149-
$crate::thread::__LocalKeyInner::new();
106+
($t:ty, $init:expr) => {{
150107
fn __init() -> $t { $init }
151-
fn __getit() -> &'static $crate::thread::__LocalKeyInner<$t> { &__KEY }
108+
109+
unsafe fn __getit() -> $crate::option::Option<
110+
&'static $crate::cell::UnsafeCell<
111+
$crate::option::Option<$t>>>
112+
{
113+
#[thread_local]
114+
#[cfg(target_thread_local)]
115+
static __KEY: $crate::thread::__ElfLocalKeyInner<$t> =
116+
$crate::thread::__ElfLocalKeyInner::new();
117+
118+
#[cfg(not(target_thread_local))]
119+
static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
120+
$crate::thread::__OsLocalKeyInner::new();
121+
122+
__KEY.get()
123+
}
124+
152125
$crate::thread::LocalKey::new(__getit, __init)
153126
}}
154127
}
@@ -190,11 +163,11 @@ impl<T: 'static> LocalKey<T> {
190163
#[unstable(feature = "thread_local_internals",
191164
reason = "recently added to create a key",
192165
issue = "0")]
193-
pub const fn new(inner: fn() -> &'static __KeyInner<T>,
166+
pub const fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
194167
init: fn() -> T) -> LocalKey<T> {
195168
LocalKey {
196169
inner: inner,
197-
init: init
170+
init: init,
198171
}
199172
}
200173

@@ -211,10 +184,10 @@ impl<T: 'static> LocalKey<T> {
211184
#[stable(feature = "rust1", since = "1.0.0")]
212185
pub fn with<F, R>(&'static self, f: F) -> R
213186
where F: FnOnce(&T) -> R {
214-
let slot = (self.inner)();
215187
unsafe {
216-
let slot = slot.get().expect("cannot access a TLS value during or \
217-
after it is destroyed");
188+
let slot = (self.inner)();
189+
let slot = slot.expect("cannot access a TLS value during or \
190+
after it is destroyed");
218191
f(match *slot.get() {
219192
Some(ref inner) => inner,
220193
None => self.init(slot),
@@ -270,7 +243,7 @@ impl<T: 'static> LocalKey<T> {
270243
issue = "27716")]
271244
pub fn state(&'static self) -> LocalKeyState {
272245
unsafe {
273-
match (self.inner)().get() {
246+
match (self.inner)() {
274247
Some(cell) => {
275248
match *cell.get() {
276249
Some(..) => LocalKeyState::Valid,
@@ -283,11 +256,9 @@ impl<T: 'static> LocalKey<T> {
283256
}
284257
}
285258

286-
#[cfg(all(any(target_os = "macos", target_os = "linux"),
287-
not(target_arch = "aarch64"),
288-
not(no_elf_tls)))]
259+
#[cfg(target_thread_local)]
289260
#[doc(hidden)]
290-
mod imp {
261+
pub mod elf {
291262
use cell::{Cell, UnsafeCell};
292263
use intrinsics;
293264
use ptr;
@@ -431,11 +402,8 @@ mod imp {
431402
}
432403
}
433404

434-
#[cfg(any(not(any(target_os = "macos", target_os = "linux")),
435-
target_arch = "aarch64",
436-
no_elf_tls))]
437405
#[doc(hidden)]
438-
mod imp {
406+
pub mod os {
439407
use prelude::v1::*;
440408

441409
use cell::{Cell, UnsafeCell};

src/libstd/thread/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,10 @@ pub use self::local::{LocalKey, LocalKeyState};
191191
pub use self::scoped_tls::ScopedKey;
192192

193193
#[unstable(feature = "libstd_thread_internals", issue = "0")]
194-
#[doc(hidden)] pub use self::local::__KeyInner as __LocalKeyInner;
194+
#[cfg(target_thread_local)]
195+
#[doc(hidden)] pub use self::local::elf::Key as __ElfLocalKeyInner;
196+
#[unstable(feature = "libstd_thread_internals", issue = "0")]
197+
#[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner;
195198
#[unstable(feature = "libstd_thread_internals", issue = "0")]
196199
#[doc(hidden)] pub use self::scoped_tls::__KeyInner as __ScopedKeyInner;
197200

0 commit comments

Comments
 (0)