• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 target_os = 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         || target_os != "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     if target_os == "wasi" {
110         use_feature_or_nothing("wasi_ext");
111     }
112     println!("cargo:rerun-if-env-changed=CARGO_CFG_RUSTIX_USE_EXPERIMENTAL_ASM");
113     println!("cargo:rerun-if-env-changed=CARGO_CFG_RUSTIX_USE_LIBC");
114 
115     // Rerun this script if any of our features or configuration flags change,
116     // or if the toolchain we used for feature detection changes.
117     println!("cargo:rerun-if-env-changed=CARGO_FEATURE_USE_LIBC");
118     println!("cargo:rerun-if-env-changed=CARGO_FEATURE_RUSTC_DEP_OF_STD");
119     println!("cargo:rerun-if-env-changed=CARGO_CFG_MIRI");
120 }
121 
122 /// Link in the desired version of librustix_outline_{arch}.a, containing the
123 /// outline assembly code for making syscalls.
link_in_librustix_outline(arch: &str, asm_name: &str)124 fn link_in_librustix_outline(arch: &str, asm_name: &str) {
125     let name = format!("rustix_outline_{}", arch);
126     let profile = var("PROFILE").unwrap();
127     let to = format!("{}/{}/lib{}.a", OUTLINE_PATH, profile, name);
128     println!("cargo:rerun-if-changed={}", to);
129 
130     // If "cc" is not enabled, use a pre-built library.
131     #[cfg(not(feature = "cc"))]
132     {
133         let _ = asm_name;
134         println!("cargo:rustc-link-search={}/{}", OUTLINE_PATH, profile);
135         println!("cargo:rustc-link-lib=static={}", name);
136     }
137 
138     // If "cc" is enabled, build the library from source, update the pre-built
139     // version, and assert that the pre-built version is checked in.
140     #[cfg(feature = "cc")]
141     {
142         let out_dir = var("OUT_DIR").unwrap();
143         Build::new().file(&asm_name).compile(&name);
144         println!("cargo:rerun-if-changed={}", asm_name);
145         if std::fs::metadata(".git").is_ok() {
146             let from = format!("{}/lib{}.a", out_dir, name);
147             let prev_metadata = std::fs::metadata(&to);
148             std::fs::copy(&from, &to).unwrap();
149             assert!(
150                 prev_metadata.is_ok(),
151                 "{} didn't previously exist; please inspect the new file and `git add` it",
152                 to
153             );
154             assert!(
155                 std::process::Command::new("git")
156                     .arg("diff")
157                     .arg("--quiet")
158                     .arg(&to)
159                     .status()
160                     .unwrap()
161                     .success(),
162                 "{} changed; please inspect the change and `git commit` it",
163                 to
164             );
165         }
166     }
167 }
168 
use_thumb_mode() -> bool169 fn use_thumb_mode() -> bool {
170     // In thumb mode, r7 is reserved.
171     !can_compile("pub unsafe fn f() { core::arch::asm!(\"udf #16\", in(\"r7\") 0); }")
172 }
173 
use_feature_or_nothing(feature: &str)174 fn use_feature_or_nothing(feature: &str) {
175     if has_feature(feature) {
176         use_feature(feature);
177     }
178 }
179 
use_feature(feature: &str)180 fn use_feature(feature: &str) {
181     println!("cargo:rustc-cfg={}", feature);
182 }
183 
184 /// Test whether the rustc at `var("RUSTC")` supports the given feature.
has_feature(feature: &str) -> bool185 fn has_feature(feature: &str) -> bool {
186     can_compile(&format!(
187         "#![allow(stable_features)]\n#![feature({})]",
188         feature
189     ))
190 }
191 
192 /// Test whether the rustc at `var("RUSTC")` can compile the given code.
can_compile<T: AsRef<str>>(test: T) -> bool193 fn can_compile<T: AsRef<str>>(test: T) -> bool {
194     use std::process::Stdio;
195 
196     let out_dir = var("OUT_DIR").unwrap();
197     let rustc = var("RUSTC").unwrap();
198     let target = var("TARGET").unwrap();
199 
200     // Use `RUSTC_WRAPPER` if it's set, unless it's set to an empty string,
201     // as documented [here].
202     // [here]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-reads
203     let wrapper = var("RUSTC_WRAPPER")
204         .ok()
205         .and_then(|w| if w.is_empty() { None } else { Some(w) });
206 
207     let mut cmd = if let Some(wrapper) = wrapper {
208         let mut cmd = std::process::Command::new(wrapper);
209         // The wrapper's first argument is supposed to be the path to rustc.
210         cmd.arg(rustc);
211         cmd
212     } else {
213         std::process::Command::new(rustc)
214     };
215 
216     cmd.arg("--crate-type=rlib") // Don't require `main`.
217         .arg("--emit=metadata") // Do as little as possible but still parse.
218         .arg("--target")
219         .arg(target)
220         .arg("--out-dir")
221         .arg(out_dir); // Put the output somewhere inconsequential.
222 
223     // If Cargo wants to set RUSTFLAGS, use that.
224     if let Ok(rustflags) = var("CARGO_ENCODED_RUSTFLAGS") {
225         if !rustflags.is_empty() {
226             for arg in rustflags.split('\x1f') {
227                 cmd.arg(arg);
228             }
229         }
230     }
231 
232     let mut child = cmd
233         .arg("-") // Read from stdin.
234         .stdin(Stdio::piped()) // Stdin is a pipe.
235         .stderr(Stdio::null()) // Errors from feature detection aren't interesting and can be confusing.
236         .spawn()
237         .unwrap();
238 
239     writeln!(child.stdin.take().unwrap(), "{}", test.as_ref()).unwrap();
240 
241     child.wait().unwrap().success()
242 }
243