Skip to main content

run_make_support/external_deps/
rustc.rs

1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::str::FromStr as _;
4
5use crate::command::Command;
6use crate::env::env_var;
7use crate::path_helpers::{cwd, source_root};
8use crate::util::set_host_compiler_dylib_path;
9use crate::{is_aix, is_darwin, is_windows, is_windows_msvc, target, uname};
10
11/// Construct a new `rustc` invocation. This will automatically set the library
12/// search path as `-L cwd()`. Use [`bare_rustc`] to avoid this.
13#[track_caller]
14pub fn rustc() -> Rustc {
15    Rustc::new()
16}
17
18/// Construct a plain `rustc` invocation with no flags set. Note that [`set_host_compiler_dylib_path`]
19/// still presets the environment variable `HOST_RUSTC_DYLIB_PATH` by default.
20#[track_caller]
21pub fn bare_rustc() -> Rustc {
22    Rustc::bare()
23}
24
25/// Construct a plain `rustc` invocation with no flags set that behaves like a stable compiler,
26/// i.e. rejects unstable flags.
27/// Note that [`set_host_compiler_dylib_path`] still presets the environment variable
28/// `HOST_RUSTC_DYLIB_PATH` by default.
29#[track_caller]
30pub fn stable_bare_rustc() -> Rustc {
31    Rustc::bare_stable()
32}
33
34/// Construct a `rustc` invocation for building `minicore`.
35///
36/// This function:
37///
38/// - adds `tests/auxiliary/minicore.rs` as an input
39/// - sets the crate name to `"minicore"`
40/// - sets the crate type to `rlib`
41///
42/// # Example
43///
44/// ```ignore (illustrative)
45/// rustc_minicore().target("wasm32-wasip1").target_cpu("mvp").output("libminicore.rlib").run();
46///
47/// rustc()
48///     .input("foo.rs")
49///     .target("wasm32-wasip1")
50///     .target_cpu("mvp")
51///     .extern_("minicore", path("libminicore.rlib"))
52///     // ...
53///     .run()
54/// ```
55#[track_caller]
56pub fn rustc_minicore() -> Rustc {
57    let mut builder = rustc();
58
59    let minicore_path = source_root().join("tests/auxiliary/minicore.rs");
60    builder.input(minicore_path).crate_name("minicore").crate_type("rlib").edition("2024");
61
62    builder
63}
64
65/// A `rustc` invocation builder.
66#[derive(Debug)]
67#[must_use]
68pub struct Rustc {
69    cmd: Command,
70    target: Option<String>,
71}
72
73// Only fill in the target just before execution, so that it can be overridden.
74crate::macros::impl_common_helpers!(Rustc, |rustc: &mut Rustc| {
75    if let Some(target) = &rustc.target {
76        rustc.cmd.arg(&format!("--target={target}"));
77    }
78});
79
80pub fn rustc_path() -> String {
81    env_var("RUSTC")
82}
83
84#[track_caller]
85fn setup_common() -> Command {
86    let mut cmd = Command::new(rustc_path());
87    set_host_compiler_dylib_path(&mut cmd);
88    cmd
89}
90
91impl Rustc {
92    // `rustc` invocation constructor methods
93
94    /// Construct a new `rustc` invocation. This will automatically set the library
95    /// search path as `-L cwd()`, configure the compilation target and enable
96    /// dynamic linkage by default on musl hosts.
97    /// Use [`bare_rustc`] to avoid this.
98    #[track_caller]
99    pub fn new() -> Self {
100        let mut cmd = setup_common();
101        cmd.arg("-L").arg(cwd());
102
103        // FIXME: On musl hosts, we currently default to static linkage, while
104        // for running run-make tests, we rely on dynamic linkage by default
105        if std::env::var("IS_MUSL_HOST").is_ok_and(|i| i == "1") {
106            cmd.arg("-Ctarget-feature=-crt-static");
107        }
108
109        if let Ok(codegen_backend) = std::env::var("RUSTC_CODEGEN_BACKEND") {
110            cmd.arg(format!("-Zcodegen-backend={codegen_backend}"));
111        }
112
113        // Use a single frontend thread by default, for now
114        cmd.arg("-Zthreads=1");
115
116        // Automatically default to cross-compilation
117        Self { cmd, target: Some(target()) }
118    }
119
120    /// Construct a bare `rustc` invocation with no flags set.
121    #[track_caller]
122    pub fn bare() -> Self {
123        let cmd = setup_common();
124        Self { cmd, target: None }
125    }
126
127    /// Construct a bare `rustc` invocation with no flags set that acts like a stable compiler.
128    #[track_caller]
129    pub fn bare_stable() -> Self {
130        let mut cmd = setup_common();
131        cmd.env("RUSTC_BOOTSTRAP", "-1");
132        Self { cmd, target: None }
133    }
134
135    // Argument provider methods
136
137    /// Configure the compilation environment.
138    pub fn cfg(&mut self, s: &str) -> &mut Self {
139        self.cmd.arg("--cfg");
140        self.cmd.arg(s);
141        self
142    }
143
144    /// Specify default optimization level `-O` (alias for `-C opt-level=3`).
145    pub fn opt(&mut self) -> &mut Self {
146        self.cmd.arg("-O");
147        self
148    }
149
150    /// Specify a specific optimization level.
151    pub fn opt_level(&mut self, option: &str) -> &mut Self {
152        self.cmd.arg(format!("-Copt-level={option}"));
153        self
154    }
155
156    /// Incorporate a hashed string to mangled symbols.
157    pub fn metadata(&mut self, meta: &str) -> &mut Self {
158        self.cmd.arg(format!("-Cmetadata={meta}"));
159        self
160    }
161
162    /// Add a suffix in each output filename.
163    pub fn extra_filename(&mut self, suffix: &str) -> &mut Self {
164        self.cmd.arg(format!("-Cextra-filename={suffix}"));
165        self
166    }
167
168    /// Specify type(s) of output files to generate.
169    pub fn emit<S: AsRef<str>>(&mut self, kinds: S) -> &mut Self {
170        let kinds = kinds.as_ref();
171        self.cmd.arg(format!("--emit={kinds}"));
172        self
173    }
174
175    /// Specify where an external library is located.
176    pub fn extern_<P: AsRef<Path>>(&mut self, crate_name: &str, path: P) -> &mut Self {
177        assert!(
178            !crate_name.contains(|c: char| c.is_whitespace() || c == '\\' || c == '/'),
179            "crate name cannot contain whitespace or path separators"
180        );
181
182        let path = path.as_ref().to_string_lossy();
183
184        self.cmd.arg("--extern");
185        self.cmd.arg(format!("{crate_name}={path}"));
186
187        self
188    }
189
190    /// Remap source path prefixes in all output.
191    pub fn remap_path_prefix<P: AsRef<Path>, P2: AsRef<Path>>(
192        &mut self,
193        from: P,
194        to: P2,
195    ) -> &mut Self {
196        let from = from.as_ref().to_string_lossy();
197        let to = to.as_ref().to_string_lossy();
198
199        self.cmd.arg("--remap-path-prefix");
200        self.cmd.arg(format!("{from}={to}"));
201
202        self
203    }
204
205    /// Specify path to the input file.
206    pub fn input<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
207        self.cmd.arg(path.as_ref());
208        self
209    }
210
211    //Adjust the backtrace level, displaying more detailed information at higher levels.
212    pub fn set_backtrace_level<R: AsRef<OsStr>>(&mut self, level: R) -> &mut Self {
213        self.cmd.env("RUST_BACKTRACE", level);
214        self
215    }
216
217    /// Specify path to the output file. Equivalent to `-o` in rustc.
218    pub fn output<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
219        self.cmd.arg("-o");
220        self.cmd.arg(path.as_ref());
221        self
222    }
223
224    /// Specify path to the output directory. Equivalent to `--out-dir` in rustc.
225    pub fn out_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
226        self.cmd.arg("--out-dir");
227        self.cmd.arg(path.as_ref());
228        self
229    }
230
231    /// This flag enables LTO in the specified form.
232    pub fn lto(&mut self, option: &str) -> &mut Self {
233        self.cmd.arg(format!("-Clto={option}"));
234        self
235    }
236
237    /// This flag defers LTO optimizations to the linker.
238    pub fn linker_plugin_lto(&mut self, option: &str) -> &mut Self {
239        self.cmd.arg(format!("-Clinker-plugin-lto={option}"));
240        self
241    }
242
243    /// Specify what happens when the code panics.
244    pub fn panic(&mut self, option: &str) -> &mut Self {
245        self.cmd.arg(format!("-Cpanic={option}"));
246        self
247    }
248
249    /// Specify number of codegen units
250    pub fn codegen_units(&mut self, units: usize) -> &mut Self {
251        self.cmd.arg(format!("-Ccodegen-units={units}"));
252        self
253    }
254
255    /// Specify directory path used for incremental cache
256    pub fn incremental<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
257        let mut arg = OsString::new();
258        arg.push("-Cincremental=");
259        arg.push(path.as_ref());
260        self.cmd.arg(&arg);
261        self
262    }
263
264    /// Specify directory path used for profile generation
265    pub fn profile_generate<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
266        let mut arg = OsString::new();
267        arg.push("-Cprofile-generate=");
268        arg.push(path.as_ref());
269        self.cmd.arg(&arg);
270        self
271    }
272
273    /// Specify directory path used for profile usage
274    pub fn profile_use<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
275        let mut arg = OsString::new();
276        arg.push("-Cprofile-use=");
277        arg.push(path.as_ref());
278        self.cmd.arg(&arg);
279        self
280    }
281
282    /// Specify option of `-C symbol-mangling-version`.
283    pub fn symbol_mangling_version(&mut self, option: &str) -> &mut Self {
284        self.cmd.arg(format!("-Csymbol-mangling-version={option}"));
285        self
286    }
287
288    /// Specify `-C prefer-dynamic`.
289    pub fn prefer_dynamic(&mut self) -> &mut Self {
290        self.cmd.arg(format!("-Cprefer-dynamic"));
291        self
292    }
293
294    /// Specify error format to use
295    pub fn error_format(&mut self, format: &str) -> &mut Self {
296        self.cmd.arg(format!("--error-format={format}"));
297        self
298    }
299
300    /// Specify json messages printed by the compiler
301    pub fn json(&mut self, items: &str) -> &mut Self {
302        self.cmd.arg(format!("--json={items}"));
303        self
304    }
305
306    /// Normalize the line number in the stderr output
307    pub fn ui_testing(&mut self) -> &mut Self {
308        self.cmd.arg(format!("-Zui-testing"));
309        self
310    }
311
312    /// Specify the target triple, or a path to a custom target json spec file.
313    pub fn target<S: AsRef<str>>(&mut self, target: S) -> &mut Self {
314        // We store the target as a separate field, so that it can be specified multiple times.
315        // This is in particular useful to override the default target set in Rustc::new().
316        self.target = Some(target.as_ref().to_string());
317        self
318    }
319
320    /// Specify the target CPU.
321    pub fn target_cpu<S: AsRef<str>>(&mut self, target_cpu: S) -> &mut Self {
322        let target_cpu = target_cpu.as_ref();
323        self.cmd.arg(format!("-Ctarget-cpu={target_cpu}"));
324        self
325    }
326
327    /// Specify the crate type.
328    pub fn crate_type(&mut self, crate_type: &str) -> &mut Self {
329        self.cmd.arg("--crate-type");
330        self.cmd.arg(crate_type);
331        self
332    }
333
334    /// Add a directory to the library search path. Equivalent to `-L` in rustc.
335    pub fn library_search_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
336        self.cmd.arg("-L");
337        self.cmd.arg(path.as_ref());
338        self
339    }
340
341    /// Add a directory to the library search path with a restriction, where `kind` is a dependency
342    /// type. Equivalent to `-L KIND=PATH` in rustc.
343    pub fn specific_library_search_path<P: AsRef<Path>>(
344        &mut self,
345        kind: &str,
346        path: P,
347    ) -> &mut Self {
348        assert!(["dependency", "native", "all", "framework", "crate"].contains(&kind));
349        let path = path.as_ref().to_string_lossy();
350        self.cmd.arg(format!("-L{kind}={path}"));
351        self
352    }
353
354    /// Override the system root. Equivalent to `--sysroot` in rustc.
355    pub fn sysroot<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
356        self.cmd.arg("--sysroot");
357        self.cmd.arg(path.as_ref());
358        self
359    }
360
361    /// Specify the edition year.
362    pub fn edition(&mut self, edition: &str) -> &mut Self {
363        self.cmd.arg("--edition");
364        self.cmd.arg(edition);
365        self
366    }
367
368    /// Specify the print request.
369    pub fn print(&mut self, request: &str) -> &mut Self {
370        self.cmd.arg("--print");
371        self.cmd.arg(request);
372        self
373    }
374
375    /// Add an extra argument to the linker invocation, via `-Clink-arg`.
376    pub fn link_arg(&mut self, link_arg: &str) -> &mut Self {
377        self.cmd.arg(format!("-Clink-arg={link_arg}"));
378        self
379    }
380
381    /// Add multiple extra arguments to the linker invocation, via `-Clink-args`.
382    pub fn link_args(&mut self, link_args: &str) -> &mut Self {
383        self.cmd.arg(format!("-Clink-args={link_args}"));
384        self
385    }
386
387    /// Specify a stdin input buffer.
388    pub fn stdin_buf<I: AsRef<[u8]>>(&mut self, input: I) -> &mut Self {
389        self.cmd.stdin_buf(input);
390        self
391    }
392
393    /// Specify the crate name.
394    pub fn crate_name<S: AsRef<OsStr>>(&mut self, name: S) -> &mut Self {
395        self.cmd.arg("--crate-name");
396        self.cmd.arg(name.as_ref());
397        self
398    }
399
400    /// Specify the linker
401    pub fn linker(&mut self, linker: &str) -> &mut Self {
402        self.cmd.arg(format!("-Clinker={linker}"));
403        self
404    }
405
406    /// Specify the linker flavor
407    pub fn linker_flavor(&mut self, linker_flavor: &str) -> &mut Self {
408        self.cmd.arg(format!("-Clinker-flavor={linker_flavor}"));
409        self
410    }
411
412    /// Specify `-C debuginfo=...`.
413    pub fn debuginfo(&mut self, level: &str) -> &mut Self {
414        self.cmd.arg(format!("-Cdebuginfo={level}"));
415        self
416    }
417
418    /// Specify `-C split-debuginfo={packed,unpacked,off}`.
419    pub fn split_debuginfo(&mut self, split_kind: &str) -> &mut Self {
420        self.cmd.arg(format!("-Csplit-debuginfo={split_kind}"));
421        self
422    }
423
424    /// Specify `-C link-self-contained={y,n}`.
425    pub fn link_self_contained(&mut self, enabled: bool) -> &mut Self {
426        let enabled = if enabled { "y" } else { "n" };
427        self.cmd.arg(format!("-Clink-self-contained={enabled}"));
428        self
429    }
430
431    pub fn split_dwarf_out_dir(&mut self, out_dir: Option<&str>) -> &mut Self {
432        if let Some(out_dir) = out_dir {
433            self.cmd.arg(format!("-Zsplit-dwarf-out-dir={out_dir}"));
434        }
435        self
436    }
437
438    /// Pass the `--verbose` flag.
439    pub fn verbose(&mut self) -> &mut Self {
440        self.cmd.arg("--verbose");
441        self
442    }
443
444    /// `EXTRARSCXXFLAGS`
445    pub fn extra_rs_cxx_flags(&mut self) -> &mut Self {
446        if is_windows() {
447            // So this is a bit hacky: we can't use the DLL version of libstdc++ because
448            // it pulls in the DLL version of libgcc, which means that we end up with 2
449            // instances of the DW2 unwinding implementation. This is a problem on
450            // i686-pc-windows-gnu because each module (DLL/EXE) needs to register its
451            // unwind information with the unwinding implementation, and libstdc++'s
452            // __cxa_throw won't see the unwinding info we registered with our statically
453            // linked libgcc.
454            //
455            // Now, simply statically linking libstdc++ would fix this problem, except
456            // that it is compiled with the expectation that pthreads is dynamically
457            // linked as a DLL and will fail to link with a statically linked libpthread.
458            //
459            // So we end up with the following hack: we link use static:-bundle to only
460            // link the parts of libstdc++ that we actually use, which doesn't include
461            // the dependency on the pthreads DLL.
462            if !is_windows_msvc() {
463                self.cmd.arg("-lstatic:-bundle=stdc++");
464            };
465        } else if is_darwin() {
466            self.cmd.arg("-lc++");
467        } else if is_aix() {
468            self.cmd.arg("-lc++");
469            self.cmd.arg("-lc++abi");
470        } else {
471            if !matches!(&uname()[..], "FreeBSD" | "SunOS" | "OpenBSD") {
472                self.cmd.arg("-lstdc++");
473            };
474        };
475        self
476    }
477
478    /// Make that the generated LLVM IR is in source order.
479    pub fn codegen_source_order(&mut self) -> &mut Self {
480        self.cmd.arg("-Zcodegen-source-order");
481        self
482    }
483
484    /// Specify `-Z function-sections={yes, no}`.
485    pub fn function_sections(&mut self, enable: bool) -> &mut Self {
486        let flag = match enable {
487            true => "-Zfunction-sections=yes",
488            false => "-Zfunction-sections=no",
489        };
490        self.cmd.arg(flag);
491        self
492    }
493}
494
495/// Query the sysroot path corresponding `rustc --print=sysroot`.
496#[track_caller]
497pub fn sysroot() -> PathBuf {
498    let path = rustc().print("sysroot").run().stdout_utf8();
499    PathBuf::from_str(path.trim()).unwrap()
500}