Skip to main content

cargo/core/compiler/context/
mod.rs

1#![allow(deprecated)]
2use std::collections::{HashMap, HashSet};
3use std::ffi::OsStr;
4use std::fmt::Write;
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use jobserver::Client;
9
10use crate::core::compiler::compilation;
11use crate::core::profiles::Profile;
12use crate::core::{Package, PackageId, Resolve, Target};
13use crate::util::errors::{CargoResult, CargoResultExt};
14use crate::util::{internal, profile, short_hash, Config};
15
16use super::build_plan::BuildPlan;
17use super::custom_build::{self, BuildDeps, BuildScripts, BuildState};
18use super::fingerprint::Fingerprint;
19use super::job_queue::JobQueue;
20use super::layout::Layout;
21use super::{BuildContext, Compilation, CompileMode, Executor, FileFlavor, Kind};
22
23mod unit_dependencies;
24use self::unit_dependencies::build_unit_dependencies;
25
26mod compilation_files;
27use self::compilation_files::CompilationFiles;
28pub use self::compilation_files::{Metadata, OutputFile};
29
30/// All information needed to define a Unit.
31///
32/// A unit is an object that has enough information so that cargo knows how to build it.
33/// For example, if your package has dependencies, then every dependency will be built as a library
34/// unit. If your package is a library, then it will be built as a library unit as well, or if it
35/// is a binary with `main.rs`, then a binary will be output. There are also separate unit types
36/// for `test`ing and `check`ing, amongst others.
37///
38/// The unit also holds information about all possible metadata about the package in `pkg`.
39///
40/// A unit needs to know extra information in addition to the type and root source file. For
41/// example, it needs to know the target architecture (OS, chip arch etc.) and it needs to know
42/// whether you want a debug or release build. There is enough information in this struct to figure
43/// all that out.
44#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug, PartialOrd, Ord)]
45pub struct Unit<'a> {
46    /// Information about available targets, which files to include/exclude, etc. Basically stuff in
47    /// `Cargo.toml`.
48    pub pkg: &'a Package,
49    /// Information about the specific target to build, out of the possible targets in `pkg`. Not
50    /// to be confused with *target-triple* (or *target architecture* ...), the target arch for a
51    /// build.
52    pub target: &'a Target,
53    /// The profile contains information about *how* the build should be run, including debug
54    /// level, etc.
55    pub profile: Profile,
56    /// Whether this compilation unit is for the host or target architecture.
57    ///
58    /// For example, when
59    /// cross compiling and using a custom build script, the build script needs to be compiled for
60    /// the host architecture so the host rustc can use it (when compiling to the target
61    /// architecture).
62    pub kind: Kind,
63    /// The "mode" this unit is being compiled for.  See `CompileMode` for
64    /// more details.
65    pub mode: CompileMode,
66}
67
68impl<'a> Unit<'a> {
69    pub fn buildkey(&self) -> String {
70        format!("{}-{}", self.pkg.name(), short_hash(self))
71    }
72}
73
74pub struct Context<'a, 'cfg: 'a> {
75    pub bcx: &'a BuildContext<'a, 'cfg>,
76    pub compilation: Compilation<'cfg>,
77    pub build_state: Arc<BuildState>,
78    pub build_script_overridden: HashSet<(PackageId, Kind)>,
79    pub build_explicit_deps: HashMap<Unit<'a>, BuildDeps>,
80    pub fingerprints: HashMap<Unit<'a>, Arc<Fingerprint>>,
81    pub compiled: HashSet<Unit<'a>>,
82    pub build_scripts: HashMap<Unit<'a>, Arc<BuildScripts>>,
83    pub links: Links,
84    pub jobserver: Client,
85    primary_packages: HashSet<PackageId>,
86    unit_dependencies: HashMap<Unit<'a>, Vec<Unit<'a>>>,
87    files: Option<CompilationFiles<'a, 'cfg>>,
88    package_cache: HashMap<PackageId, &'a Package>,
89}
90
91impl<'a, 'cfg> Context<'a, 'cfg> {
92    pub fn new(config: &'cfg Config, bcx: &'a BuildContext<'a, 'cfg>) -> CargoResult<Self> {
93        // Load up the jobserver that we'll use to manage our parallelism. This
94        // is the same as the GNU make implementation of a jobserver, and
95        // intentionally so! It's hoped that we can interact with GNU make and
96        // all share the same jobserver.
97        //
98        // Note that if we don't have a jobserver in our environment then we
99        // create our own, and we create it with `n-1` tokens because one token
100        // is ourself, a running process.
101        let jobserver = match config.jobserver_from_env() {
102            Some(c) => c.clone(),
103            None => Client::new(bcx.build_config.jobs as usize - 1)
104                .chain_err(|| "failed to create jobserver")?,
105        };
106
107        Ok(Self {
108            bcx,
109            compilation: Compilation::new(bcx)?,
110            build_state: Arc::new(BuildState::new(&bcx.host_config, &bcx.target_config)),
111            fingerprints: HashMap::new(),
112            compiled: HashSet::new(),
113            build_scripts: HashMap::new(),
114            build_explicit_deps: HashMap::new(),
115            links: Links::new(),
116            jobserver,
117            build_script_overridden: HashSet::new(),
118
119            primary_packages: HashSet::new(),
120            unit_dependencies: HashMap::new(),
121            files: None,
122            package_cache: HashMap::new(),
123        })
124    }
125
126    // Returns a mapping of the root package plus its immediate dependencies to
127    // where the compiled libraries are all located.
128    pub fn compile(
129        mut self,
130        units: &[Unit<'a>],
131        export_dir: Option<PathBuf>,
132        exec: &Arc<dyn Executor>,
133    ) -> CargoResult<Compilation<'cfg>> {
134        let mut queue = JobQueue::new(self.bcx);
135        let mut plan = BuildPlan::new();
136        let build_plan = self.bcx.build_config.build_plan;
137        self.prepare_units(export_dir, units)?;
138        self.prepare()?;
139        custom_build::build_map(&mut self, units)?;
140        self.check_collistions()?;
141
142        for unit in units.iter() {
143            // Build up a list of pending jobs, each of which represent
144            // compiling a particular package. No actual work is executed as
145            // part of this, that's all done next as part of the `execute`
146            // function which will run everything in order with proper
147            // parallelism.
148            let force_rebuild = self.bcx.build_config.force_rebuild;
149            super::compile(&mut self, &mut queue, &mut plan, unit, exec, force_rebuild)?;
150        }
151
152        // Now that we've figured out everything that we're going to do, do it!
153        queue.execute(&mut self, &mut plan)?;
154
155        if build_plan {
156            plan.set_inputs(self.build_plan_inputs()?);
157            plan.output_plan();
158        }
159
160        for unit in units.iter() {
161            for output in self.outputs(unit)?.iter() {
162                if output.flavor == FileFlavor::DebugInfo {
163                    continue;
164                }
165
166                let bindst = output.bin_dst();
167
168                if unit.mode == CompileMode::Test {
169                    self.compilation.tests.push((
170                        unit.pkg.clone(),
171                        unit.target.kind().clone(),
172                        unit.target.name().to_string(),
173                        output.path.clone(),
174                    ));
175                } else if unit.target.is_bin() || unit.target.is_bin_example() {
176                    self.compilation.binaries.push(bindst.clone());
177                } else if unit.target.is_lib() {
178                    let pkgid = unit.pkg.package_id().clone();
179                    self.compilation
180                        .libraries
181                        .entry(pkgid)
182                        .or_insert_with(HashSet::new)
183                        .insert((unit.target.clone(), output.path.clone()));
184                }
185            }
186
187            for dep in self.dep_targets(unit).iter() {
188                if !unit.target.is_lib() {
189                    continue;
190                }
191
192                if dep.mode.is_run_custom_build() {
193                    let out_dir = self.files().build_script_out_dir(dep).display().to_string();
194                    self.compilation
195                        .extra_env
196                        .entry(dep.pkg.package_id())
197                        .or_insert_with(Vec::new)
198                        .push(("OUT_DIR".to_string(), out_dir));
199                }
200
201                if !dep.target.is_lib() {
202                    continue;
203                }
204                if dep.mode.is_doc() {
205                    continue;
206                }
207
208                let outputs = self.outputs(dep)?;
209                self.compilation
210                    .libraries
211                    .entry(unit.pkg.package_id().clone())
212                    .or_insert_with(HashSet::new)
213                    .extend(
214                        outputs
215                            .iter()
216                            .map(|output| (dep.target.clone(), output.path.clone())),
217                    );
218            }
219
220            if unit.mode == CompileMode::Doctest {
221                // Note that we can *only* doctest rlib outputs here.  A
222                // staticlib output cannot be linked by the compiler (it just
223                // doesn't do that). A dylib output, however, can be linked by
224                // the compiler, but will always fail. Currently all dylibs are
225                // built as "static dylibs" where the standard library is
226                // statically linked into the dylib. The doc tests fail,
227                // however, for now as they try to link the standard library
228                // dynamically as well, causing problems. As a result we only
229                // pass `--extern` for rlib deps and skip out on all other
230                // artifacts.
231                let mut doctest_deps = Vec::new();
232                for dep in self.dep_targets(unit) {
233                    if dep.target.is_lib() && dep.mode == CompileMode::Build {
234                        let outputs = self.outputs(&dep)?;
235                        let outputs = outputs.iter().filter(|output| {
236                            output.path.extension() == Some(OsStr::new("rlib"))
237                                || dep.target.for_host()
238                        });
239                        for output in outputs {
240                            doctest_deps.push((
241                                self.bcx.extern_crate_name(unit, &dep)?,
242                                output.path.clone(),
243                            ));
244                        }
245                    }
246                }
247                // Help with tests to get a stable order with renamed deps.
248                doctest_deps.sort();
249                self.compilation.to_doc_test.push(compilation::Doctest {
250                    package: unit.pkg.clone(),
251                    target: unit.target.clone(),
252                    deps: doctest_deps,
253                });
254            }
255
256            let feats = self.bcx.resolve.features(unit.pkg.package_id());
257            if !feats.is_empty() {
258                self.compilation
259                    .cfgs
260                    .entry(unit.pkg.package_id())
261                    .or_insert_with(|| {
262                        feats
263                            .iter()
264                            .map(|feat| format!("feature=\"{}\"", feat))
265                            .collect()
266                    });
267            }
268            let rustdocflags = self.bcx.rustdocflags_args(unit)?;
269            if !rustdocflags.is_empty() {
270                self.compilation
271                    .rustdocflags
272                    .entry(unit.pkg.package_id())
273                    .or_insert(rustdocflags);
274            }
275
276            super::output_depinfo(&mut self, unit)?;
277        }
278
279        for (&(ref pkg, _), output) in self.build_state.outputs.lock().unwrap().iter() {
280            self.compilation
281                .cfgs
282                .entry(pkg.clone())
283                .or_insert_with(HashSet::new)
284                .extend(output.cfgs.iter().cloned());
285
286            self.compilation
287                .extra_env
288                .entry(pkg.clone())
289                .or_insert_with(Vec::new)
290                .extend(output.env.iter().cloned());
291
292            for dir in output.library_paths.iter() {
293                self.compilation.native_dirs.insert(dir.clone());
294            }
295        }
296        Ok(self.compilation)
297    }
298
299    /// Returns the executable for the specified unit (if any).
300    pub fn get_executable(&mut self, unit: &Unit<'a>) -> CargoResult<Option<PathBuf>> {
301        for output in self.outputs(unit)?.iter() {
302            if output.flavor == FileFlavor::DebugInfo {
303                continue;
304            }
305
306            let is_binary = unit.target.is_bin() || unit.target.is_bin_example();
307            let is_test = unit.mode.is_any_test() && !unit.mode.is_check();
308
309            if is_binary || is_test {
310                return Ok(Option::Some(output.bin_dst().clone()));
311            }
312        }
313        Ok(None)
314    }
315
316    pub fn prepare_units(
317        &mut self,
318        export_dir: Option<PathBuf>,
319        units: &[Unit<'a>],
320    ) -> CargoResult<()> {
321        let dest = if self.bcx.build_config.release {
322            "release"
323        } else {
324            "debug"
325        };
326        let host_layout = Layout::new(self.bcx.ws, None, dest)?;
327        let target_layout = match self.bcx.build_config.requested_target.as_ref() {
328            Some(target) => Some(Layout::new(self.bcx.ws, Some(target), dest)?),
329            None => None,
330        };
331        self.primary_packages
332            .extend(units.iter().map(|u| u.pkg.package_id()));
333
334        build_unit_dependencies(
335            units,
336            self.bcx,
337            &mut self.unit_dependencies,
338            &mut self.package_cache,
339        )?;
340        let files = CompilationFiles::new(
341            units,
342            host_layout,
343            target_layout,
344            export_dir,
345            self.bcx.ws,
346            self,
347        );
348        self.files = Some(files);
349        Ok(())
350    }
351
352    /// Prepare this context, ensuring that all filesystem directories are in
353    /// place.
354    pub fn prepare(&mut self) -> CargoResult<()> {
355        let _p = profile::start("preparing layout");
356
357        self.files_mut()
358            .host
359            .prepare()
360            .chain_err(|| internal("couldn't prepare build directories"))?;
361        if let Some(ref mut target) = self.files.as_mut().unwrap().target {
362            target
363                .prepare()
364                .chain_err(|| internal("couldn't prepare build directories"))?;
365        }
366
367        self.compilation.host_deps_output = self.files_mut().host.deps().to_path_buf();
368
369        let files = self.files.as_ref().unwrap();
370        let layout = files.target.as_ref().unwrap_or(&files.host);
371        self.compilation.root_output = layout.dest().to_path_buf();
372        self.compilation.deps_output = layout.deps().to_path_buf();
373        Ok(())
374    }
375
376    pub fn files(&self) -> &CompilationFiles<'a, 'cfg> {
377        self.files.as_ref().unwrap()
378    }
379
380    fn files_mut(&mut self) -> &mut CompilationFiles<'a, 'cfg> {
381        self.files.as_mut().unwrap()
382    }
383
384    /// Return the filenames that the given unit will generate.
385    pub fn outputs(&self, unit: &Unit<'a>) -> CargoResult<Arc<Vec<OutputFile>>> {
386        self.files.as_ref().unwrap().outputs(unit, self.bcx)
387    }
388
389    /// For a package, return all targets which are registered as dependencies
390    /// for that package.
391    // TODO: this ideally should be `-> &[Unit<'a>]`
392    pub fn dep_targets(&self, unit: &Unit<'a>) -> Vec<Unit<'a>> {
393        // If this build script's execution has been overridden then we don't
394        // actually depend on anything, we've reached the end of the dependency
395        // chain as we've got all the info we're gonna get.
396        //
397        // Note there's a subtlety about this piece of code! The
398        // `build_script_overridden` map here is populated in
399        // `custom_build::build_map` which you need to call before inspecting
400        // dependencies. However, that code itself calls this method and
401        // gets a full pre-filtered set of dependencies. This is not super
402        // obvious, and clear, but it does work at the moment.
403        if unit.target.is_custom_build() {
404            let key = (unit.pkg.package_id(), unit.kind);
405            if self.build_script_overridden.contains(&key) {
406                return Vec::new();
407            }
408        }
409        let mut deps = self.unit_dependencies[unit].clone();
410        deps.sort();
411        deps
412    }
413
414    pub fn incremental_args(&self, unit: &Unit<'_>) -> CargoResult<Vec<String>> {
415        // There's a number of ways to configure incremental compilation right
416        // now. In order of descending priority (first is highest priority) we
417        // have:
418        //
419        // * `CARGO_INCREMENTAL` - this is blanket used unconditionally to turn
420        //   on/off incremental compilation for any cargo subcommand. We'll
421        //   respect this if set.
422        // * `build.incremental` - in `.cargo/config` this blanket key can
423        //   globally for a system configure whether incremental compilation is
424        //   enabled. Note that setting this to `true` will not actually affect
425        //   all builds though. For example a `true` value doesn't enable
426        //   release incremental builds, only dev incremental builds. This can
427        //   be useful to globally disable incremental compilation like
428        //   `CARGO_INCREMENTAL`.
429        // * `profile.dev.incremental` - in `Cargo.toml` specific profiles can
430        //   be configured to enable/disable incremental compilation. This can
431        //   be primarily used to disable incremental when buggy for a package.
432        // * Finally, each profile has a default for whether it will enable
433        //   incremental compilation or not. Primarily development profiles
434        //   have it enabled by default while release profiles have it disabled
435        //   by default.
436        let global_cfg = self
437            .bcx
438            .config
439            .get_bool("build.incremental")?
440            .map(|c| c.val);
441        let incremental = match (
442            self.bcx.incremental_env,
443            global_cfg,
444            unit.profile.incremental,
445        ) {
446            (Some(v), _, _) => v,
447            (None, Some(false), _) => false,
448            (None, _, other) => other,
449        };
450
451        if !incremental {
452            return Ok(Vec::new());
453        }
454
455        // Only enable incremental compilation for sources the user can
456        // modify (aka path sources). For things that change infrequently,
457        // non-incremental builds yield better performance in the compiler
458        // itself (aka crates.io / git dependencies)
459        //
460        // (see also https://github.com/rust-lang/cargo/issues/3972)
461        if !unit.pkg.package_id().source_id().is_path() {
462            return Ok(Vec::new());
463        }
464
465        let dir = self.files().layout(unit.kind).incremental().display();
466        Ok(vec!["-C".to_string(), format!("incremental={}", dir)])
467    }
468
469    pub fn is_primary_package(&self, unit: &Unit<'a>) -> bool {
470        self.primary_packages.contains(&unit.pkg.package_id())
471    }
472
473    /// Gets a package for the given package id.
474    pub fn get_package(&self, id: PackageId) -> CargoResult<&'a Package> {
475        self.package_cache
476            .get(&id)
477            .cloned()
478            .ok_or_else(|| failure::format_err!("failed to find {}", id))
479    }
480
481    /// Return the list of filenames read by cargo to generate the BuildContext
482    /// (all Cargo.toml, etc).
483    pub fn build_plan_inputs(&self) -> CargoResult<Vec<PathBuf>> {
484        let mut inputs = Vec::new();
485        // Note that we're using the `package_cache`, which should have been
486        // populated by `build_unit_dependencies`, and only those packages are
487        // considered as all the inputs.
488        //
489        // (notably we skip dev-deps here if they aren't present)
490        for pkg in self.package_cache.values() {
491            inputs.push(pkg.manifest_path().to_path_buf());
492        }
493        inputs.sort();
494        Ok(inputs)
495    }
496
497    fn check_collistions(&self) -> CargoResult<()> {
498        let mut output_collisions = HashMap::new();
499        let describe_collision =
500            |unit: &Unit<'_>, other_unit: &Unit<'_>, path: &PathBuf| -> String {
501                format!(
502                    "The {} target `{}` in package `{}` has the same output \
503                     filename as the {} target `{}` in package `{}`.\n\
504                     Colliding filename is: {}\n",
505                    unit.target.kind().description(),
506                    unit.target.name(),
507                    unit.pkg.package_id(),
508                    other_unit.target.kind().description(),
509                    other_unit.target.name(),
510                    other_unit.pkg.package_id(),
511                    path.display()
512                )
513            };
514        let suggestion = "Consider changing their names to be unique or compiling them separately.\n\
515            This may become a hard error in the future, see https://github.com/rust-lang/cargo/issues/6313";
516        let report_collision = |unit: &Unit<'_>,
517                                other_unit: &Unit<'_>,
518                                path: &PathBuf|
519         -> CargoResult<()> {
520            if unit.target.name() == other_unit.target.name() {
521                self.bcx.config.shell().warn(format!(
522                    "output filename collision.\n\
523                     {}\
524                     The targets should have unique names.\n\
525                     {}",
526                    describe_collision(unit, other_unit, path),
527                    suggestion
528                ))
529            } else {
530                self.bcx.config.shell().warn(format!(
531                    "output filename collision.\n\
532                    {}\
533                    The output filenames should be unique.\n\
534                    {}\n\
535                    If this looks unexpected, it may be a bug in Cargo. Please file a bug report at\n\
536                    https://github.com/rust-lang/cargo/issues/ with as much information as you\n\
537                    can provide.\n\
538                    {} running on `{}` target `{}`\n\
539                    First unit: {:?}\n\
540                    Second unit: {:?}",
541                    describe_collision(unit, other_unit, path),
542                    suggestion,
543                    crate::version(), self.bcx.host_triple(), self.bcx.target_triple(),
544                    unit, other_unit))
545            }
546        };
547        let mut keys = self
548            .unit_dependencies
549            .keys()
550            .filter(|unit| !unit.mode.is_run_custom_build())
551            .collect::<Vec<_>>();
552        // Sort for consistent error messages.
553        keys.sort_unstable();
554        for unit in keys {
555            for output in self.outputs(unit)?.iter() {
556                if let Some(other_unit) = output_collisions.insert(output.path.clone(), unit) {
557                    report_collision(unit, &other_unit, &output.path)?;
558                }
559                if let Some(hardlink) = output.hardlink.as_ref() {
560                    if let Some(other_unit) = output_collisions.insert(hardlink.clone(), unit) {
561                        report_collision(unit, &other_unit, hardlink)?;
562                    }
563                }
564                if let Some(ref export_path) = output.export_path {
565                    if let Some(other_unit) = output_collisions.insert(export_path.clone(), unit) {
566                        self.bcx.config.shell().warn(format!(
567                            "`--out-dir` filename collision.\n\
568                             {}\
569                             The exported filenames should be unique.\n\
570                             {}",
571                            describe_collision(unit, &other_unit, &export_path),
572                            suggestion
573                        ))?;
574                    }
575                }
576            }
577        }
578        Ok(())
579    }
580}
581
582#[derive(Default)]
583pub struct Links {
584    validated: HashSet<PackageId>,
585    links: HashMap<String, PackageId>,
586}
587
588impl Links {
589    pub fn new() -> Links {
590        Links {
591            validated: HashSet::new(),
592            links: HashMap::new(),
593        }
594    }
595
596    pub fn validate(&mut self, resolve: &Resolve, unit: &Unit<'_>) -> CargoResult<()> {
597        if !self.validated.insert(unit.pkg.package_id()) {
598            return Ok(());
599        }
600        let lib = match unit.pkg.manifest().links() {
601            Some(lib) => lib,
602            None => return Ok(()),
603        };
604        if let Some(&prev) = self.links.get(lib) {
605            let pkg = unit.pkg.package_id();
606
607            let describe_path = |pkgid: PackageId| -> String {
608                let dep_path = resolve.path_to_top(&pkgid);
609                let mut dep_path_desc = format!("package `{}`", dep_path[0]);
610                for dep in dep_path.iter().skip(1) {
611                    write!(dep_path_desc, "\n    ... which is depended on by `{}`", dep).unwrap();
612                }
613                dep_path_desc
614            };
615
616            failure::bail!(
617                "multiple packages link to native library `{}`, \
618                 but a native library can be linked only once\n\
619                 \n\
620                 {}\nlinks to native library `{}`\n\
621                 \n\
622                 {}\nalso links to native library `{}`",
623                lib,
624                describe_path(prev),
625                lib,
626                describe_path(pkg),
627                lib
628            )
629        }
630        if !unit
631            .pkg
632            .manifest()
633            .targets()
634            .iter()
635            .any(|t| t.is_custom_build())
636        {
637            failure::bail!(
638                "package `{}` specifies that it links to `{}` but does not \
639                 have a custom build script",
640                unit.pkg.package_id(),
641                lib
642            )
643        }
644        self.links.insert(lib.to_string(), unit.pkg.package_id());
645        Ok(())
646    }
647}