Skip to main content

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