Skip to main content

cargo/core/compiler/
compilation.rs

1//! Type definitions for the result of a compilation.
2
3use std::collections::{BTreeSet, HashMap};
4use std::ffi::{OsStr, OsString};
5use std::path::Path;
6use std::path::PathBuf;
7
8use cargo_platform::CfgExpr;
9use cargo_util::{ProcessBuilder, paths};
10
11use crate::core::Package;
12use crate::core::compiler::BuildContext;
13use crate::core::compiler::CompileTarget;
14use crate::core::compiler::RustdocFingerprint;
15use crate::core::compiler::apply_env_config;
16use crate::core::compiler::{CompileKind, Unit, UnitHash};
17use crate::util::{CargoResult, GlobalContext};
18
19/// Represents the kind of process we are creating.
20#[derive(Debug)]
21enum ToolKind {
22    /// See [`Compilation::rustc_process`].
23    Rustc,
24    /// See [`Compilation::rustdoc_process`].
25    Rustdoc,
26    /// See [`Compilation::host_process`].
27    HostProcess,
28    /// See [`Compilation::target_process`].
29    TargetProcess,
30}
31
32impl ToolKind {
33    fn is_rustc_tool(&self) -> bool {
34        matches!(self, ToolKind::Rustc | ToolKind::Rustdoc)
35    }
36}
37
38/// Structure with enough information to run `rustdoc --test`.
39pub struct Doctest {
40    /// What's being doctested
41    pub unit: Unit,
42    /// Arguments needed to pass to rustdoc to run this test.
43    pub args: Vec<OsString>,
44    /// Whether or not -Zunstable-options is needed.
45    pub unstable_opts: bool,
46    /// The -Clinker value to use.
47    pub linker: Option<PathBuf>,
48    /// The script metadata, if this unit's package has a build script.
49    ///
50    /// This is used for indexing [`Compilation::extra_env`].
51    pub script_metas: Option<Vec<UnitHash>>,
52
53    /// Environment variables to set in the rustdoc process.
54    pub env: HashMap<String, OsString>,
55}
56
57/// Information about the output of a unit.
58pub struct UnitOutput {
59    /// The unit that generated this output.
60    pub unit: Unit,
61    /// Path to the unit's primary output (an executable or cdylib).
62    pub path: PathBuf,
63    /// The script metadata, if this unit's package has a build script.
64    ///
65    /// This is used for indexing [`Compilation::extra_env`].
66    pub script_metas: Option<Vec<UnitHash>>,
67
68    /// Environment variables to set in the unit's process.
69    pub env: HashMap<String, OsString>,
70}
71
72/// A structure returning the result of a compilation.
73pub struct Compilation<'gctx> {
74    /// An array of all tests created during this compilation.
75    pub tests: Vec<UnitOutput>,
76
77    /// An array of all binaries created.
78    pub binaries: Vec<UnitOutput>,
79
80    /// An array of all cdylibs created.
81    pub cdylibs: Vec<UnitOutput>,
82
83    /// The crate names of the root units specified on the command-line.
84    pub root_crate_names: Vec<String>,
85
86    /// All directories for the output of native build commands.
87    ///
88    /// This is currently used to drive some entries which are added to the
89    /// `LD_LIBRARY_PATH` as appropriate.
90    ///
91    /// The order should be deterministic.
92    pub native_dirs: BTreeSet<PathBuf>,
93
94    /// Root output directory (for the local package's artifacts)
95    pub root_output: HashMap<CompileKind, PathBuf>,
96
97    /// Output directory for rust dependencies.
98    /// May be for the host or for a specific target.
99    pub deps_output: HashMap<CompileKind, PathBuf>,
100
101    /// The path to libstd for each target
102    sysroot_target_libdir: HashMap<CompileKind, PathBuf>,
103
104    /// Extra environment variables that were passed to compilations and should
105    /// be passed to future invocations of programs.
106    ///
107    /// The key is the build script metadata for uniquely identifying the
108    /// `RunCustomBuild` unit that generated these env vars.
109    pub extra_env: HashMap<UnitHash, Vec<(String, String)>>,
110
111    /// Libraries to test with rustdoc.
112    pub to_doc_test: Vec<Doctest>,
113
114    /// Rustdoc fingerprint files to determine whether we need to run `rustdoc --merge=finalize`.
115    ///
116    /// See `-Zrustdoc-mergeable-info` for more.
117    pub rustdoc_fingerprints: Option<HashMap<CompileKind, RustdocFingerprint>>,
118
119    /// The target host triple.
120    pub host: String,
121
122    gctx: &'gctx GlobalContext,
123
124    /// Rustc process to be used by default
125    rustc_process: ProcessBuilder,
126    /// Rustc process to be used for workspace crates instead of `rustc_process`
127    rustc_workspace_wrapper_process: ProcessBuilder,
128    /// Optional rustc process to be used for primary crates instead of either `rustc_process` or
129    /// `rustc_workspace_wrapper_process`
130    primary_rustc_process: Option<ProcessBuilder>,
131
132    /// The runner to use for each host or target process.
133    runners: HashMap<CompileKind, Option<(PathBuf, Vec<String>)>>,
134    /// The linker to use for each host or target.
135    linkers: HashMap<CompileKind, Option<PathBuf>>,
136
137    /// The total number of lint warnings emitted by the compilation.
138    pub lint_warning_count: usize,
139}
140
141impl<'gctx> Compilation<'gctx> {
142    pub fn new<'a>(bcx: &BuildContext<'a, 'gctx>) -> CargoResult<Compilation<'gctx>> {
143        let rustc_process = bcx.rustc().process();
144        let primary_rustc_process = bcx.build_config.primary_unit_rustc.clone();
145        let rustc_workspace_wrapper_process = bcx.rustc().workspace_process();
146        let host = bcx.host_triple().to_string();
147        let mut runners = bcx
148            .build_config
149            .requested_kinds
150            .iter()
151            .chain(Some(&CompileKind::Host))
152            .map(|kind| Ok((*kind, target_runner(bcx, *kind)?)))
153            .collect::<CargoResult<HashMap<_, _>>>()?;
154        if !bcx.gctx.target_applies_to_host()? {
155            // When `target-applies-to-host=false`, and without `--target`,
156            // there will be only `CompileKind::Host` in requested_kinds.
157            // Need to insert target config explicitly for target-applies-to-host=false
158            // to find the correct configs.
159            let kind = explicit_host_kind(&host);
160            runners.insert(kind, target_runner(bcx, kind)?);
161        }
162
163        let mut linkers = bcx
164            .build_config
165            .requested_kinds
166            .iter()
167            .chain(Some(&CompileKind::Host))
168            .map(|kind| Ok((*kind, target_linker(bcx, *kind)?)))
169            .collect::<CargoResult<HashMap<_, _>>>()?;
170        if !bcx.gctx.target_applies_to_host()? {
171            // See above reason in runner why we do this.
172            let kind = explicit_host_kind(&host);
173            linkers.insert(kind, target_linker(bcx, kind)?);
174        }
175        Ok(Compilation {
176            native_dirs: BTreeSet::new(),
177            root_output: HashMap::new(),
178            deps_output: HashMap::new(),
179            sysroot_target_libdir: get_sysroot_target_libdir(bcx)?,
180            tests: Vec::new(),
181            binaries: Vec::new(),
182            cdylibs: Vec::new(),
183            root_crate_names: Vec::new(),
184            extra_env: HashMap::new(),
185            to_doc_test: Vec::new(),
186            rustdoc_fingerprints: None,
187            gctx: bcx.gctx,
188            host,
189            rustc_process,
190            rustc_workspace_wrapper_process,
191            primary_rustc_process,
192            runners,
193            linkers,
194            lint_warning_count: 0,
195        })
196    }
197
198    /// Returns a [`ProcessBuilder`] for running `rustc`.
199    ///
200    /// `is_primary` is true if this is a "primary package", which means it
201    /// was selected by the user on the command-line (such as with a `-p`
202    /// flag), see [`crate::core::compiler::BuildRunner::primary_packages`].
203    ///
204    /// `is_workspace` is true if this is a workspace member.
205    pub fn rustc_process(
206        &self,
207        unit: &Unit,
208        is_primary: bool,
209        is_workspace: bool,
210    ) -> CargoResult<ProcessBuilder> {
211        let mut rustc = if is_primary && self.primary_rustc_process.is_some() {
212            self.primary_rustc_process.clone().unwrap()
213        } else if is_workspace {
214            self.rustc_workspace_wrapper_process.clone()
215        } else {
216            self.rustc_process.clone()
217        };
218        if self.gctx.extra_verbose() {
219            rustc.display_env_vars();
220        }
221        let cmd = fill_rustc_tool_env(rustc, unit);
222        self.fill_env(cmd, &unit.pkg, None, unit.kind, ToolKind::Rustc)
223    }
224
225    /// Returns a [`ProcessBuilder`] for running `rustdoc`.
226    pub fn rustdoc_process(
227        &self,
228        unit: &Unit,
229        script_metas: Option<&Vec<UnitHash>>,
230    ) -> CargoResult<ProcessBuilder> {
231        let mut rustdoc = ProcessBuilder::new(&*self.gctx.rustdoc()?);
232        if self.gctx.extra_verbose() {
233            rustdoc.display_env_vars();
234        }
235        let cmd = fill_rustc_tool_env(rustdoc, unit);
236        let mut cmd = self.fill_env(cmd, &unit.pkg, script_metas, unit.kind, ToolKind::Rustdoc)?;
237        cmd.retry_with_argfile(true);
238        unit.target.edition().cmd_edition_arg(&mut cmd);
239
240        for crate_type in unit.target.rustc_crate_types() {
241            cmd.arg("--crate-type").arg(crate_type.as_str());
242        }
243
244        Ok(cmd)
245    }
246
247    /// Returns a [`ProcessBuilder`] appropriate for running a process for the
248    /// host platform.
249    ///
250    /// This is currently only used for running build scripts. If you use this
251    /// for anything else, please be extra careful on how environment
252    /// variables are set!
253    pub fn host_process<T: AsRef<OsStr>>(
254        &self,
255        cmd: T,
256        pkg: &Package,
257    ) -> CargoResult<ProcessBuilder> {
258        // Only use host runner when -Zhost-config is enabled
259        // to ensure `target.<host>.runner` does not wrap build scripts.
260        let builder = if !self.gctx.target_applies_to_host()?
261            && let Some((runner, args)) = self
262                .runners
263                .get(&CompileKind::Host)
264                .and_then(|x| x.as_ref())
265        {
266            let mut builder = ProcessBuilder::new(runner);
267            builder.args(args);
268            builder.arg(cmd);
269            builder
270        } else {
271            ProcessBuilder::new(cmd)
272        };
273        self.fill_env(builder, pkg, None, CompileKind::Host, ToolKind::HostProcess)
274    }
275
276    pub fn target_runner(&self, kind: CompileKind) -> Option<&(PathBuf, Vec<String>)> {
277        let target_applies_to_host = self.gctx.target_applies_to_host().unwrap_or(true);
278        let kind = if !target_applies_to_host && kind.is_host() {
279            // Use explicit host target triple when `target-applies-to-host=false`
280            // This ensures `host.runner` won't be accidentally applied to `cargo run` / `cargo test`.
281            explicit_host_kind(&self.host)
282        } else {
283            kind
284        };
285        self.runners.get(&kind).and_then(|x| x.as_ref())
286    }
287
288    /// Gets the `[host.linker]` for host build target (build scripts and proc macros).
289    pub fn host_linker(&self) -> Option<&Path> {
290        self.linkers
291            .get(&CompileKind::Host)
292            .and_then(|x| x.as_ref())
293            .map(|x| x.as_path())
294    }
295
296    /// Gets the user-specified linker for a particular host or target.
297    pub fn target_linker(&self, kind: CompileKind) -> Option<&Path> {
298        let target_applies_to_host = self.gctx.target_applies_to_host().unwrap_or(true);
299        let kind = if !target_applies_to_host && kind.is_host() {
300            // Use explicit host target triple when `target-applies-to-host=false`
301            // This ensures `host.linker` won't be accidentally applied to normal builds
302            explicit_host_kind(&self.host)
303        } else {
304            kind
305        };
306        self.linkers
307            .get(&kind)
308            .and_then(|x| x.as_ref())
309            .map(|x| x.as_path())
310    }
311
312    /// Returns a [`ProcessBuilder`] appropriate for running a process for the
313    /// target platform. This is typically used for `cargo run` and `cargo
314    /// test`.
315    ///
316    /// `script_metas` is the metadata for the `RunCustomBuild` unit that this
317    /// unit used for its build script. Use `None` if the package did not have
318    /// a build script.
319    pub fn target_process<T: AsRef<OsStr>>(
320        &self,
321        cmd: T,
322        kind: CompileKind,
323        pkg: &Package,
324        script_metas: Option<&Vec<UnitHash>>,
325    ) -> CargoResult<ProcessBuilder> {
326        let builder = if let Some((runner, args)) = self.target_runner(kind) {
327            let mut builder = ProcessBuilder::new(runner);
328            builder.args(args);
329            builder.arg(cmd);
330            builder
331        } else {
332            ProcessBuilder::new(cmd)
333        };
334        let tool_kind = ToolKind::TargetProcess;
335        let mut builder = self.fill_env(builder, pkg, script_metas, kind, tool_kind)?;
336
337        if let Some(client) = self.gctx.jobserver_from_env() {
338            builder.inherit_jobserver(client);
339        }
340
341        Ok(builder)
342    }
343
344    /// Prepares a new process with an appropriate environment to run against
345    /// the artifacts produced by the build process.
346    ///
347    /// The package argument is also used to configure environment variables as
348    /// well as the working directory of the child process.
349    fn fill_env(
350        &self,
351        mut cmd: ProcessBuilder,
352        pkg: &Package,
353        script_metas: Option<&Vec<UnitHash>>,
354        kind: CompileKind,
355        tool_kind: ToolKind,
356    ) -> CargoResult<ProcessBuilder> {
357        let mut search_path = Vec::new();
358        if tool_kind.is_rustc_tool() {
359            if matches!(tool_kind, ToolKind::Rustdoc) {
360                // HACK: `rustdoc --test` not only compiles but executes doctests.
361                // Ideally only execution phase should have search paths appended,
362                // so the executions can find native libs just like other tests.
363                // However, there is no way to separate these two phase, so this
364                // hack is added for both phases.
365                // TODO: handle doctest-xcompile
366                search_path.extend(super::filter_dynamic_search_path(
367                    self.native_dirs.iter(),
368                    &self.root_output[&CompileKind::Host],
369                ));
370            }
371            search_path.push(self.deps_output[&CompileKind::Host].clone());
372        } else {
373            if let Some(path) = self.root_output.get(&kind) {
374                search_path.extend(super::filter_dynamic_search_path(
375                    self.native_dirs.iter(),
376                    path,
377                ));
378                search_path.push(path.clone());
379            }
380            search_path.push(self.deps_output[&kind].clone());
381            // For build-std, we don't want to accidentally pull in any shared
382            // libs from the sysroot that ships with rustc. This may not be
383            // required (at least I cannot craft a situation where it
384            // matters), but is here to be safe.
385            if self.gctx.cli_unstable().build_std.is_none() ||
386                // Proc macros dynamically link to std, so set it anyway.
387                pkg.proc_macro()
388            {
389                search_path.push(self.sysroot_target_libdir[&kind].clone());
390            }
391        }
392
393        let dylib_path = paths::dylib_path();
394        let dylib_path_is_empty = dylib_path.is_empty();
395        if dylib_path.starts_with(&search_path) {
396            search_path = dylib_path;
397        } else {
398            search_path.extend(dylib_path.into_iter());
399        }
400        if cfg!(target_os = "macos") && dylib_path_is_empty {
401            // These are the defaults when DYLD_FALLBACK_LIBRARY_PATH isn't
402            // set or set to an empty string. Since Cargo is explicitly setting
403            // the value, make sure the defaults still work.
404            if let Some(home) = self.gctx.get_env_os("HOME") {
405                search_path.push(PathBuf::from(home).join("lib"));
406            }
407            search_path.push(PathBuf::from("/usr/local/lib"));
408            search_path.push(PathBuf::from("/usr/lib"));
409        }
410        let search_path = paths::join_paths(&search_path, paths::dylib_path_envvar())?;
411
412        cmd.env(paths::dylib_path_envvar(), &search_path);
413        if let Some(meta_vec) = script_metas {
414            for meta in meta_vec {
415                if let Some(env) = self.extra_env.get(meta) {
416                    for (k, v) in env {
417                        cmd.env(k, v);
418                    }
419                }
420            }
421        }
422
423        let cargo_exe = self.gctx.cargo_exe()?;
424        cmd.env(crate::CARGO_ENV, cargo_exe);
425
426        // When adding new environment variables depending on
427        // crate properties which might require rebuild upon change
428        // consider adding the corresponding properties to the hash
429        // in BuildContext::target_metadata()
430        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
431            .env("CARGO_MANIFEST_PATH", pkg.manifest_path())
432            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
433            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
434            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
435            .env("CARGO_PKG_VERSION_PRE", pkg.version().pre.as_str())
436            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
437            .env("CARGO_PKG_NAME", &*pkg.name());
438
439        for (key, value) in pkg.manifest().metadata().env_vars() {
440            cmd.env(key, value.as_ref());
441        }
442
443        cmd.cwd(pkg.root());
444
445        apply_env_config(self.gctx, &mut cmd)?;
446
447        Ok(cmd)
448    }
449}
450
451/// Prepares a `rustc_tool` process with additional environment variables
452/// that are only relevant in a context that has a unit
453fn fill_rustc_tool_env(mut cmd: ProcessBuilder, unit: &Unit) -> ProcessBuilder {
454    if unit.target.is_executable() {
455        let name = unit
456            .target
457            .binary_filename()
458            .unwrap_or(unit.target.name().to_string());
459
460        cmd.env("CARGO_BIN_NAME", name);
461    }
462    cmd.env("CARGO_CRATE_NAME", unit.target.crate_name());
463    cmd
464}
465
466fn get_sysroot_target_libdir(
467    bcx: &BuildContext<'_, '_>,
468) -> CargoResult<HashMap<CompileKind, PathBuf>> {
469    bcx.all_kinds
470        .iter()
471        .map(|&kind| {
472            let Some(info) = bcx.target_data.get_info(kind) else {
473                let target = match kind {
474                    CompileKind::Host => "host".to_owned(),
475                    CompileKind::Target(s) => s.short_name().to_owned(),
476                };
477
478                let dependency = bcx
479                    .unit_graph
480                    .iter()
481                    .find_map(|(u, _)| (u.kind == kind).then_some(u.pkg.summary().package_id()))
482                    .unwrap();
483
484                anyhow::bail!(
485                    "could not find specification for target `{target}`.\n  \
486                    Dependency `{dependency}` requires to build for target `{target}`."
487                )
488            };
489
490            Ok((kind, info.sysroot_target_libdir.clone()))
491        })
492        .collect()
493}
494
495fn target_runner(
496    bcx: &BuildContext<'_, '_>,
497    kind: CompileKind,
498) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
499    if let Some(runner) = bcx.target_data.target_config(kind).runner.as_ref() {
500        let path = runner.val.path.clone().resolve_program(bcx.gctx);
501        return Ok(Some((path, runner.val.args.clone())));
502    }
503
504    // try target.'cfg(...)'.runner
505    let target_cfg = bcx.target_data.info(kind).cfg();
506    let mut cfgs = bcx
507        .gctx
508        .target_cfgs()?
509        .iter()
510        .filter_map(|(key, cfg)| cfg.runner.as_ref().map(|runner| (key, runner)))
511        .filter(|(key, _runner)| CfgExpr::matches_key(key, target_cfg));
512    let matching_runner = cfgs.next();
513    if let Some((key, runner)) = cfgs.next() {
514        anyhow::bail!(
515            "several matching instances of `target.'cfg(..)'.runner` in configurations\n\
516             first match `{}` located in {}\n\
517             second match `{}` located in {}",
518            matching_runner.unwrap().0,
519            matching_runner.unwrap().1.definition,
520            key,
521            runner.definition
522        );
523    }
524    Ok(matching_runner.map(|(_k, runner)| {
525        (
526            runner.val.path.clone().resolve_program(bcx.gctx),
527            runner.val.args.clone(),
528        )
529    }))
530}
531
532/// Gets the user-specified linker for a particular host or target from the configuration.
533fn target_linker(bcx: &BuildContext<'_, '_>, kind: CompileKind) -> CargoResult<Option<PathBuf>> {
534    // Try host.linker and target.{}.linker.
535    if let Some(path) = bcx
536        .target_data
537        .target_config(kind)
538        .linker
539        .as_ref()
540        .map(|l| l.val.clone().resolve_program(bcx.gctx))
541    {
542        return Ok(Some(path));
543    }
544
545    // Try target.'cfg(...)'.linker.
546    let target_cfg = bcx.target_data.info(kind).cfg();
547    let mut cfgs = bcx
548        .gctx
549        .target_cfgs()?
550        .iter()
551        .filter_map(|(key, cfg)| cfg.linker.as_ref().map(|linker| (key, linker)))
552        .filter(|(key, _linker)| CfgExpr::matches_key(key, target_cfg));
553    let matching_linker = cfgs.next();
554    if let Some((key, linker)) = cfgs.next() {
555        anyhow::bail!(
556            "several matching instances of `target.'cfg(..)'.linker` in configurations\n\
557             first match `{}` located in {}\n\
558             second match `{}` located in {}",
559            matching_linker.unwrap().0,
560            matching_linker.unwrap().1.definition,
561            key,
562            linker.definition
563        );
564    }
565    Ok(matching_linker.map(|(_k, linker)| linker.val.clone().resolve_program(bcx.gctx)))
566}
567
568fn explicit_host_kind(host: &str) -> CompileKind {
569    let target = CompileTarget::new(host, false).expect("must be a host tuple");
570    CompileKind::Target(target)
571}