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