Skip to main content

cargo/core/compiler/build_context/
mod.rs

1use std::collections::HashMap;
2use std::env;
3use std::path::{Path, PathBuf};
4use std::str;
5
6use log::debug;
7
8use crate::core::profiles::Profiles;
9use crate::core::{Dependency, Workspace};
10use crate::core::{PackageId, PackageSet, Resolve};
11use crate::util::errors::CargoResult;
12use crate::util::{profile, Cfg, CfgExpr, Config, Rustc};
13
14use super::{BuildConfig, BuildOutput, Kind, Unit};
15
16mod target_info;
17pub use self::target_info::{FileFlavor, TargetInfo};
18
19/// The build context, containing all information about a build task
20pub struct BuildContext<'a, 'cfg: 'a> {
21    /// The workspace the build is for
22    pub ws: &'a Workspace<'cfg>,
23    /// The cargo configuration
24    pub config: &'cfg Config,
25    /// The dependency graph for our build
26    pub resolve: &'a Resolve,
27    pub profiles: &'a Profiles,
28    pub build_config: &'a BuildConfig,
29    /// Extra compiler args for either `rustc` or `rustdoc`.
30    pub extra_compiler_args: HashMap<Unit<'a>, Vec<String>>,
31    pub packages: &'a PackageSet<'cfg>,
32
33    /// Information about the compiler
34    pub rustc: Rustc,
35    /// Build information for the host arch
36    pub host_config: TargetConfig,
37    /// Build information for the target
38    pub target_config: TargetConfig,
39    pub target_info: TargetInfo,
40    pub host_info: TargetInfo,
41    pub incremental_env: Option<bool>,
42}
43
44impl<'a, 'cfg> BuildContext<'a, 'cfg> {
45    pub fn new(
46        ws: &'a Workspace<'cfg>,
47        resolve: &'a Resolve,
48        packages: &'a PackageSet<'cfg>,
49        config: &'cfg Config,
50        build_config: &'a BuildConfig,
51        profiles: &'a Profiles,
52        extra_compiler_args: HashMap<Unit<'a>, Vec<String>>,
53    ) -> CargoResult<BuildContext<'a, 'cfg>> {
54        let incremental_env = match env::var("CARGO_INCREMENTAL") {
55            Ok(v) => Some(v == "1"),
56            Err(_) => None,
57        };
58
59        let rustc = config.rustc(Some(ws))?;
60        let host_config = TargetConfig::new(config, &rustc.host)?;
61        let target_config = match build_config.requested_target.as_ref() {
62            Some(triple) => TargetConfig::new(config, triple)?,
63            None => host_config.clone(),
64        };
65        let (host_info, target_info) = {
66            let _p = profile::start("BuildContext::probe_target_info");
67            debug!("probe_target_info");
68            let host_info =
69                TargetInfo::new(config, &build_config.requested_target, &rustc, Kind::Host)?;
70            let target_info =
71                TargetInfo::new(config, &build_config.requested_target, &rustc, Kind::Target)?;
72            (host_info, target_info)
73        };
74
75        Ok(BuildContext {
76            ws,
77            resolve,
78            packages,
79            config,
80            rustc,
81            target_config,
82            target_info,
83            host_config,
84            host_info,
85            build_config,
86            profiles,
87            incremental_env,
88            extra_compiler_args,
89        })
90    }
91
92    pub fn extern_crate_name(&self, unit: &Unit<'a>, dep: &Unit<'a>) -> CargoResult<String> {
93        self.resolve
94            .extern_crate_name(unit.pkg.package_id(), dep.pkg.package_id(), dep.target)
95    }
96
97    /// Whether a dependency should be compiled for the host or target platform,
98    /// specified by `Kind`.
99    pub fn dep_platform_activated(&self, dep: &Dependency, kind: Kind) -> bool {
100        // If this dependency is only available for certain platforms,
101        // make sure we're only enabling it for that platform.
102        let platform = match dep.platform() {
103            Some(p) => p,
104            None => return true,
105        };
106        let (name, info) = match kind {
107            Kind::Host => (self.host_triple(), &self.host_info),
108            Kind::Target => (self.target_triple(), &self.target_info),
109        };
110        platform.matches(name, info.cfg())
111    }
112
113    /// Get the user-specified linker for a particular host or target
114    pub fn linker(&self, kind: Kind) -> Option<&Path> {
115        self.target_config(kind).linker.as_ref().map(|s| s.as_ref())
116    }
117
118    /// Get the user-specified `ar` program for a particular host or target
119    pub fn ar(&self, kind: Kind) -> Option<&Path> {
120        self.target_config(kind).ar.as_ref().map(|s| s.as_ref())
121    }
122
123    /// Get the list of cfg printed out from the compiler for the specified kind
124    pub fn cfg(&self, kind: Kind) -> &[Cfg] {
125        let info = match kind {
126            Kind::Host => &self.host_info,
127            Kind::Target => &self.target_info,
128        };
129        info.cfg().unwrap_or(&[])
130    }
131
132    /// The host arch triple
133    ///
134    /// e.g. x86_64-unknown-linux-gnu, would be
135    ///  - machine: x86_64
136    ///  - hardware-platform: unknown
137    ///  - operating system: linux-gnu
138    pub fn host_triple(&self) -> &str {
139        &self.rustc.host
140    }
141
142    pub fn target_triple(&self) -> &str {
143        self.build_config
144            .requested_target
145            .as_ref()
146            .map(|s| s.as_str())
147            .unwrap_or_else(|| self.host_triple())
148    }
149
150    /// Get the target configuration for a particular host or target
151    fn target_config(&self, kind: Kind) -> &TargetConfig {
152        match kind {
153            Kind::Host => &self.host_config,
154            Kind::Target => &self.target_config,
155        }
156    }
157
158    /// Number of jobs specified for this build
159    pub fn jobs(&self) -> u32 {
160        self.build_config.jobs
161    }
162
163    pub fn rustflags_args(&self, unit: &Unit<'_>) -> CargoResult<Vec<String>> {
164        env_args(
165            self.config,
166            &self.build_config.requested_target,
167            self.host_triple(),
168            self.info(unit.kind).cfg(),
169            unit.kind,
170            "RUSTFLAGS",
171        )
172    }
173
174    pub fn rustdocflags_args(&self, unit: &Unit<'_>) -> CargoResult<Vec<String>> {
175        env_args(
176            self.config,
177            &self.build_config.requested_target,
178            self.host_triple(),
179            self.info(unit.kind).cfg(),
180            unit.kind,
181            "RUSTDOCFLAGS",
182        )
183    }
184
185    pub fn show_warnings(&self, pkg: PackageId) -> bool {
186        pkg.source_id().is_path() || self.config.extra_verbose()
187    }
188
189    fn info(&self, kind: Kind) -> &TargetInfo {
190        match kind {
191            Kind::Host => &self.host_info,
192            Kind::Target => &self.target_info,
193        }
194    }
195
196    pub fn extra_args_for(&self, unit: &Unit<'a>) -> Option<&Vec<String>> {
197        self.extra_compiler_args.get(unit)
198    }
199}
200
201/// Information required to build for a target
202#[derive(Clone, Default)]
203pub struct TargetConfig {
204    /// The path of archiver (lib builder) for this target.
205    pub ar: Option<PathBuf>,
206    /// The path of the linker for this target.
207    pub linker: Option<PathBuf>,
208    /// Special build options for any necessary input files (filename -> options)
209    pub overrides: HashMap<String, BuildOutput>,
210}
211
212impl TargetConfig {
213    pub fn new(config: &Config, triple: &str) -> CargoResult<TargetConfig> {
214        let key = format!("target.{}", triple);
215        let mut ret = TargetConfig {
216            ar: config.get_path(&format!("{}.ar", key))?.map(|v| v.val),
217            linker: config.get_path(&format!("{}.linker", key))?.map(|v| v.val),
218            overrides: HashMap::new(),
219        };
220        let table = match config.get_table(&key)? {
221            Some(table) => table.val,
222            None => return Ok(ret),
223        };
224        for (lib_name, value) in table {
225            match lib_name.as_str() {
226                "ar" | "linker" | "runner" | "rustflags" => continue,
227                _ => {}
228            }
229
230            let mut output = BuildOutput {
231                library_paths: Vec::new(),
232                library_links: Vec::new(),
233                cfgs: Vec::new(),
234                env: Vec::new(),
235                metadata: Vec::new(),
236                rerun_if_changed: Vec::new(),
237                rerun_if_env_changed: Vec::new(),
238                warnings: Vec::new(),
239            };
240            // We require deterministic order of evaluation, so we must sort the pairs by key first.
241            let mut pairs = Vec::new();
242            for (k, value) in value.table(&lib_name)?.0 {
243                pairs.push((k, value));
244            }
245            pairs.sort_by_key(|p| p.0);
246            for (k, value) in pairs {
247                let key = format!("{}.{}", key, k);
248                match &k[..] {
249                    "rustc-flags" => {
250                        let (flags, definition) = value.string(k)?;
251                        let whence = format!("in `{}` (in {})", key, definition.display());
252                        let (paths, links) = BuildOutput::parse_rustc_flags(flags, &whence)?;
253                        output.library_paths.extend(paths);
254                        output.library_links.extend(links);
255                    }
256                    "rustc-link-lib" => {
257                        let list = value.list(k)?;
258                        output
259                            .library_links
260                            .extend(list.iter().map(|v| v.0.clone()));
261                    }
262                    "rustc-link-search" => {
263                        let list = value.list(k)?;
264                        output
265                            .library_paths
266                            .extend(list.iter().map(|v| PathBuf::from(&v.0)));
267                    }
268                    "rustc-cfg" => {
269                        let list = value.list(k)?;
270                        output.cfgs.extend(list.iter().map(|v| v.0.clone()));
271                    }
272                    "rustc-env" => {
273                        for (name, val) in value.table(k)?.0 {
274                            let val = val.string(name)?.0;
275                            output.env.push((name.clone(), val.to_string()));
276                        }
277                    }
278                    "warning" | "rerun-if-changed" | "rerun-if-env-changed" => {
279                        failure::bail!("`{}` is not supported in build script overrides", k);
280                    }
281                    _ => {
282                        let val = value.string(k)?.0;
283                        output.metadata.push((k.clone(), val.to_string()));
284                    }
285                }
286            }
287            ret.overrides.insert(lib_name, output);
288        }
289
290        Ok(ret)
291    }
292}
293
294/// Acquire extra flags to pass to the compiler from various locations.
295///
296/// The locations are:
297///
298///  - the `RUSTFLAGS` environment variable
299///
300/// then if this was not found
301///
302///  - `target.*.rustflags` from the manifest (Cargo.toml)
303///  - `target.cfg(..).rustflags` from the manifest
304///
305/// then if neither of these were found
306///
307///  - `build.rustflags` from the manifest
308///
309/// Note that if a `target` is specified, no args will be passed to host code (plugins, build
310/// scripts, ...), even if it is the same as the target.
311fn env_args(
312    config: &Config,
313    requested_target: &Option<String>,
314    host_triple: &str,
315    target_cfg: Option<&[Cfg]>,
316    kind: Kind,
317    name: &str,
318) -> CargoResult<Vec<String>> {
319    // We *want* to apply RUSTFLAGS only to builds for the
320    // requested target architecture, and not to things like build
321    // scripts and plugins, which may be for an entirely different
322    // architecture. Cargo's present architecture makes it quite
323    // hard to only apply flags to things that are not build
324    // scripts and plugins though, so we do something more hacky
325    // instead to avoid applying the same RUSTFLAGS to multiple targets
326    // arches:
327    //
328    // 1) If --target is not specified we just apply RUSTFLAGS to
329    // all builds; they are all going to have the same target.
330    //
331    // 2) If --target *is* specified then we only apply RUSTFLAGS
332    // to compilation units with the Target kind, which indicates
333    // it was chosen by the --target flag.
334    //
335    // This means that, e.g. even if the specified --target is the
336    // same as the host, build scripts in plugins won't get
337    // RUSTFLAGS.
338    let compiling_with_target = requested_target.is_some();
339    let is_target_kind = kind == Kind::Target;
340
341    if compiling_with_target && !is_target_kind {
342        // This is probably a build script or plugin and we're
343        // compiling with --target. In this scenario there are
344        // no rustflags we can apply.
345        return Ok(Vec::new());
346    }
347
348    // First try RUSTFLAGS from the environment
349    if let Ok(a) = env::var(name) {
350        let args = a
351            .split(' ')
352            .map(str::trim)
353            .filter(|s| !s.is_empty())
354            .map(str::to_string);
355        return Ok(args.collect());
356    }
357
358    let mut rustflags = Vec::new();
359
360    let name = name
361        .chars()
362        .flat_map(|c| c.to_lowercase())
363        .collect::<String>();
364    // Then the target.*.rustflags value...
365    let target = requested_target
366        .as_ref()
367        .map(|s| s.as_str())
368        .unwrap_or(host_triple);
369    let key = format!("target.{}.{}", target, name);
370    if let Some(args) = config.get_list_or_split_string(&key)? {
371        let args = args.val.into_iter();
372        rustflags.extend(args);
373    }
374    // ...including target.'cfg(...)'.rustflags
375    if let Some(target_cfg) = target_cfg {
376        if let Some(table) = config.get_table("target")? {
377            let cfgs = table
378                .val
379                .keys()
380                .filter(|key| CfgExpr::matches_key(key, target_cfg));
381
382            // Note that we may have multiple matching `[target]` sections and
383            // because we're passing flags to the compiler this can affect
384            // cargo's caching and whether it rebuilds. Ensure a deterministic
385            // ordering through sorting for now. We may perhaps one day wish to
386            // ensure a deterministic ordering via the order keys were defined
387            // in files perhaps.
388            let mut cfgs = cfgs.collect::<Vec<_>>();
389            cfgs.sort();
390
391            for n in cfgs {
392                let key = format!("target.{}.{}", n, name);
393                if let Some(args) = config.get_list_or_split_string(&key)? {
394                    let args = args.val.into_iter();
395                    rustflags.extend(args);
396                }
397            }
398        }
399    }
400
401    if !rustflags.is_empty() {
402        return Ok(rustflags);
403    }
404
405    // Then the build.rustflags value
406    let key = format!("build.{}", name);
407    if let Some(args) = config.get_list_or_split_string(&key)? {
408        let args = args.val.into_iter();
409        return Ok(args.collect());
410    }
411
412    Ok(Vec::new())
413}