Skip to content

Commit d9f633f

Browse files
authored
Rollup merge of rust-lang#40113 - smaeul:native-musl, r=alexcrichton
Support dynamically-linked and/or native musl targets These changes allow native compilation on musl-based distributions and the use of dynamic libraries on linux-musl targets. This is intended to remove limitations based on past assumptions about musl targets, while maintaining existing behavior by default. A minor related bugfix is included.
2 parents ee60afa + 706fc55 commit d9f633f

File tree

14 files changed

+95
-53
lines changed

14 files changed

+95
-53
lines changed

src/bootstrap/bin/rustc.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,15 @@ fn main() {
207207
}
208208
}
209209

210-
if target.contains("pc-windows-msvc") {
211-
cmd.arg("-Z").arg("unstable-options");
212-
cmd.arg("-C").arg("target-feature=+crt-static");
210+
if let Ok(s) = env::var("RUST_CRT_STATIC") {
211+
if s == "true" {
212+
cmd.arg("-Z").arg("unstable-options");
213+
cmd.arg("-C").arg("target-feature=+crt-static");
214+
}
215+
if s == "false" {
216+
cmd.arg("-Z").arg("unstable-options");
217+
cmd.arg("-C").arg("target-feature=-crt-static");
218+
}
213219
}
214220
}
215221

src/bootstrap/compile.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -106,14 +106,17 @@ pub fn std_link(build: &Build,
106106
t!(fs::create_dir_all(&libdir));
107107
add_to_sysroot(&out_dir, &libdir);
108108

109-
if target.contains("musl") && !target.contains("mips") {
109+
if target.contains("musl") {
110110
copy_musl_third_party_objects(build, target, &libdir);
111111
}
112112
}
113113

114114
/// Copies the crt(1,i,n).o startup objects
115115
///
116-
/// Only required for musl targets that statically link to libc
116+
/// Since musl supports fully static linking, we can cross link for it even
117+
/// with a glibc-targeting toolchain, given we have the appropriate startup
118+
/// files. As those shipped with glibc won't work, copy the ones provided by
119+
/// musl so we have them on linux-gnu hosts.
117120
fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
118121
for &obj in &["crt1.o", "crti.o", "crtn.o"] {
119122
copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));

src/bootstrap/config.rs

+3
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ pub struct Target {
117117
pub cc: Option<PathBuf>,
118118
pub cxx: Option<PathBuf>,
119119
pub ndk: Option<PathBuf>,
120+
pub crt_static: Option<bool>,
120121
pub musl_root: Option<PathBuf>,
121122
pub qemu_rootfs: Option<PathBuf>,
122123
}
@@ -231,6 +232,7 @@ struct TomlTarget {
231232
cc: Option<String>,
232233
cxx: Option<String>,
233234
android_ndk: Option<String>,
235+
crt_static: Option<bool>,
234236
musl_root: Option<String>,
235237
qemu_rootfs: Option<String>,
236238
}
@@ -375,6 +377,7 @@ impl Config {
375377
}
376378
target.cxx = cfg.cxx.clone().map(PathBuf::from);
377379
target.cc = cfg.cc.clone().map(PathBuf::from);
380+
target.crt_static = cfg.crt_static.clone();
378381
target.musl_root = cfg.musl_root.clone().map(PathBuf::from);
379382
target.qemu_rootfs = cfg.qemu_rootfs.clone().map(PathBuf::from);
380383

src/bootstrap/lib.rs

