cargo/core/compiler/build_context/
target_info.rs

1//! This modules contains types storing information of target platforms.
2//!
3//! Normally, call [`RustcTargetData::new`] to construct all the target
4//! platform once, and then query info on your demand. For example,
5//!
6//! * [`RustcTargetData::dep_platform_activated`] to check if platform is activated.
7//! * [`RustcTargetData::info`] to get a [`TargetInfo`] for an in-depth query.
8//! * [`TargetInfo::rustc_outputs`] to get a list of supported file types.
9
10use crate::core::compiler::CompileKind;
11use crate::core::compiler::CompileMode;
12use crate::core::compiler::CompileTarget;
13use crate::core::compiler::CrateType;
14use crate::core::compiler::apply_env_config;
15use crate::core::{Dependency, Package, Target, TargetKind, Workspace};
16use crate::util::context::{GlobalContext, StringList, TargetConfig};
17use crate::util::interning::InternedString;
18use crate::util::{CargoResult, Rustc};
19
20use anyhow::Context as _;
21use cargo_platform::{Cfg, CfgExpr};
22use cargo_util::ProcessBuilder;
23use serde::Deserialize;
24
25use std::cell::RefCell;
26use std::collections::hash_map::{Entry, HashMap};
27use std::path::PathBuf;
28use std::rc::Rc;
29use std::str::{self, FromStr};
30
31/// Information about the platform target gleaned from querying rustc.
32///
33/// [`RustcTargetData`] keeps several of these, one for the host and the others
34/// for other specified targets. If no target is specified, it uses a clone from
35/// the host.
36#[derive(Clone)]
37pub struct TargetInfo {
38    /// A base process builder for discovering crate type information. In
39    /// particular, this is used to determine the output filename prefix and
40    /// suffix for a crate type.
41    crate_type_process: ProcessBuilder,
42    /// Cache of output filename prefixes and suffixes.
43    ///
44    /// The key is the crate type name (like `cdylib`) and the value is
45    /// `Some((prefix, suffix))`, for example `libcargo.so` would be
46    /// `Some(("lib", ".so"))`. The value is `None` if the crate type is not
47    /// supported.
48    crate_types: RefCell<HashMap<CrateType, Option<(String, String)>>>,
49    /// `cfg` information extracted from `rustc --print=cfg`.
50    cfg: Vec<Cfg>,
51    /// `supports_std` information extracted from `rustc --print=target-spec-json`
52    pub supports_std: Option<bool>,
53    /// Supported values for `-Csplit-debuginfo=` flag, queried from rustc
54    support_split_debuginfo: Vec<String>,
55    /// Path to the sysroot.
56    pub sysroot: PathBuf,
57    /// Path to the "lib" directory in the sysroot which rustc uses for linking
58    /// target libraries.
59    pub sysroot_target_libdir: PathBuf,
60    /// Extra flags to pass to `rustc`, see [`extra_args`].
61    pub rustflags: Rc<[String]>,
62    /// Extra flags to pass to `rustdoc`, see [`extra_args`].
63    pub rustdocflags: Rc<[String]>,
64}
65
66/// Kind of each file generated by a Unit, part of `FileType`.
67#[derive(Clone, PartialEq, Eq, Debug)]
68pub enum FileFlavor {
69    /// Not a special file type.
70    Normal,
71    /// Like `Normal`, but not directly executable.
72    /// For example, a `.wasm` file paired with the "normal" `.js` file.
73    Auxiliary,
74    /// Something you can link against (e.g., a library).
75    Linkable,
76    /// An `.rmeta` Rust metadata file.
77    Rmeta,
78    /// Piece of external debug information (e.g., `.dSYM`/`.pdb` file).
79    DebugInfo,
80    /// SBOM (Software Bill of Materials pre-cursor) file (e.g. cargo-sbon.json).
81    Sbom,
82    /// Cross-crate info JSON files generated by rustdoc.
83    DocParts,
84}
85
86/// Type of each file generated by a Unit.
87#[derive(Debug)]
88pub struct FileType {
89    /// The kind of file.
90    pub flavor: FileFlavor,
91    /// The crate-type that generates this file.
92    ///
93    /// `None` for things that aren't associated with a specific crate type,
94    /// for example `rmeta` files.
95    pub crate_type: Option<CrateType>,
96    /// The suffix for the file (for example, `.rlib`).
97    /// This is an empty string for executables on Unix-like platforms.
98    suffix: String,
99    /// The prefix for the file (for example, `lib`).
100    /// This is an empty string for things like executables.
101    prefix: String,
102    /// Flag to convert hyphen to underscore when uplifting.
103    should_replace_hyphens: bool,
104}
105
106impl FileType {
107    /// The filename for this `FileType` created by rustc.
108    pub fn output_filename(&self, target: &Target, metadata: Option<&str>) -> String {
109        match metadata {
110            Some(metadata) => format!(
111                "{}{}-{}{}",
112                self.prefix,
113                target.crate_name(),
114                metadata,
115                self.suffix
116            ),
117            None => format!("{}{}{}", self.prefix, target.crate_name(), self.suffix),
118        }
119    }
120
121    /// The filename for this `FileType` that Cargo should use when "uplifting"
122    /// it to the destination directory.
123    pub fn uplift_filename(&self, target: &Target) -> String {
124        let name = match target.binary_filename() {
125            Some(name) => name,
126            None => {
127                // For binary crate type, `should_replace_hyphens` will always be false.
128                if self.should_replace_hyphens {
129                    target.crate_name()
130                } else {
131                    target.name().to_string()
132                }
133            }
134        };
135
136        format!("{}{}{}", self.prefix, name, self.suffix)
137    }
138
139    /// Creates a new instance representing a `.rmeta` file.
140    pub fn new_rmeta() -> FileType {
141        // Note that even binaries use the `lib` prefix.
142        FileType {
143            flavor: FileFlavor::Rmeta,
144            crate_type: None,
145            suffix: ".rmeta".to_string(),
146            prefix: "lib".to_string(),
147            should_replace_hyphens: true,
148        }
149    }
150}
151
152impl TargetInfo {
153    /// Learns the information of target platform from `rustc` invocation(s).
154    ///
155    /// Generally, the first time calling this function is expensive, as it may
156    /// query `rustc` several times. To reduce the cost, output of each `rustc`
157    /// invocation is cached by [`Rustc::cached_output`].
158    ///
159    /// Search `Tricky` to learn why querying `rustc` several times is needed.
160    #[tracing::instrument(skip_all)]
161    pub fn new(
162        gctx: &GlobalContext,
163        requested_kinds: &[CompileKind],
164        rustc: &Rustc,
165        kind: CompileKind,
166    ) -> CargoResult<TargetInfo> {
167        let mut rustflags =
168            extra_args(gctx, requested_kinds, &rustc.host, None, kind, Flags::Rust)?;
169        let mut turn = 0;
170        loop {
171            let extra_fingerprint = kind.fingerprint_hash();
172
173            // Query rustc for several kinds of info from each line of output:
174            // 0) file-names (to determine output file prefix/suffix for given crate type)
175            // 1) sysroot
176            // 2) split-debuginfo
177            // 3) cfg
178            //
179            // Search `--print` to see what we query so far.
180            let mut process = rustc.workspace_process();
181            apply_env_config(gctx, &mut process)?;
182            process
183                .arg("-")
184                .arg("--crate-name")
185                .arg("___")
186                .arg("--print=file-names")
187                .args(&rustflags)
188                .env_remove("RUSTC_LOG");
189
190            // Removes `FD_CLOEXEC` set by `jobserver::Client` to pass jobserver
191            // as environment variables specify.
192            if let Some(client) = gctx.jobserver_from_env() {
193                process.inherit_jobserver(client);
194            }
195
196            if let CompileKind::Target(target) = kind {
197                process.arg("--target").arg(target.rustc_target());
198            }
199
200            let crate_type_process = process.clone();
201            const KNOWN_CRATE_TYPES: &[CrateType] = &[
202                CrateType::Bin,
203                CrateType::Rlib,
204                CrateType::Dylib,
205                CrateType::Cdylib,
206                CrateType::Staticlib,
207                CrateType::ProcMacro,
208            ];
209            for crate_type in KNOWN_CRATE_TYPES.iter() {
210                process.arg("--crate-type").arg(crate_type.as_str());
211            }
212
213            process.arg("--print=sysroot");
214            process.arg("--print=split-debuginfo");
215            process.arg("--print=crate-name"); // `___` as a delimiter.
216            process.arg("--print=cfg");
217
218            // parse_crate_type() relies on "unsupported/unknown crate type" error message,
219            // so make warnings always emitted as warnings.
220            process.arg("-Wwarnings");
221
222            let (output, error) = rustc
223                .cached_output(&process, extra_fingerprint)
224                .with_context(
225                    || "failed to run `rustc` to learn about target-specific information",
226                )?;
227
228            let mut lines = output.lines();
229            let mut map = HashMap::new();
230            for crate_type in KNOWN_CRATE_TYPES {
231                let out = parse_crate_type(crate_type, &process, &output, &error, &mut lines)?;
232                map.insert(crate_type.clone(), out);
233            }
234
235            let Some(line) = lines.next() else {
236                return error_missing_print_output("sysroot", &process, &output, &error);
237            };
238            let sysroot = PathBuf::from(line);
239            let sysroot_target_libdir = {
240                let mut libdir = sysroot.clone();
241                libdir.push("lib");
242                libdir.push("rustlib");
243                libdir.push(match &kind {
244                    CompileKind::Host => rustc.host.as_str(),
245                    CompileKind::Target(target) => target.short_name(),
246                });
247                libdir.push("lib");
248                libdir
249            };
250
251            let support_split_debuginfo = {
252                // HACK: abuse `--print=crate-name` to use `___` as a delimiter.
253                let mut res = Vec::new();
254                loop {
255                    match lines.next() {
256                        Some(line) if line == "___" => break,
257                        Some(line) => res.push(line.into()),
258                        None => {
259                            return error_missing_print_output(
260                                "split-debuginfo",
261                                &process,
262                                &output,
263                                &error,
264                            );
265                        }
266                    }
267                }
268                res
269            };
270
271            let cfg = lines
272                .map(|line| Ok(Cfg::from_str(line)?))
273                .filter(TargetInfo::not_user_specific_cfg)
274                .collect::<CargoResult<Vec<_>>>()
275                .with_context(|| {
276                    format!(
277                        "failed to parse the cfg from `rustc --print=cfg`, got:\n{}",
278                        output
279                    )
280                })?;
281
282            // recalculate `rustflags` from above now that we have `cfg`
283            // information
284            let new_flags = extra_args(
285                gctx,
286                requested_kinds,
287                &rustc.host,
288                Some(&cfg),
289                kind,
290                Flags::Rust,
291            )?;
292
293            // Tricky: `RUSTFLAGS` defines the set of active `cfg` flags, active
294            // `cfg` flags define which `.cargo/config` sections apply, and they
295            // in turn can affect `RUSTFLAGS`! This is a bona fide mutual
296            // dependency, and it can even diverge (see `cfg_paradox` test).
297            //
298            // So what we do here is running at most *two* iterations of
299            // fixed-point iteration, which should be enough to cover
300            // practically useful cases, and warn if that's not enough for
301            // convergence.
302            let reached_fixed_point = new_flags == rustflags;
303            if !reached_fixed_point && turn == 0 {
304                turn += 1;
305                rustflags = new_flags;
306                continue;
307            }
308            if !reached_fixed_point {
309                gctx.shell().warn("non-trivial mutual dependency between target-specific configuration and RUSTFLAGS")?;
310            }
311
312            let mut supports_std: Option<bool> = None;
313
314            // The '--print=target-spec-json' is an unstable option of rustc, therefore only
315            // try to fetch this information if rustc allows nightly features. Additionally,
316            // to avoid making two rustc queries when not required, only try to fetch the
317            // target-spec when the '-Zbuild-std' option is passed.
318            if gctx.cli_unstable().build_std.is_some() {
319                let mut target_spec_process = rustc.workspace_process();
320                apply_env_config(gctx, &mut target_spec_process)?;
321                target_spec_process
322                    .arg("--print=target-spec-json")
323                    .arg("-Zunstable-options")
324                    .args(&rustflags)
325                    .env_remove("RUSTC_LOG");
326
327                if let CompileKind::Target(target) = kind {
328                    target_spec_process
329                        .arg("--target")
330                        .arg(target.rustc_target());
331                }
332
333                #[derive(Deserialize)]
334                struct Metadata {
335                    pub std: Option<bool>,
336                }
337
338                #[derive(Deserialize)]
339                struct TargetSpec {
340                    pub metadata: Metadata,
341                }
342
343                if let Ok(output) = target_spec_process.output() {
344                    if let Ok(spec) = serde_json::from_slice::<TargetSpec>(&output.stdout) {
345                        supports_std = spec.metadata.std;
346                    }
347                }
348            }
349
350            return Ok(TargetInfo {
351                crate_type_process,
352                crate_types: RefCell::new(map),
353                sysroot,
354                sysroot_target_libdir,
355                rustflags: rustflags.into(),
356                rustdocflags: extra_args(
357                    gctx,
358                    requested_kinds,
359                    &rustc.host,
360                    Some(&cfg),
361                    kind,
362                    Flags::Rustdoc,
363                )?
364                .into(),
365                cfg,
366                supports_std,
367                support_split_debuginfo,
368            });
369        }
370    }
371
372    fn not_user_specific_cfg(cfg: &CargoResult<Cfg>) -> bool {
373        if let Ok(Cfg::Name(cfg_name)) = cfg {
374            // This should also include "debug_assertions", but it causes
375            // regressions. Maybe some day in the distant future it can be
376            // added (and possibly change the warning to an error).
377            if cfg_name == "proc_macro" {
378                return false;
379            }
380        }
381        true
382    }
383
384    /// All the target [`Cfg`] settings.
385    pub fn cfg(&self) -> &[Cfg] {
386        &self.cfg
387    }
388
389    /// Returns the list of file types generated by the given crate type.
390    ///
391    /// Returns `None` if the target does not support the given crate type.
392    fn file_types(
393        &self,
394        crate_type: &CrateType,
395        flavor: FileFlavor,
396        target_triple: &str,
397    ) -> CargoResult<Option<Vec<FileType>>> {
398        let crate_type = if *crate_type == CrateType::Lib {
399            CrateType::Rlib
400        } else {
401            crate_type.clone()
402        };
403
404        let mut crate_types = self.crate_types.borrow_mut();
405        let entry = crate_types.entry(crate_type.clone());
406        let crate_type_info = match entry {
407            Entry::Occupied(o) => &*o.into_mut(),
408            Entry::Vacant(v) => {
409                let value = self.discover_crate_type(v.key())?;
410                &*v.insert(value)
411            }
412        };
413        let Some((prefix, suffix)) = crate_type_info else {
414            return Ok(None);
415        };
416        let mut ret = vec![FileType {
417            suffix: suffix.clone(),
418            prefix: prefix.clone(),
419            flavor,
420            crate_type: Some(crate_type.clone()),
421            should_replace_hyphens: crate_type != CrateType::Bin,
422        }];
423
424        // Window shared library import/export files.
425        if crate_type.is_dynamic() {
426            // Note: Custom JSON specs can alter the suffix. For now, we'll
427            // just ignore non-DLL suffixes.
428            if target_triple.ends_with("-windows-msvc") && suffix == ".dll" {
429                // See https://docs.microsoft.com/en-us/cpp/build/reference/working-with-import-libraries-and-export-files
430                // for more information about DLL import/export files.
431                ret.push(FileType {
432                    suffix: ".dll.lib".to_string(),
433                    prefix: prefix.clone(),
434                    flavor: FileFlavor::Auxiliary,
435                    crate_type: Some(crate_type.clone()),
436                    should_replace_hyphens: true,
437                });
438                // NOTE: lld does not produce these
439                ret.push(FileType {
440                    suffix: ".dll.exp".to_string(),
441                    prefix: prefix.clone(),
442                    flavor: FileFlavor::Auxiliary,
443                    crate_type: Some(crate_type.clone()),
444                    should_replace_hyphens: true,
445                });
446            } else if suffix == ".dll"
447                && (target_triple.ends_with("windows-gnu")
448                    || target_triple.ends_with("windows-gnullvm")
449                    || target_triple.ends_with("cygwin"))
450            {
451                // See https://cygwin.com/cygwin-ug-net/dll.html for more
452                // information about GNU import libraries.
453                // LD can link DLL directly, but LLD requires the import library.
454                ret.push(FileType {
455                    suffix: ".dll.a".to_string(),
456                    prefix: "lib".to_string(),
457                    flavor: FileFlavor::Auxiliary,
458                    crate_type: Some(crate_type.clone()),
459                    should_replace_hyphens: true,
460                })
461            }
462        }
463
464        if target_triple.starts_with("wasm32-") && crate_type == CrateType::Bin && suffix == ".js" {
465            // emscripten binaries generate a .js file, which loads a .wasm
466            // file.
467            ret.push(FileType {
468                suffix: ".wasm".to_string(),
469                prefix: prefix.clone(),
470                flavor: FileFlavor::Auxiliary,
471                crate_type: Some(crate_type.clone()),
472                // Name `foo-bar` will generate a `foo_bar.js` and
473                // `foo_bar.wasm`. Cargo will translate the underscore and
474                // copy `foo_bar.js` to `foo-bar.js`. However, the wasm
475                // filename is embedded in the .js file with an underscore, so
476                // it should not contain hyphens.
477                should_replace_hyphens: true,
478            });
479            // And a map file for debugging. This is only emitted with debug=2
480            // (-g4 for emcc).
481            ret.push(FileType {
482                suffix: ".wasm.map".to_string(),
483                prefix: prefix.clone(),
484                flavor: FileFlavor::DebugInfo,
485                crate_type: Some(crate_type.clone()),
486                should_replace_hyphens: true,
487            });
488        }
489
490        // Handle separate debug files.
491        let is_apple = target_triple.contains("-apple-");
492        if matches!(
493            crate_type,
494            CrateType::Bin | CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro
495        ) {
496            if is_apple {
497                let suffix = if crate_type == CrateType::Bin {
498                    ".dSYM".to_string()
499                } else {
500                    ".dylib.dSYM".to_string()
501                };
502                ret.push(FileType {
503                    suffix,
504                    prefix: prefix.clone(),
505                    flavor: FileFlavor::DebugInfo,
506                    crate_type: Some(crate_type),
507                    // macOS tools like lldb use all sorts of magic to locate
508                    // dSYM files. See https://lldb.llvm.org/use/symbols.html
509                    // for some details. It seems like a `.dSYM` located next
510                    // to the executable with the same name is one method. The
511                    // dSYM should have the same hyphens as the executable for
512                    // the names to match.
513                    should_replace_hyphens: false,
514                })
515            } else if target_triple.ends_with("-msvc") || target_triple.ends_with("-uefi") {
516                ret.push(FileType {
517                    suffix: ".pdb".to_string(),
518                    prefix: prefix.clone(),
519                    flavor: FileFlavor::DebugInfo,
520                    crate_type: Some(crate_type),
521                    // The absolute path to the pdb file is embedded in the
522                    // executable. If the exe/pdb pair is moved to another
523                    // machine, then debuggers will look in the same directory
524                    // of the exe with the original pdb filename. Since the
525                    // original name contains underscores, they need to be
526                    // preserved.
527                    should_replace_hyphens: true,
528                })
529            } else {
530                // Because DWARF Package (dwp) files are produced after the
531                // fact by another tool, there is nothing in the binary that
532                // provides a means to locate them. By convention, debuggers
533                // take the binary filename and append ".dwp" (including to
534                // binaries that already have an extension such as shared libs)
535                // to find the dwp.
536                ret.push(FileType {
537                    // It is important to preserve the existing suffix for
538                    // e.g. shared libraries, where the dwp for libfoo.so is
539                    // expected to be at libfoo.so.dwp.
540                    suffix: format!("{suffix}.dwp"),
541                    prefix: prefix.clone(),
542                    flavor: FileFlavor::DebugInfo,
543                    crate_type: Some(crate_type.clone()),
544                    // Likewise, the dwp needs to match the primary artifact's
545                    // hyphenation exactly.
546                    should_replace_hyphens: crate_type != CrateType::Bin,
547                })
548            }
549        }
550
551        Ok(Some(ret))
552    }
553
554    fn discover_crate_type(&self, crate_type: &CrateType) -> CargoResult<Option<(String, String)>> {
555        let mut process = self.crate_type_process.clone();
556
557        process.arg("--crate-type").arg(crate_type.as_str());
558
559        let output = process.exec_with_output().with_context(|| {
560            format!(
561                "failed to run `rustc` to learn about crate-type {} information",
562                crate_type
563            )
564        })?;
565
566        let error = str::from_utf8(&output.stderr).unwrap();
567        let output = str::from_utf8(&output.stdout).unwrap();
568        parse_crate_type(crate_type, &process, output, error, &mut output.lines())
569    }
570
571    /// Returns all the file types generated by rustc for the given `mode`/`target_kind`.
572    ///
573    /// The first value is a Vec of file types generated, the second value is
574    /// a list of `CrateTypes` that are not supported by the given target.
575    pub fn rustc_outputs(
576        &self,
577        mode: CompileMode,
578        target_kind: &TargetKind,
579        target_triple: &str,
580        gctx: &GlobalContext,
581    ) -> CargoResult<(Vec<FileType>, Vec<CrateType>)> {
582        match mode {
583            CompileMode::Build => self.calc_rustc_outputs(target_kind, target_triple, gctx),
584            CompileMode::Test => {
585                match self.file_types(&CrateType::Bin, FileFlavor::Normal, target_triple)? {
586                    Some(fts) => Ok((fts, Vec::new())),
587                    None => Ok((Vec::new(), vec![CrateType::Bin])),
588                }
589            }
590            CompileMode::Check { .. } => Ok((vec![FileType::new_rmeta()], Vec::new())),
591            CompileMode::Doc { .. }
592            | CompileMode::Doctest
593            | CompileMode::Docscrape
594            | CompileMode::RunCustomBuild => {
595                panic!("asked for rustc output for non-rustc mode")
596            }
597        }
598    }
599
600    fn calc_rustc_outputs(
601        &self,
602        target_kind: &TargetKind,
603        target_triple: &str,
604        gctx: &GlobalContext,
605    ) -> CargoResult<(Vec<FileType>, Vec<CrateType>)> {
606        let mut unsupported = Vec::new();
607        let mut result = Vec::new();
608        let crate_types = target_kind.rustc_crate_types();
609        for crate_type in &crate_types {
610            let flavor = if crate_type.is_linkable() {
611                FileFlavor::Linkable
612            } else {
613                FileFlavor::Normal
614            };
615            let file_types = self.file_types(crate_type, flavor, target_triple)?;
616            match file_types {
617                Some(types) => {
618                    result.extend(types);
619                }
620                None => {
621                    unsupported.push(crate_type.clone());
622                }
623            }
624        }
625        if !result.is_empty() {
626            if gctx.cli_unstable().no_embed_metadata
627                && crate_types
628                    .iter()
629                    .any(|ct| ct.benefits_from_no_embed_metadata())
630            {
631                // Add .rmeta when we apply -Zembed-metadata=no to the unit.
632                result.push(FileType::new_rmeta());
633            } else if !crate_types.iter().any(|ct| ct.requires_upstream_objects()) {
634                // Only add rmeta if pipelining
635                result.push(FileType::new_rmeta());
636            }
637        }
638        Ok((result, unsupported))
639    }
640
641    /// Checks if the debuginfo-split value is supported by this target
642    pub fn supports_debuginfo_split(&self, split: InternedString) -> bool {
643        self.support_split_debuginfo
644            .iter()
645            .any(|sup| sup.as_str() == split.as_str())
646    }
647
648    /// Checks if a target maybe support std.
649    ///
650    /// If no explicitly stated in target spec json, we treat it as "maybe support".
651    ///
652    /// This is only useful for `-Zbuild-std` to determine the default set of
653    /// crates it is going to build.
654    pub fn maybe_support_std(&self) -> bool {
655        matches!(self.supports_std, Some(true) | None)
656    }
657}
658
659/// Takes rustc output (using specialized command line args), and calculates the file prefix and
660/// suffix for the given crate type, or returns `None` if the type is not supported. (e.g., for a
661/// Rust library like `libcargo.rlib`, we have prefix "lib" and suffix "rlib").
662///
663/// The caller needs to ensure that the lines object is at the correct line for the given crate
664/// type: this is not checked.
665///
666/// This function can not handle more than one file per type (with wasm32-unknown-emscripten, there
667/// are two files for bin (`.wasm` and `.js`)).
668fn parse_crate_type(
669    crate_type: &CrateType,
670    cmd: &ProcessBuilder,
671    output: &str,
672    error: &str,
673    lines: &mut str::Lines<'_>,
674) -> CargoResult<Option<(String, String)>> {
675    let not_supported = error.lines().any(|line| {
676        (line.contains("unsupported crate type") || line.contains("unknown crate type"))
677            && line.contains(&format!("crate type `{}`", crate_type))
678    });
679    if not_supported {
680        return Ok(None);
681    }
682    let Some(line) = lines.next() else {
683        anyhow::bail!(
684            "malformed output when learning about crate-type {} information\n{}",
685            crate_type,
686            output_err_info(cmd, output, error)
687        )
688    };
689    let mut parts = line.trim().split("___");
690    let prefix = parts.next().unwrap();
691    let Some(suffix) = parts.next() else {
692        return error_missing_print_output("file-names", cmd, output, error);
693    };
694
695    Ok(Some((prefix.to_string(), suffix.to_string())))
696}
697
698/// Helper for creating an error message for missing output from a certain `--print` request.
699fn error_missing_print_output<T>(
700    request: &str,
701    cmd: &ProcessBuilder,
702    stdout: &str,
703    stderr: &str,
704) -> CargoResult<T> {
705    let err_info = output_err_info(cmd, stdout, stderr);
706    anyhow::bail!(
707        "output of --print={request} missing when learning about \
708     target-specific information from rustc\n{err_info}",
709    )
710}
711
712/// Helper for creating an error message when parsing rustc output fails.
713fn output_err_info(cmd: &ProcessBuilder, stdout: &str, stderr: &str) -> String {
714    let mut result = format!("command was: {}\n", cmd);
715    if !stdout.is_empty() {
716        result.push_str("\n--- stdout\n");
717        result.push_str(stdout);
718    }
719    if !stderr.is_empty() {
720        result.push_str("\n--- stderr\n");
721        result.push_str(stderr);
722    }
723    if stdout.is_empty() && stderr.is_empty() {
724        result.push_str("(no output received)");
725    }
726    result
727}
728
729/// Compiler flags for either rustc or rustdoc.
730#[derive(Debug, Copy, Clone)]
731enum Flags {
732    Rust,
733    Rustdoc,
734}
735
736impl Flags {
737    fn as_key(self) -> &'static str {
738        match self {
739            Flags::Rust => "rustflags",
740            Flags::Rustdoc => "rustdocflags",
741        }
742    }
743
744    fn as_env(self) -> &'static str {
745        match self {
746            Flags::Rust => "RUSTFLAGS",
747            Flags::Rustdoc => "RUSTDOCFLAGS",
748        }
749    }
750}
751
752/// Acquire extra flags to pass to the compiler from various locations.
753///
754/// The locations are:
755///
756///  - the `CARGO_ENCODED_RUSTFLAGS` environment variable
757///  - the `RUSTFLAGS` environment variable
758///
759/// then if none of those were found
760///
761///  - `target.*.rustflags` from the config (.cargo/config)
762///  - `target.cfg(..).rustflags` from the config
763///  - `host.*.rustflags` from the config if compiling a host artifact or without `--target`
764///     (requires `-Zhost-config`)
765///
766/// then if none of those were found
767///
768///  - `build.rustflags` from the config
769///
770/// The behavior differs slightly when cross-compiling (or, specifically, when `--target` is
771/// provided) for artifacts that are always built for the host (plugins, build scripts, ...).
772/// For those artifacts, _only_ `host.*.rustflags` is respected, and no other configuration
773/// sources, _regardless of the value of `target-applies-to-host`_. This is counterintuitive, but
774/// necessary to retain backwards compatibility with older versions of Cargo.
775///
776/// Rules above also applies to rustdoc. Just the key would be `rustdocflags`/`RUSTDOCFLAGS`.
777fn extra_args(
778    gctx: &GlobalContext,
779    requested_kinds: &[CompileKind],
780    host_triple: &str,
781    target_cfg: Option<&[Cfg]>,
782    kind: CompileKind,
783    flags: Flags,
784) -> CargoResult<Vec<String>> {
785    let target_applies_to_host = gctx.target_applies_to_host()?;
786
787    // Host artifacts should not generally pick up rustflags from anywhere except [host].
788    //
789    // The one exception to this is if `target-applies-to-host = true`, which opts into a
790    // particular (inconsistent) past Cargo behavior where host artifacts _do_ pick up rustflags
791    // set elsewhere when `--target` isn't passed.
792    if kind.is_host() {
793        if target_applies_to_host && requested_kinds == [CompileKind::Host] {
794            // This is the past Cargo behavior where we fall back to the same logic as for other
795            // artifacts without --target.
796        } else {
797            // In all other cases, host artifacts just get flags from [host], regardless of
798            // --target. Or, phrased differently, no `--target` behaves the same as `--target
799            // <host>`, and host artifacts are always "special" (they don't pick up `RUSTFLAGS` for
800            // example).
801            return Ok(rustflags_from_host(gctx, flags, host_triple)?.unwrap_or_else(Vec::new));
802        }
803    }
804
805    // All other artifacts pick up the RUSTFLAGS, [target.*], and [build], in that order.
806    // NOTE: It is impossible to have a [host] section and reach this logic with kind.is_host(),
807    // since [host] implies `target-applies-to-host = false`, which always early-returns above.
808
809    if let Some(rustflags) = rustflags_from_env(gctx, flags) {
810        Ok(rustflags)
811    } else if let Some(rustflags) =
812        rustflags_from_target(gctx, host_triple, target_cfg, kind, flags)?
813    {
814        Ok(rustflags)
815    } else if let Some(rustflags) = rustflags_from_build(gctx, flags)? {
816        Ok(rustflags)
817    } else {
818        Ok(Vec::new())
819    }
820}
821
822/// Gets compiler flags from environment variables.
823/// See [`extra_args`] for more.
824fn rustflags_from_env(gctx: &GlobalContext, flags: Flags) -> Option<Vec<String>> {
825    // First try CARGO_ENCODED_RUSTFLAGS from the environment.
826    // Prefer this over RUSTFLAGS since it's less prone to encoding errors.
827    if let Ok(a) = gctx.get_env(format!("CARGO_ENCODED_{}", flags.as_env())) {
828        if a.is_empty() {
829            return Some(Vec::new());
830        }
831        return Some(a.split('\x1f').map(str::to_string).collect());
832    }
833
834    // Then try RUSTFLAGS from the environment
835    if let Ok(a) = gctx.get_env(flags.as_env()) {
836        let args = a
837            .split(' ')
838            .map(str::trim)
839            .filter(|s| !s.is_empty())
840            .map(str::to_string);
841        return Some(args.collect());
842    }
843
844    // No rustflags to be collected from the environment
845    None
846}
847
848/// Gets compiler flags from `[target]` section in the config.
849/// See [`extra_args`] for more.
850fn rustflags_from_target(
851    gctx: &GlobalContext,
852    host_triple: &str,
853    target_cfg: Option<&[Cfg]>,
854    kind: CompileKind,
855    flag: Flags,
856) -> CargoResult<Option<Vec<String>>> {
857    let mut rustflags = Vec::new();
858
859    // Then the target.*.rustflags value...
860    let target = match &kind {
861        CompileKind::Host => host_triple,
862        CompileKind::Target(target) => target.short_name(),
863    };
864    let key = format!("target.{}.{}", target, flag.as_key());
865    if let Some(args) = gctx.get::<Option<StringList>>(&key)? {
866        rustflags.extend(args.as_slice().iter().cloned());
867    }
868    // ...including target.'cfg(...)'.rustflags
869    if let Some(target_cfg) = target_cfg {
870        gctx.target_cfgs()?
871            .iter()
872            .filter_map(|(key, cfg)| {
873                match flag {
874                    Flags::Rust => cfg
875                        .rustflags
876                        .as_ref()
877                        .map(|rustflags| (key, &rustflags.val)),
878                    // `target.cfg(…).rustdocflags` is currently not supported.
879                    Flags::Rustdoc => None,
880                }
881            })
882            .filter(|(key, _rustflags)| CfgExpr::matches_key(key, target_cfg))
883            .for_each(|(_key, cfg_rustflags)| {
884                rustflags.extend(cfg_rustflags.as_slice().iter().cloned());
885            });
886    }
887
888    if rustflags.is_empty() {
889        Ok(None)
890    } else {
891        Ok(Some(rustflags))
892    }
893}
894
895/// Gets compiler flags from `[host]` section in the config.
896/// See [`extra_args`] for more.
897fn rustflags_from_host(
898    gctx: &GlobalContext,
899    flag: Flags,
900    host_triple: &str,
901) -> CargoResult<Option<Vec<String>>> {
902    let target_cfg = gctx.host_cfg_triple(host_triple)?;
903    let list = match flag {
904        Flags::Rust => &target_cfg.rustflags,
905        Flags::Rustdoc => {
906            // host.rustdocflags is not a thing, since it does not make sense
907            return Ok(None);
908        }
909    };
910    Ok(list.as_ref().map(|l| l.val.as_slice().to_vec()))
911}
912
913/// Gets compiler flags from `[build]` section in the config.
914/// See [`extra_args`] for more.
915fn rustflags_from_build(gctx: &GlobalContext, flag: Flags) -> CargoResult<Option<Vec<String>>> {
916    // Then the `build.rustflags` value.
917    let build = gctx.build_config()?;
918    let list = match flag {
919        Flags::Rust => &build.rustflags,
920        Flags::Rustdoc => &build.rustdocflags,
921    };
922    Ok(list.as_ref().map(|l| l.as_slice().to_vec()))
923}
924
925/// Collection of information about `rustc` and the host and target.
926pub struct RustcTargetData<'gctx> {
927    /// Information about `rustc` itself.
928    pub rustc: Rustc,
929
930    /// Config
931    pub gctx: &'gctx GlobalContext,
932    requested_kinds: Vec<CompileKind>,
933
934    /// Build information for the "host", which is information about when
935    /// `rustc` is invoked without a `--target` flag. This is used for
936    /// selecting a linker, and applying link overrides.
937    ///
938    /// The configuration read into this depends on whether or not
939    /// `target-applies-to-host=true`.
940    host_config: TargetConfig,
941    /// Information about the host platform.
942    host_info: TargetInfo,
943
944    /// Build information for targets that we're building for.
945    target_config: HashMap<CompileTarget, TargetConfig>,
946    /// Information about the target platform that we're building for.
947    target_info: HashMap<CompileTarget, TargetInfo>,
948}
949
950impl<'gctx> RustcTargetData<'gctx> {
951    #[tracing::instrument(skip_all)]
952    pub fn new(
953        ws: &Workspace<'gctx>,
954        requested_kinds: &[CompileKind],
955    ) -> CargoResult<RustcTargetData<'gctx>> {
956        let gctx = ws.gctx();
957        let rustc = gctx.load_global_rustc(Some(ws))?;
958        let mut target_config = HashMap::new();
959        let mut target_info = HashMap::new();
960        let target_applies_to_host = gctx.target_applies_to_host()?;
961        let host_target = CompileTarget::new(&rustc.host)?;
962        let host_info = TargetInfo::new(gctx, requested_kinds, &rustc, CompileKind::Host)?;
963
964        // This config is used for link overrides and choosing a linker.
965        let host_config = if target_applies_to_host {
966            gctx.target_cfg_triple(&rustc.host)?
967        } else {
968            gctx.host_cfg_triple(&rustc.host)?
969        };
970
971        // This is a hack. The unit_dependency graph builder "pretends" that
972        // `CompileKind::Host` is `CompileKind::Target(host)` if the
973        // `--target` flag is not specified. Since the unit_dependency code
974        // needs access to the target config data, create a copy so that it
975        // can be found. See `rebuild_unit_graph_shared` for why this is done.
976        if requested_kinds.iter().any(CompileKind::is_host) {
977            target_config.insert(host_target, gctx.target_cfg_triple(&rustc.host)?);
978
979            // If target_applies_to_host is true, the host_info is the target info,
980            // otherwise we need to build target info for the target.
981            if target_applies_to_host {
982                target_info.insert(host_target, host_info.clone());
983            } else {
984                let host_target_info = TargetInfo::new(
985                    gctx,
986                    requested_kinds,
987                    &rustc,
988                    CompileKind::Target(host_target),
989                )?;
990                target_info.insert(host_target, host_target_info);
991            }
992        };
993
994        let mut res = RustcTargetData {
995            rustc,
996            gctx,
997            requested_kinds: requested_kinds.into(),
998            host_config,
999            host_info,
1000            target_config,
1001            target_info,
1002        };
1003
1004        // Get all kinds we currently know about.
1005        //
1006        // For now, targets can only ever come from the root workspace
1007        // units and artifact dependencies, so this
1008        // correctly represents all the kinds that can happen. When we have
1009        // other ways for targets to appear at places that are not the root units,
1010        // we may have to revisit this.
1011        fn artifact_targets(package: &Package) -> impl Iterator<Item = CompileKind> + '_ {
1012            package
1013                .manifest()
1014                .dependencies()
1015                .iter()
1016                .filter_map(|d| d.artifact()?.target()?.to_compile_kind())
1017        }
1018        let all_kinds = requested_kinds
1019            .iter()
1020            .copied()
1021            .chain(ws.members().flat_map(|p| {
1022                p.manifest()
1023                    .default_kind()
1024                    .into_iter()
1025                    .chain(p.manifest().forced_kind())
1026                    .chain(artifact_targets(p))
1027            }));
1028        for kind in all_kinds {
1029            res.merge_compile_kind(kind)?;
1030        }
1031
1032        Ok(res)
1033    }
1034
1035    /// Insert `kind` into our `target_info` and `target_config` members if it isn't present yet.
1036    pub fn merge_compile_kind(&mut self, kind: CompileKind) -> CargoResult<()> {
1037        if let CompileKind::Target(target) = kind {
1038            if !self.target_config.contains_key(&target) {
1039                self.target_config
1040                    .insert(target, self.gctx.target_cfg_triple(target.short_name())?);
1041            }
1042            if !self.target_info.contains_key(&target) {
1043                self.target_info.insert(
1044                    target,
1045                    TargetInfo::new(self.gctx, &self.requested_kinds, &self.rustc, kind)?,
1046                );
1047            }
1048        }
1049        Ok(())
1050    }
1051
1052    /// Returns a "short" name for the given kind, suitable for keying off
1053    /// configuration in Cargo or presenting to users.
1054    pub fn short_name<'a>(&'a self, kind: &'a CompileKind) -> &'a str {
1055        match kind {
1056            CompileKind::Host => &self.rustc.host,
1057            CompileKind::Target(target) => target.short_name(),
1058        }
1059    }
1060
1061    /// Whether a dependency should be compiled for the host or target platform,
1062    /// specified by `CompileKind`.
1063    pub fn dep_platform_activated(&self, dep: &Dependency, kind: CompileKind) -> bool {
1064        // If this dependency is only available for certain platforms,
1065        // make sure we're only enabling it for that platform.
1066        let Some(platform) = dep.platform() else {
1067            return true;
1068        };
1069        let name = self.short_name(&kind);
1070        platform.matches(name, self.cfg(kind))
1071    }
1072
1073    /// Gets the list of `cfg`s printed out from the compiler for the specified kind.
1074    pub fn cfg(&self, kind: CompileKind) -> &[Cfg] {
1075        self.info(kind).cfg()
1076    }
1077
1078    /// Information about the given target platform, learned by querying rustc.
1079    ///
1080    /// # Panics
1081    ///
1082    /// Panics, if the target platform described by `kind` can't be found.
1083    /// See [`get_info`](Self::get_info) for a non-panicking alternative.
1084    pub fn info(&self, kind: CompileKind) -> &TargetInfo {
1085        self.get_info(kind).unwrap()
1086    }
1087
1088    /// Information about the given target platform, learned by querying rustc.
1089    ///
1090    /// Returns `None` if the target platform described by `kind` can't be found.
1091    pub fn get_info(&self, kind: CompileKind) -> Option<&TargetInfo> {
1092        match kind {
1093            CompileKind::Host => Some(&self.host_info),
1094            CompileKind::Target(s) => self.target_info.get(&s),
1095        }
1096    }
1097
1098    /// Gets the target configuration for a particular host or target.
1099    pub fn target_config(&self, kind: CompileKind) -> &TargetConfig {
1100        match kind {
1101            CompileKind::Host => &self.host_config,
1102            CompileKind::Target(s) => &self.target_config[&s],
1103        }
1104    }
1105
1106    pub fn get_unsupported_std_targets(&self) -> Vec<&str> {
1107        let mut unsupported = Vec::new();
1108        for (target, target_info) in &self.target_info {
1109            if target_info.supports_std == Some(false) {
1110                unsupported.push(target.short_name());
1111            }
1112        }
1113        unsupported
1114    }
1115
1116    pub fn requested_kinds(&self) -> &[CompileKind] {
1117        &self.requested_kinds
1118    }
1119}