1 #[cfg(feature = "cc")]
2 use cc::Build;
3 use std::env::var;
4 use std::io::Write;
5
6 /// The directory for out-of-line ("outline") libraries.
7 const OUTLINE_PATH: &str = "src/backend/linux_raw/arch/outline";
8
main()9 fn main() {
10 // Don't rerun this on changes other than build.rs, as we only depend on
11 // the rustc version.
12 println!("cargo:rerun-if-changed=build.rs");
13
14 use_feature_or_nothing("rustc_attrs");
15
16 // Features only used in no-std configurations.
17 #[cfg(not(feature = "std"))]
18 {
19 use_feature_or_nothing("const_raw_ptr_deref");
20 use_feature_or_nothing("core_ffi_c");
21 use_feature_or_nothing("core_c_str");
22 use_feature_or_nothing("alloc_c_string");
23 }
24
25 // Gather target information.
26 let arch = var("CARGO_CFG_TARGET_ARCH").unwrap();
27 let asm_name = format!("{}/{}.s", OUTLINE_PATH, arch);
28 let asm_name_present = std::fs::metadata(&asm_name).is_ok();
29 let os_name = var("CARGO_CFG_TARGET_OS").unwrap();
30 let pointer_width = var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap();
31 let endian = var("CARGO_CFG_TARGET_ENDIAN").unwrap();
32
33 // Check for special target variants.
34 let is_x32 = arch == "x86_64" && pointer_width == "32";
35 let is_arm64_ilp32 = arch == "aarch64" && pointer_width == "32";
36 let is_powerpc64be = arch == "powerpc64" && endian == "big";
37 let is_mipseb = arch == "mips" && endian == "big";
38 let is_mips64eb = arch == "mips64" && endian == "big";
39 let is_unsupported_abi = is_x32 || is_arm64_ilp32 || is_powerpc64be || is_mipseb || is_mips64eb;
40
41 // Check for `--features=use-libc`. This allows crate users to enable the
42 // libc backend.
43 let feature_use_libc = var("CARGO_FEATURE_USE_LIBC").is_ok();
44
45 // Check for `--features=rustc-dep-of-std`. This is used when rustix is
46 // being used to build std, in which case `can_compile` doesn't work
47 // because `core` isn't available yet, but also, we can assume we have a
48 // recent compiler.
49 let feature_rustc_dep_of_std = var("CARGO_FEATURE_RUSTC_DEP_OF_STD").is_ok();
50
51 // Check for `RUSTFLAGS=--cfg=rustix_use_libc`. This allows end users to
52 // enable the libc backend even if rustix is depended on transitively.
53 let cfg_use_libc = var("CARGO_CFG_RUSTIX_USE_LIBC").is_ok();
54
55 // Check for eg. `RUSTFLAGS=--cfg=rustix_use_experimental_asm`. This is a
56 // rustc flag rather than a cargo feature flag because it's experimental
57 // and not something we want accidentally enabled via `--all-features`.
58 let rustix_use_experimental_asm = var("CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_ASM").is_ok();
59
60 // Miri doesn't support inline asm, and has builtin support for recognizing
61 // libc FFI calls, so if we're running under miri, use the libc backend.
62 let miri = var("CARGO_CFG_MIRI").is_ok();
63
64 // If the libc backend is requested, or if we're not on a platform for
65 // which we have linux_raw support, use the libc backend.
66 //
67 // For now Android uses the libc backend; in theory it could use the
68 // linux_raw backend, but to do that we'll need to figure out how to
69 // install the toolchain for it.
70 if feature_use_libc
71 || cfg_use_libc
72 || os_name != "linux"
73 || !asm_name_present
74 || is_unsupported_abi
75 || miri
76 {
77 // Use the libc backend.
78 use_feature("libc");
79 } else {
80 // Use the linux_raw backend.
81 use_feature("linux_raw");
82 use_feature_or_nothing("core_intrinsics");
83
84 // Use inline asm if we have it, or outline asm otherwise. On PowerPC
85 // and MIPS, Rust's inline asm is considered experimental, so only use
86 // it if `--cfg=rustix_use_experimental_asm` is given.
87 if (feature_rustc_dep_of_std || can_compile("use std::arch::asm;"))
88 && (arch != "x86" || has_feature("naked_functions"))
89 && ((arch != "powerpc64" && arch != "mips" && arch != "mips64")
90 || rustix_use_experimental_asm)
91 {
92 use_feature("asm");
93 if arch == "x86" {
94 use_feature("naked_functions");
95 }
96 if rustix_use_experimental_asm {
97 use_feature("asm_experimental_arch");
98 }
99 } else {
100 link_in_librustix_outline(&arch, &asm_name);
101 }
102 }
103
104 // Detect whether the compiler requires us to use thumb mode on ARM.
105 if arch == "arm" && use_thumb_mode() {
106 use_feature("thumb_mode");
107 }
108
109 println!("cargo:rerun-if-env-changed=CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_ASM");
110 }
111
112 /// Link in the desired version of librustix_outline_{arch}.a, containing the
113 /// outline assembly code for making syscalls.
link_in_librustix_outline(arch: &str, asm_name: &str)114 fn link_in_librustix_outline(arch: &str, asm_name: &str) {
115 let name = format!("rustix_outline_{}", arch);
116 let profile = var("PROFILE").unwrap();
117 let to = format!("{}/{}/lib{}.a", OUTLINE_PATH, profile, name);
118 println!("cargo:rerun-if-changed={}", to);
119
120 // If "cc" is not enabled, use a pre-built library.
121 #[cfg(not(feature = "cc"))]
122 {
123 let _ = asm_name;
124 println!("cargo:rustc-link-search={}/{}", OUTLINE_PATH, profile);
125 println!("cargo:rustc-link-lib=static={}", name);
126 }
127
128 // If "cc" is enabled, build the library from source, update the pre-built
129 // version, and assert that the pre-built version is checked in.
130 #[cfg(feature = "cc")]
131 {
132 let out_dir = var("OUT_DIR").unwrap();
133 Build::new().file(&asm_name).compile(&name);
134 println!("cargo:rerun-if-changed={}", asm_name);
135 if std::fs::metadata(".git").is_ok() {
136 let from = format!("{}/lib{}.a", out_dir, name);
137 let prev_metadata = std::fs::metadata(&to);
138 std::fs::copy(&from, &to).unwrap();
139 assert!(
140 prev_metadata.is_ok(),
141 "{} didn't previously exist; please inspect the new file and `git add` it",
142 to
143 );
144 assert!(
145 std::process::Command::new("git")
146 .arg("diff")
147 .arg("--quiet")
148 .arg(&to)
149 .status()
150 .unwrap()
151 .success(),
152 "{} changed; please inspect the change and `git commit` it",
153 to
154 );
155 }
156 }
157 }
158
use_thumb_mode() -> bool159 fn use_thumb_mode() -> bool {
160 // In thumb mode, r7 is reserved.
161 !can_compile("pub unsafe fn f() { core::arch::asm!(\"udf #16\", in(\"r7\") 0); }")
162 }
163
use_feature_or_nothing(feature: &str)164 fn use_feature_or_nothing(feature: &str) {
165 if has_feature(feature) {
166 use_feature(feature);
167 }
168 }
169
use_feature(feature: &str)170 fn use_feature(feature: &str) {
171 println!("cargo:rustc-cfg={}", feature);
172 }
173
174 /// Test whether the rustc at `var("RUSTC")` supports the given feature.
has_feature(feature: &str) -> bool175 fn has_feature(feature: &str) -> bool {
176 can_compile(&format!(
177 "#![allow(stable_features)]\n#![feature({})]",
178 feature
179 ))
180 }
181
182 /// Test whether the rustc at `var("RUSTC")` can compile the given code.
can_compile<T: AsRef<str>>(test: T) -> bool183 fn can_compile<T: AsRef<str>>(test: T) -> bool {
184 use std::process::Stdio;
185
186 let out_dir = var("OUT_DIR").unwrap();
187 let rustc = var("RUSTC").unwrap();
188 let target = var("TARGET").unwrap();
189
190 let mut cmd = if let Ok(wrapper) = var("CARGO_RUSTC_WRAPPER") {
191 let mut cmd = std::process::Command::new(wrapper);
192 // The wrapper's first argument is supposed to be the path to rustc.
193 cmd.arg(rustc);
194 cmd
195 } else {
196 std::process::Command::new(rustc)
197 };
198
199 cmd.arg("--crate-type=rlib") // Don't require `main`.
200 .arg("--emit=metadata") // Do as little as possible but still parse.
201 .arg("--target")
202 .arg(target)
203 .arg("--out-dir")
204 .arg(out_dir); // Put the output somewhere inconsequential.
205
206 // If Cargo wants to set RUSTFLAGS, use that.
207 if let Ok(rustflags) = var("CARGO_ENCODED_RUSTFLAGS") {
208 if !rustflags.is_empty() {
209 for arg in rustflags.split('\x1f') {
210 cmd.arg(arg);
211 }
212 }
213 }
214
215 let mut child = cmd
216 .arg("-") // Read from stdin.
217 .stdin(Stdio::piped()) // Stdin is a pipe.
218 .stderr(Stdio::null()) // Errors from feature detection aren't interesting and can be confusing.
219 .spawn()
220 .unwrap();
221
222 writeln!(child.stdin.take().unwrap(), "{}", test.as_ref()).unwrap();
223
224 child.wait().unwrap().success()
225 }
226