+14
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,10 @@ impl Build {
473473
.env("RUSTDOC_REAL", self.rustdoc(compiler))
474474
.env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
475475

476+
if let Some(x) = self.crt_static(target) {
477+
cargo.env("RUST_CRT_STATIC", x.to_string());
478+
}
479+
476480
// Enable usage of unstable features
477481
cargo.env("RUSTC_BOOTSTRAP", "1");
478482
self.add_rust_test_threads(&mut cargo);
@@ -880,6 +884,16 @@ impl Build {
880884
return base
881885
}
882886

887+
/// Returns if this target should statically link the C runtime, if specified
888+
fn crt_static(&self, target: &str) -> Option<bool> {
889+
if target.contains("pc-windows-msvc") {
890+
Some(true)
891+
} else {
892+
self.config.target_config.get(target)
893+
.and_then(|t| t.crt_static)
894+
}
895+
}
896+
883897
/// Returns the "musl root" for this `target`, if defined
884898
fn musl_root(&self, target: &str) -> Option<&Path> {
885899
self.config.target_config.get(target)

src/bootstrap/sanity.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,15 @@ pub fn check(build: &mut Build) {
157157
panic!("the iOS target is only supported on OSX");
158158
}
159159

160-
// Make sure musl-root is valid if specified
161-
if target.contains("musl") && !target.contains("mips") {
160+
// Make sure musl-root is valid
161+
if target.contains("musl") {
162+
// If this is a native target (host is also musl) and no musl-root is given,
163+
// fall back to the system toolchain in /usr before giving up
164+
if build.musl_root(target).is_none() && build.config.build == *target {
165+
let target = build.config.target_config.entry(target.clone())
166+
.or_insert(Default::default());
167+
target.musl_root = Some("/usr".into());
168+
}
162169
match build.musl_root(target) {
163170
Some(root) => {
164171
if fs::metadata(root.join("lib/libc.a")).is_err() {

src/librustc/session/mod.rs

+29
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use syntax::parse::ParseSess;
3434
use syntax::symbol::Symbol;
3535
use syntax::{ast, codemap};
3636
use syntax::feature_gate::AttributeType;
37+
use syntax::feature_gate::UnstableFeatures;
3738
use syntax_pos::{Span, MultiSpan};
3839

3940
use rustc_back::PanicStrategy;
@@ -378,6 +379,34 @@ impl Session {
378379
.unwrap_or(self.opts.debug_assertions)
379380
}
380381

382+
pub fn crt_static(&self) -> bool {
383+
let requested_features = self.opts.cg.target_feature.split(',');
384+
let unstable_options = self.opts.debugging_opts.unstable_options;
385+
let is_nightly = UnstableFeatures::from_environment().is_nightly_build();
386+
let found_negative = requested_features.clone().any(|r| r == "-crt-static");
387+
let found_positive = requested_features.clone().any(|r| r == "+crt-static");
388+
389+
// If the target we're compiling for requests a static crt by default,
390+
// then see if the `-crt-static` feature was passed to disable that.
391+
// Otherwise if we don't have a static crt by default then see if the
392+
// `+crt-static` feature was passed.
393+
let crt_static = if self.target.target.options.crt_static_default {
394+
!found_negative
395+
} else {
396+
found_positive
397+
};
398+
399+
// If we switched from the default then that's only allowed on nightly, so
400+
// gate that here.
401+
if (found_positive || found_negative) && (!is_nightly || !unstable_options) {
402+
self.fatal("specifying the `crt-static` target feature is only allowed \
403+
on the nightly channel with `-Z unstable-options` passed \
404+
as well");
405+
}
406+
407+
return crt_static;
408+
}
409+
381410
pub fn must_not_eliminate_frame_pointers(&self) -> bool {
382411
self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
383412
!self.target.target.options.eliminate_frame_pointer

src/librustc_back/target/linux_musl_base.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -59,14 +59,7 @@ pub fn opts() -> TargetOptions {
5959
base.pre_link_objects_exe.push("crti.o".to_string());
6060
base.post_link_objects.push("crtn.o".to_string());
6161

62-
// MUSL support doesn't currently include dynamic linking, so there's no
63-
// need for dylibs or rpath business. Additionally `-pie` is incompatible
64-
// with `-static`, so we can't pass `-pie`.
65-
base.dynamic_linking = false;
66-
base.has_rpath = false;
67-
base.position_independent_executables = false;
68-
69-
// These targets statically link libc by default
62+
// Except for on MIPS, these targets statically link libc by default.
7063
base.crt_static_default = true;
7164

7265
base

src/librustc_back/target/mips_unknown_linux_musl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ pub fn target() -> TargetResult {
2525
features: "+mips32r2,+soft-float".to_string(),
2626
max_atomic_width: Some(32),
2727

28+
crt_static_default: false,
2829
// see #36994
2930
exe_allocation_crate: "alloc_system".to_string(),
3031

src/librustc_back/target/mipsel_unknown_linux_musl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ pub fn target() -> TargetResult {
2525
features: "+mips32,+soft-float".to_string(),
2626
max_atomic_width: Some(32),
2727

28+
crt_static_default: false,
2829
// see #36994
2930
exe_allocation_crate: "alloc_system".to_string(),
3031

src/librustc_driver/target_features.rs

+1-26
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use syntax::ast;
1212
use llvm::LLVMRustHasFeature;
1313
use rustc::session::Session;
1414
use rustc_trans::back::write::create_target_machine;
15-
use syntax::feature_gate::UnstableFeatures;
1615
use syntax::symbol::Symbol;
1716
use libc::c_char;
1817

@@ -49,31 +48,7 @@ pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) {
4948
}
5049
}
5150

52-
let requested_features = sess.opts.cg.target_feature.split(',');
53-
let unstable_options = sess.opts.debugging_opts.unstable_options;
54-
let is_nightly = UnstableFeatures::from_environment().is_nightly_build();
55-
let found_negative = requested_features.clone().any(|r| r == "-crt-static");
56-
let found_positive = requested_features.clone().any(|r| r == "+crt-static");
57-
58-
// If the target we're compiling for requests a static crt by default,
59-
// then see if the `-crt-static` feature was passed to disable that.
60-
// Otherwise if we don't have a static crt by default then see if the
61-
// `+crt-static` feature was passed.
62-
let crt_static = if sess.target.target.options.crt_static_default {
63-
!found_negative
64-
} else {
65-
found_positive
66-
};
67-
68-
// If we switched from the default then that's only allowed on nightly, so
69-
// gate that here.
70-
if (found_positive || found_negative) && (!is_nightly || !unstable_options) {
71-
sess.fatal("specifying the `crt-static` target feature is only allowed \
72-
on the nightly channel with `-Z unstable-options` passed \
73-
as well");
74-
}
75-
76-
if crt_static {
51+
if sess.crt_static() {
7752
cfg.insert((tf, Some(Symbol::intern("crt-static"))));
7853
}
7954
}

src/librustc_trans/back/link.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -715,13 +715,15 @@ fn link_natively(sess: &Session,
715715
let root = sess.target_filesearch(PathKind::Native).get_lib_path();
716716
cmd.args(&sess.target.target.options.pre_link_args);
717717

718-
let pre_link_objects = if crate_type == config::CrateTypeExecutable {
719-
&sess.target.target.options.pre_link_objects_exe
720-
} else {
721-
&sess.target.target.options.pre_link_objects_dll
722-
};
723-
for obj in pre_link_objects {
724-
cmd.arg(root.join(obj));
718+
if sess.crt_static() {
719+
let pre_link_objects = if crate_type == config::CrateTypeExecutable {
720+
&sess.target.target.options.pre_link_objects_exe
721+
} else {
722+
&sess.target.target.options.pre_link_objects_dll
723+
};
724+
for obj in pre_link_objects {
725+
cmd.arg(root.join(obj));
726+
}
725727
}
726728

727729
if sess.target.target.options.is_like_emscripten {
@@ -739,8 +741,10 @@ fn link_natively(sess: &Session,
739741
objects, out_filename, outputs, trans);
740742
}
741743
cmd.args(&sess.target.target.options.late_link_args);
742-
for obj in &sess.target.target.options.post_link_objects {
743-
cmd.arg(root.join(obj));
744+
if sess.crt_static() {
745+
for obj in &sess.target.target.options.post_link_objects {
746+
cmd.arg(root.join(obj));
747+
}
744748
}
745749
cmd.args(&sess.target.target.options.post_link_args);
746750

src/libstd/build.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn main() {
3030
println!("cargo:rustc-link-lib=dl");
3131
println!("cargo:rustc-link-lib=log");
3232
println!("cargo:rustc-link-lib=gcc");
33-
} else if !target.contains("musl") || target.contains("mips") {
33+
} else if !target.contains("musl") {
3434
println!("cargo:rustc-link-lib=dl");
3535
println!("cargo:rustc-link-lib=rt");
3636
println!("cargo:rustc-link-lib=pthread");

src/libunwind/build.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ fn main() {
1515
let target = env::var("TARGET").expect("TARGET was not set");
1616

1717
if target.contains("linux") {
18-
if target.contains("musl") && !target.contains("mips") {
19-
println!("cargo:rustc-link-lib=static=unwind");
18+
if target.contains("musl") {
19+
// musl is handled in lib.rs
2020
} else if !target.contains("android") {
2121
println!("cargo:rustc-link-lib=gcc_s");
2222
}

src/libunwind/lib.rs

+6
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#![deny(warnings)]
1616

1717
#![feature(cfg_target_vendor)]
18+
#![feature(link_cfg)]
1819
#![feature(staged_api)]
1920
#![feature(unwind_attributes)]
2021

@@ -27,3 +28,8 @@ extern crate libc;
2728
mod libunwind;
2829
#[cfg(not(target_env = "msvc"))]
2930
pub use libunwind::*;
31+
32+
#[cfg(target_env = "musl")]
33+
#[link(name = "unwind", kind = "static", cfg(target_feature = "crt-static"))]
34+
#[link(name = "gcc_s", cfg(not(target_feature = "crt-static")))]
35+
extern {}

0 commit comments

Comments
 (0)