Skip to main content

cargo/core/compiler/
mod.rs

1use std::env;
2use std::ffi::{OsStr, OsString};
3use std::fs;
4use std::io::{self, Write};
5use std::path::{self, Path, PathBuf};
6use std::sync::Arc;
7
8use failure::Error;
9use log::debug;
10use same_file::is_same_file;
11use serde::Serialize;
12
13use crate::core::manifest::TargetSourcePath;
14use crate::core::profiles::{Lto, Profile};
15use crate::core::{PackageId, Target};
16use crate::util::errors::{CargoResult, CargoResultExt, Internal, ProcessError};
17use crate::util::paths;
18use crate::util::{self, machine_message, process, Freshness, ProcessBuilder};
19use crate::util::{internal, join_paths, profile};
20
21use self::build_plan::BuildPlan;
22use self::job::{Job, Work};
23use self::job_queue::JobQueue;
24
25use self::output_depinfo::output_depinfo;
26
27pub use self::build_config::{BuildConfig, CompileMode, MessageFormat};
28pub use self::build_context::{BuildContext, FileFlavor, TargetConfig, TargetInfo};
29pub use self::compilation::{Compilation, Doctest};
30pub use self::context::{Context, Unit};
31pub use self::custom_build::{BuildMap, BuildOutput, BuildScripts};
32pub use self::layout::is_bad_artifact_name;
33
34mod build_config;
35mod build_context;
36mod build_plan;
37mod compilation;
38mod context;
39mod custom_build;
40mod fingerprint;
41mod job;
42mod job_queue;
43mod layout;
44mod output_depinfo;
45
46/// Whether an object is for the host arch, or the target arch.
47///
48/// These will be the same unless cross-compiling.
49#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy, PartialOrd, Ord, Serialize)]
50pub enum Kind {
51    Host,
52    Target,
53}
54
55/// A glorified callback for executing calls to rustc. Rather than calling rustc
56/// directly, we'll use an Executor, giving clients an opportunity to intercept
57/// the build calls.
58pub trait Executor: Send + Sync + 'static {
59    /// Called after a rustc process invocation is prepared up-front for a given
60    /// unit of work (may still be modified for runtime-known dependencies, when
61    /// the work is actually executed).
62    fn init(&self, _cx: &Context<'_, '_>, _unit: &Unit<'_>) {}
63
64    /// In case of an `Err`, Cargo will not continue with the build process for
65    /// this package.
66    fn exec(
67        &self,
68        cmd: ProcessBuilder,
69        _id: PackageId,
70        _target: &Target,
71        _mode: CompileMode,
72    ) -> CargoResult<()> {
73        cmd.exec()?;
74        Ok(())
75    }
76
77    fn exec_and_capture_output(
78        &self,
79        cmd: ProcessBuilder,
80        id: PackageId,
81        target: &Target,
82        mode: CompileMode,
83        _state: &job_queue::JobState<'_>,
84    ) -> CargoResult<()> {
85        // we forward to exec() to keep RLS working.
86        self.exec(cmd, id, target, mode)
87    }
88
89    fn exec_json(
90        &self,
91        cmd: ProcessBuilder,
92        _id: PackageId,
93        _target: &Target,
94        _mode: CompileMode,
95        handle_stdout: &mut dyn FnMut(&str) -> CargoResult<()>,
96        handle_stderr: &mut dyn FnMut(&str) -> CargoResult<()>,
97    ) -> CargoResult<()> {
98        cmd.exec_with_streaming(handle_stdout, handle_stderr, false)?;
99        Ok(())
100    }
101
102    /// Queried when queuing each unit of work. If it returns true, then the
103    /// unit will always be rebuilt, independent of whether it needs to be.
104    fn force_rebuild(&self, _unit: &Unit<'_>) -> bool {
105        false
106    }
107}
108
109/// A `DefaultExecutor` calls rustc without doing anything else. It is Cargo's
110/// default behaviour.
111#[derive(Copy, Clone)]
112pub struct DefaultExecutor;
113
114impl Executor for DefaultExecutor {
115    fn exec_and_capture_output(
116        &self,
117        cmd: ProcessBuilder,
118        _id: PackageId,
119        _target: &Target,
120        _mode: CompileMode,
121        state: &job_queue::JobState<'_>,
122    ) -> CargoResult<()> {
123        state.capture_output(&cmd, None, false).map(drop)
124    }
125}
126
127fn compile<'a, 'cfg: 'a>(
128    cx: &mut Context<'a, 'cfg>,
129    jobs: &mut JobQueue<'a>,
130    plan: &mut BuildPlan,
131    unit: &Unit<'a>,
132    exec: &Arc<dyn Executor>,
133    force_rebuild: bool,
134) -> CargoResult<()> {
135    let bcx = cx.bcx;
136    let build_plan = bcx.build_config.build_plan;
137    if !cx.compiled.insert(*unit) {
138        return Ok(());
139    }
140
141    // Build up the work to be done to compile this unit, enqueuing it once
142    // we've got everything constructed.
143    let p = profile::start(format!("preparing: {}/{}", unit.pkg, unit.target.name()));
144    fingerprint::prepare_init(cx, unit)?;
145    cx.links.validate(bcx.resolve, unit)?;
146
147    let (dirty, fresh, freshness) = if unit.mode.is_run_custom_build() {
148        custom_build::prepare(cx, unit)?
149    } else if unit.mode == CompileMode::Doctest {
150        // we run these targets later, so this is just a noop for now
151        (Work::noop(), Work::noop(), Freshness::Fresh)
152    } else if build_plan {
153        (
154            rustc(cx, unit, &exec.clone())?,
155            Work::noop(),
156            Freshness::Dirty,
157        )
158    } else {
159        let (mut freshness, dirty, fresh) = fingerprint::prepare_target(cx, unit)?;
160        let work = if unit.mode.is_doc() {
161            rustdoc(cx, unit)?
162        } else {
163            rustc(cx, unit, exec)?
164        };
165        // Need to link targets on both the dirty and fresh
166        let dirty = work.then(link_targets(cx, unit, false)?).then(dirty);
167        let fresh = link_targets(cx, unit, true)?.then(fresh);
168
169        if exec.force_rebuild(unit) || force_rebuild {
170            freshness = Freshness::Dirty;
171        }
172
173        (dirty, fresh, freshness)
174    };
175    jobs.enqueue(cx, unit, Job::new(dirty, fresh), freshness)?;
176    drop(p);
177
178    // Be sure to compile all dependencies of this target as well.
179    for unit in cx.dep_targets(unit).iter() {
180        compile(cx, jobs, plan, unit, exec, false)?;
181    }
182    if build_plan {
183        plan.add(cx, unit)?;
184    }
185
186    Ok(())
187}
188
189fn rustc<'a, 'cfg>(
190    cx: &mut Context<'a, 'cfg>,
191    unit: &Unit<'a>,
192    exec: &Arc<dyn Executor>,
193) -> CargoResult<Work> {
194    let mut rustc = prepare_rustc(cx, &unit.target.rustc_crate_types(), unit)?;
195    if cx.is_primary_package(unit) {
196        rustc.env("CARGO_PRIMARY_PACKAGE", "1");
197    }
198    let build_plan = cx.bcx.build_config.build_plan;
199
200    let name = unit.pkg.name().to_string();
201    let buildkey = unit.buildkey();
202
203    add_cap_lints(cx.bcx, unit, &mut rustc);
204
205    let outputs = cx.outputs(unit)?;
206    let root = cx.files().out_dir(unit);
207    let kind = unit.kind;
208
209    // Prepare the native lib state (extra -L and -l flags)
210    let build_state = cx.build_state.clone();
211    let current_id = unit.pkg.package_id();
212    let build_deps = load_build_deps(cx, unit);
213
214    // If we are a binary and the package also contains a library, then we
215    // don't pass the `-l` flags.
216    let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
217    let do_rename = unit.target.allows_underscores() && !unit.mode.is_any_test();
218    let real_name = unit.target.name().to_string();
219    let crate_name = unit.target.crate_name();
220
221    // XXX(Rely on target_filenames iterator as source of truth rather than rederiving filestem)
222    let rustc_dep_info_loc = if do_rename && cx.files().metadata(unit).is_none() {
223        root.join(&crate_name)
224    } else {
225        root.join(&cx.files().file_stem(unit))
226    }
227    .with_extension("d");
228    let dep_info_loc = fingerprint::dep_info_loc(cx, unit);
229
230    rustc.args(&cx.bcx.rustflags_args(unit)?);
231    let json_messages = cx.bcx.build_config.json_messages();
232    let package_id = unit.pkg.package_id();
233    let target = unit.target.clone();
234    let mode = unit.mode;
235
236    exec.init(cx, unit);
237    let exec = exec.clone();
238
239    let root_output = cx.files().target_root().to_path_buf();
240    let pkg_root = unit.pkg.root().to_path_buf();
241    let cwd = rustc
242        .get_cwd()
243        .unwrap_or_else(|| cx.bcx.config.cwd())
244        .to_path_buf();
245
246    return Ok(Work::new(move |state| {
247        // Only at runtime have we discovered what the extra -L and -l
248        // arguments are for native libraries, so we process those here. We
249        // also need to be sure to add any -L paths for our plugins to the
250        // dynamic library load path as a plugin's dynamic library may be
251        // located somewhere in there.
252        // Finally, if custom environment variables have been produced by
253        // previous build scripts, we include them in the rustc invocation.
254        if let Some(build_deps) = build_deps {
255            let build_state = build_state.outputs.lock().unwrap();
256            if !build_plan {
257                add_native_deps(
258                    &mut rustc,
259                    &build_state,
260                    &build_deps,
261                    pass_l_flag,
262                    current_id,
263                )?;
264                add_plugin_deps(&mut rustc, &build_state, &build_deps, &root_output)?;
265            }
266            add_custom_env(&mut rustc, &build_state, current_id, kind)?;
267        }
268
269        for output in outputs.iter() {
270            // If there is both an rmeta and rlib, rustc will prefer to use the
271            // rlib, even if it is older. Therefore, we must delete the rlib to
272            // force using the new rmeta.
273            if output.path.extension() == Some(OsStr::new("rmeta")) {
274                let dst = root.join(&output.path).with_extension("rlib");
275                if dst.exists() {
276                    paths::remove_file(&dst)?;
277                }
278            }
279        }
280
281        fn internal_if_simple_exit_code(err: Error) -> Error {
282            // If a signal on unix (code == None) or an abnormal termination
283            // on Windows (codes like 0xC0000409), don't hide the error details.
284            match err
285                .downcast_ref::<ProcessError>()
286                .as_ref()
287                .and_then(|perr| perr.exit.and_then(|e| e.code()))
288            {
289                Some(n) if n < 128 => Internal::new(err).into(),
290                _ => err,
291            }
292        }
293
294        state.running(&rustc);
295        if json_messages {
296            exec.exec_json(
297                rustc,
298                package_id,
299                &target,
300                mode,
301                &mut assert_is_empty,
302                &mut |line| json_stderr(line, package_id, &target),
303            )
304            .map_err(internal_if_simple_exit_code)
305            .chain_err(|| format!("Could not compile `{}`.", name))?;
306        } else if build_plan {
307            state.build_plan(buildkey, rustc.clone(), outputs.clone());
308        } else {
309            exec.exec_and_capture_output(rustc, package_id, &target, mode, state)
310                .map_err(internal_if_simple_exit_code)
311                .chain_err(|| format!("Could not compile `{}`.", name))?;
312        }
313
314        if do_rename && real_name != crate_name {
315            let dst = &outputs[0].path;
316            let src = dst.with_file_name(
317                dst.file_name()
318                    .unwrap()
319                    .to_str()
320                    .unwrap()
321                    .replace(&real_name, &crate_name),
322            );
323            if src.exists() && src.file_name() != dst.file_name() {
324                fs::rename(&src, &dst)
325                    .chain_err(|| internal(format!("could not rename crate {:?}", src)))?;
326            }
327        }
328
329        if rustc_dep_info_loc.exists() {
330            fingerprint::translate_dep_info(&rustc_dep_info_loc, &dep_info_loc, &pkg_root, &cwd)
331                .chain_err(|| {
332                    internal(format!(
333                        "could not parse/generate dep info at: {}",
334                        rustc_dep_info_loc.display()
335                    ))
336                })?;
337        }
338
339        Ok(())
340    }));
341
342    // Add all relevant -L and -l flags from dependencies (now calculated and
343    // present in `state`) to the command provided
344    fn add_native_deps(
345        rustc: &mut ProcessBuilder,
346        build_state: &BuildMap,
347        build_scripts: &BuildScripts,
348        pass_l_flag: bool,
349        current_id: PackageId,
350    ) -> CargoResult<()> {
351        for key in build_scripts.to_link.iter() {
352            let output = build_state.get(key).ok_or_else(|| {
353                internal(format!(
354                    "couldn't find build state for {}/{:?}",
355                    key.0, key.1
356                ))
357            })?;
358            for path in output.library_paths.iter() {
359                rustc.arg("-L").arg(path);
360            }
361            if key.0 == current_id {
362                for cfg in &output.cfgs {
363                    rustc.arg("--cfg").arg(cfg);
364                }
365                if pass_l_flag {
366                    for name in output.library_links.iter() {
367                        rustc.arg("-l").arg(name);
368                    }
369                }
370            }
371        }
372        Ok(())
373    }
374
375    // Add all custom environment variables present in `state` (after they've
376    // been put there by one of the `build_scripts`) to the command provided.
377    fn add_custom_env(
378        rustc: &mut ProcessBuilder,
379        build_state: &BuildMap,
380        current_id: PackageId,
381        kind: Kind,
382    ) -> CargoResult<()> {
383        let key = (current_id, kind);
384        if let Some(output) = build_state.get(&key) {
385            for &(ref name, ref value) in output.env.iter() {
386                rustc.env(name, value);
387            }
388        }
389        Ok(())
390    }
391}
392
393/// Link the compiled target (often of form `foo-{metadata_hash}`) to the
394/// final target. This must happen during both "Fresh" and "Compile"
395fn link_targets<'a, 'cfg>(
396    cx: &mut Context<'a, 'cfg>,
397    unit: &Unit<'a>,
398    fresh: bool,
399) -> CargoResult<Work> {
400    let bcx = cx.bcx;
401    let outputs = cx.outputs(unit)?;
402    let export_dir = cx.files().export_dir();
403    let package_id = unit.pkg.package_id();
404    let profile = unit.profile;
405    let unit_mode = unit.mode;
406    let features = bcx
407        .resolve
408        .features_sorted(package_id)
409        .into_iter()
410        .map(|s| s.to_owned())
411        .collect();
412    let json_messages = bcx.build_config.json_messages();
413    let executable = cx.get_executable(unit)?;
414    let mut target = unit.target.clone();
415    if let TargetSourcePath::Metabuild = target.src_path() {
416        // Give it something to serialize.
417        let path = unit.pkg.manifest().metabuild_path(cx.bcx.ws.target_dir());
418        target.set_src_path(TargetSourcePath::Path(path));
419    }
420
421    Ok(Work::new(move |_| {
422        // If we're a "root crate", e.g. the target of this compilation, then we
423        // hard link our outputs out of the `deps` directory into the directory
424        // above. This means that `cargo build` will produce binaries in
425        // `target/debug` which one probably expects.
426        let mut destinations = vec![];
427        for output in outputs.iter() {
428            let src = &output.path;
429            // This may have been a `cargo rustc` command which changes the
430            // output, so the source may not actually exist.
431            if !src.exists() {
432                continue;
433            }
434            let dst = match output.hardlink.as_ref() {
435                Some(dst) => dst,
436                None => {
437                    destinations.push(src.clone());
438                    continue;
439                }
440            };
441            destinations.push(dst.clone());
442            hardlink_or_copy(src, dst)?;
443            if let Some(ref path) = output.export_path {
444                let export_dir = export_dir.as_ref().unwrap();
445                if !export_dir.exists() {
446                    fs::create_dir_all(export_dir)?;
447                }
448
449                hardlink_or_copy(src, path)?;
450            }
451        }
452
453        if json_messages {
454            let art_profile = machine_message::ArtifactProfile {
455                opt_level: profile.opt_level.as_str(),
456                debuginfo: profile.debuginfo,
457                debug_assertions: profile.debug_assertions,
458                overflow_checks: profile.overflow_checks,
459                test: unit_mode.is_any_test(),
460            };
461
462            machine_message::emit(&machine_message::Artifact {
463                package_id,
464                target: &target,
465                profile: art_profile,
466                features,
467                filenames: destinations,
468                executable,
469                fresh,
470            });
471        }
472        Ok(())
473    }))
474}
475
476fn hardlink_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
477    debug!("linking {} to {}", src.display(), dst.display());
478    if is_same_file(src, dst).unwrap_or(false) {
479        return Ok(());
480    }
481    if dst.exists() {
482        paths::remove_file(&dst)?;
483    }
484
485    let link_result = if src.is_dir() {
486        #[cfg(target_os = "redox")]
487        use std::os::redox::fs::symlink;
488        #[cfg(unix)]
489        use std::os::unix::fs::symlink;
490        #[cfg(windows)]
491        use std::os::windows::fs::symlink_dir as symlink;
492
493        let dst_dir = dst.parent().unwrap();
494        let src = if src.starts_with(dst_dir) {
495            src.strip_prefix(dst_dir).unwrap()
496        } else {
497            src
498        };
499        symlink(src, dst)
500    } else {
501        fs::hard_link(src, dst)
502    };
503    link_result
504        .or_else(|err| {
505            debug!("link failed {}. falling back to fs::copy", err);
506            fs::copy(src, dst).map(|_| ())
507        })
508        .chain_err(|| {
509            format!(
510                "failed to link or copy `{}` to `{}`",
511                src.display(),
512                dst.display()
513            )
514        })?;
515    Ok(())
516}
517
518fn load_build_deps(cx: &Context<'_, '_>, unit: &Unit<'_>) -> Option<Arc<BuildScripts>> {
519    cx.build_scripts.get(unit).cloned()
520}
521
522// For all plugin dependencies, add their -L paths (now calculated and
523// present in `state`) to the dynamic library load path for the command to
524// execute.
525fn add_plugin_deps(
526    rustc: &mut ProcessBuilder,
527    build_state: &BuildMap,
528    build_scripts: &BuildScripts,
529    root_output: &PathBuf,
530) -> CargoResult<()> {
531    let var = util::dylib_path_envvar();
532    let search_path = rustc.get_env(var).unwrap_or_default();
533    let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
534    for &id in build_scripts.plugins.iter() {
535        let output = build_state
536            .get(&(id, Kind::Host))
537            .ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", id)))?;
538        search_path.append(&mut filter_dynamic_search_path(
539            output.library_paths.iter(),
540            root_output,
541        ));
542    }
543    let search_path = join_paths(&search_path, var)?;
544    rustc.env(var, &search_path);
545    Ok(())
546}
547
548// Determine paths to add to the dynamic search path from -L entries
549//
550// Strip off prefixes like "native=" or "framework=" and filter out directories
551// *not* inside our output directory since they are likely spurious and can cause
552// clashes with system shared libraries (issue #3366).
553fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &PathBuf) -> Vec<PathBuf>
554where
555    I: Iterator<Item = &'a PathBuf>,
556{
557    let mut search_path = vec![];
558    for dir in paths {
559        let dir = match dir.to_str() {
560            Some(s) => {
561                let mut parts = s.splitn(2, '=');
562                match (parts.next(), parts.next()) {
563                    (Some("native"), Some(path))
564                    | (Some("crate"), Some(path))
565                    | (Some("dependency"), Some(path))
566                    | (Some("framework"), Some(path))
567                    | (Some("all"), Some(path)) => path.into(),
568                    _ => dir.clone(),
569                }
570            }
571            None => dir.clone(),
572        };
573        if dir.starts_with(&root_output) {
574            search_path.push(dir);
575        } else {
576            debug!(
577                "Not including path {} in runtime library search path because it is \
578                 outside target root {}",
579                dir.display(),
580                root_output.display()
581            );
582        }
583    }
584    search_path
585}
586
587fn prepare_rustc<'a, 'cfg>(
588    cx: &mut Context<'a, 'cfg>,
589    crate_types: &[&str],
590    unit: &Unit<'a>,
591) -> CargoResult<ProcessBuilder> {
592    let mut base = cx.compilation.rustc_process(unit.pkg, unit.target)?;
593    base.inherit_jobserver(&cx.jobserver);
594    build_base_args(cx, &mut base, unit, crate_types)?;
595    build_deps_args(&mut base, cx, unit)?;
596    Ok(base)
597}
598
599fn rustdoc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<Work> {
600    let bcx = cx.bcx;
601    let mut rustdoc = cx.compilation.rustdoc_process(unit.pkg, unit.target)?;
602    rustdoc.inherit_jobserver(&cx.jobserver);
603    rustdoc.arg("--crate-name").arg(&unit.target.crate_name());
604    add_path_args(bcx, unit, &mut rustdoc);
605    add_cap_lints(bcx, unit, &mut rustdoc);
606
607    let mut can_add_color_process = process(&*bcx.config.rustdoc()?);
608    can_add_color_process.args(&["--color", "never", "-V"]);
609    if bcx.rustc.cached_success(&can_add_color_process)? {
610        add_color(bcx, &mut rustdoc);
611    }
612
613    if unit.kind != Kind::Host {
614        if let Some(ref target) = bcx.build_config.requested_target {
615            rustdoc.arg("--target").arg(target);
616        }
617    }
618
619    let doc_dir = cx.files().out_dir(unit);
620
621    // Create the documentation directory ahead of time as rustdoc currently has
622    // a bug where concurrent invocations will race to create this directory if
623    // it doesn't already exist.
624    fs::create_dir_all(&doc_dir)?;
625
626    rustdoc.arg("-o").arg(doc_dir);
627
628    for feat in bcx.resolve.features_sorted(unit.pkg.package_id()) {
629        rustdoc.arg("--cfg").arg(&format!("feature=\"{}\"", feat));
630    }
631
632    add_error_format(bcx, &mut rustdoc);
633
634    if let Some(ref args) = bcx.extra_args_for(unit) {
635        rustdoc.args(args);
636    }
637
638    build_deps_args(&mut rustdoc, cx, unit)?;
639
640    rustdoc.args(&bcx.rustdocflags_args(unit)?);
641
642    let name = unit.pkg.name().to_string();
643    let build_state = cx.build_state.clone();
644    let key = (unit.pkg.package_id(), unit.kind);
645    let json_messages = bcx.build_config.json_messages();
646    let package_id = unit.pkg.package_id();
647    let target = unit.target.clone();
648
649    Ok(Work::new(move |state| {
650        if let Some(output) = build_state.outputs.lock().unwrap().get(&key) {
651            for cfg in output.cfgs.iter() {
652                rustdoc.arg("--cfg").arg(cfg);
653            }
654            for &(ref name, ref value) in output.env.iter() {
655                rustdoc.env(name, value);
656            }
657        }
658        state.running(&rustdoc);
659
660        let exec_result = if json_messages {
661            rustdoc
662                .exec_with_streaming(
663                    &mut assert_is_empty,
664                    &mut |line| json_stderr(line, package_id, &target),
665                    false,
666                )
667                .map(drop)
668        } else {
669            state.capture_output(&rustdoc, None, false).map(drop)
670        };
671        exec_result.chain_err(|| format!("Could not document `{}`.", name))?;
672        Ok(())
673    }))
674}
675
676// The path that we pass to rustc is actually fairly important because it will
677// show up in error messages (important for readability), debug information
678// (important for caching), etc. As a result we need to be pretty careful how we
679// actually invoke rustc.
680//
681// In general users don't expect `cargo build` to cause rebuilds if you change
682// directories. That could be if you just change directories in the package or
683// if you literally move the whole package wholesale to a new directory. As a
684// result we mostly don't factor in `cwd` to this calculation. Instead we try to
685// track the workspace as much as possible and we update the current directory
686// of rustc/rustdoc where appropriate.
687//
688// The first returned value here is the argument to pass to rustc, and the
689// second is the cwd that rustc should operate in.
690fn path_args(bcx: &BuildContext<'_, '_>, unit: &Unit<'_>) -> (PathBuf, PathBuf) {
691    let ws_root = bcx.ws.root();
692    let src = match unit.target.src_path() {
693        TargetSourcePath::Path(path) => path.to_path_buf(),
694        TargetSourcePath::Metabuild => unit.pkg.manifest().metabuild_path(bcx.ws.target_dir()),
695    };
696    assert!(src.is_absolute());
697    if unit.pkg.package_id().source_id().is_path() {
698        if let Ok(path) = src.strip_prefix(ws_root) {
699            return (path.to_path_buf(), ws_root.to_path_buf());
700        }
701    }
702    (src, unit.pkg.root().to_path_buf())
703}
704
705fn add_path_args(bcx: &BuildContext<'_, '_>, unit: &Unit<'_>, cmd: &mut ProcessBuilder) {
706    let (arg, cwd) = path_args(bcx, unit);
707    cmd.arg(arg);
708    cmd.cwd(cwd);
709}
710
711fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit<'_>, cmd: &mut ProcessBuilder) {
712    // If this is an upstream dep we don't want warnings from, turn off all
713    // lints.
714    if !bcx.show_warnings(unit.pkg.package_id()) {
715        cmd.arg("--cap-lints").arg("allow");
716
717    // If this is an upstream dep but we *do* want warnings, make sure that they
718    // don't fail compilation.
719    } else if !unit.pkg.package_id().source_id().is_path() {
720        cmd.arg("--cap-lints").arg("warn");
721    }
722}
723
724fn add_color(bcx: &BuildContext<'_, '_>, cmd: &mut ProcessBuilder) {
725    let shell = bcx.config.shell();
726    let color = if shell.supports_color() {
727        "always"
728    } else {
729        "never"
730    };
731    cmd.args(&["--color", color]);
732}
733
734fn add_error_format(bcx: &BuildContext<'_, '_>, cmd: &mut ProcessBuilder) {
735    match bcx.build_config.message_format {
736        MessageFormat::Human => (),
737        MessageFormat::Json => {
738            cmd.arg("--error-format").arg("json");
739        }
740        MessageFormat::Short => {
741            cmd.arg("--error-format").arg("short");
742        }
743    }
744}
745
746fn build_base_args<'a, 'cfg>(
747    cx: &mut Context<'a, 'cfg>,
748    cmd: &mut ProcessBuilder,
749    unit: &Unit<'a>,
750    crate_types: &[&str],
751) -> CargoResult<()> {
752    assert!(!unit.mode.is_run_custom_build());
753
754    let bcx = cx.bcx;
755    let Profile {
756        ref opt_level,
757        ref lto,
758        codegen_units,
759        debuginfo,
760        debug_assertions,
761        overflow_checks,
762        rpath,
763        ref panic,
764        ..
765    } = unit.profile;
766    let test = unit.mode.is_any_test();
767
768    cmd.arg("--crate-name").arg(&unit.target.crate_name());
769
770    add_path_args(bcx, unit, cmd);
771    add_color(bcx, cmd);
772    add_error_format(bcx, cmd);
773
774    if !test {
775        for crate_type in crate_types.iter() {
776            cmd.arg("--crate-type").arg(crate_type);
777        }
778    }
779
780    if unit.mode.is_check() {
781        cmd.arg("--emit=dep-info,metadata");
782    } else {
783        cmd.arg("--emit=dep-info,link");
784    }
785
786    let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
787        || (crate_types.contains(&"dylib") && bcx.ws.members().any(|p| p != unit.pkg));
788    if prefer_dynamic {
789        cmd.arg("-C").arg("prefer-dynamic");
790    }
791
792    if opt_level.as_str() != "0" {
793        cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
794    }
795
796    if let Some(panic) = panic.as_ref() {
797        cmd.arg("-C").arg(format!("panic={}", panic));
798    }
799
800    // Disable LTO for host builds as prefer_dynamic and it are mutually
801    // exclusive.
802    if unit.target.can_lto() && !unit.target.for_host() {
803        match *lto {
804            Lto::Bool(false) => {}
805            Lto::Bool(true) => {
806                cmd.args(&["-C", "lto"]);
807            }
808            Lto::Named(ref s) => {
809                cmd.arg("-C").arg(format!("lto={}", s));
810            }
811        }
812    }
813
814    if let Some(n) = codegen_units {
815        // There are some restrictions with LTO and codegen-units, so we
816        // only add codegen units when LTO is not used.
817        cmd.arg("-C").arg(&format!("codegen-units={}", n));
818    }
819
820    if let Some(debuginfo) = debuginfo {
821        cmd.arg("-C").arg(format!("debuginfo={}", debuginfo));
822    }
823
824    if let Some(ref args) = bcx.extra_args_for(unit) {
825        cmd.args(args);
826    }
827
828    // -C overflow-checks is implied by the setting of -C debug-assertions,
829    // so we only need to provide -C overflow-checks if it differs from
830    // the value of -C debug-assertions we would provide.
831    if opt_level.as_str() != "0" {
832        if debug_assertions {
833            cmd.args(&["-C", "debug-assertions=on"]);
834            if !overflow_checks {
835                cmd.args(&["-C", "overflow-checks=off"]);
836            }
837        } else if overflow_checks {
838            cmd.args(&["-C", "overflow-checks=on"]);
839        }
840    } else if !debug_assertions {
841        cmd.args(&["-C", "debug-assertions=off"]);
842        if overflow_checks {
843            cmd.args(&["-C", "overflow-checks=on"]);
844        }
845    } else if !overflow_checks {
846        cmd.args(&["-C", "overflow-checks=off"]);
847    }
848
849    if test && unit.target.harness() {
850        cmd.arg("--test");
851    } else if test {
852        cmd.arg("--cfg").arg("test");
853    }
854
855    // We ideally want deterministic invocations of rustc to ensure that
856    // rustc-caching strategies like sccache are able to cache more, so sort the
857    // feature list here.
858    for feat in bcx.resolve.features_sorted(unit.pkg.package_id()) {
859        cmd.arg("--cfg").arg(&format!("feature=\"{}\"", feat));
860    }
861
862    match cx.files().metadata(unit) {
863        Some(m) => {
864            cmd.arg("-C").arg(&format!("metadata={}", m));
865            cmd.arg("-C").arg(&format!("extra-filename=-{}", m));
866        }
867        None => {
868            cmd.arg("-C")
869                .arg(&format!("metadata={}", cx.files().target_short_hash(unit)));
870        }
871    }
872
873    if rpath {
874        cmd.arg("-C").arg("rpath");
875    }
876
877    cmd.arg("--out-dir").arg(&cx.files().out_dir(unit));
878
879    fn opt(cmd: &mut ProcessBuilder, key: &str, prefix: &str, val: Option<&OsStr>) {
880        if let Some(val) = val {
881            let mut joined = OsString::from(prefix);
882            joined.push(val);
883            cmd.arg(key).arg(joined);
884        }
885    }
886
887    if unit.kind == Kind::Target {
888        opt(
889            cmd,
890            "--target",
891            "",
892            bcx.build_config
893                .requested_target
894                .as_ref()
895                .map(|s| s.as_ref()),
896        );
897    }
898
899    opt(cmd, "-C", "ar=", bcx.ar(unit.kind).map(|s| s.as_ref()));
900    opt(
901        cmd,
902        "-C",
903        "linker=",
904        bcx.linker(unit.kind).map(|s| s.as_ref()),
905    );
906    cmd.args(&cx.incremental_args(unit)?);
907
908    Ok(())
909}
910
911fn build_deps_args<'a, 'cfg>(
912    cmd: &mut ProcessBuilder,
913    cx: &mut Context<'a, 'cfg>,
914    unit: &Unit<'a>,
915) -> CargoResult<()> {
916    let bcx = cx.bcx;
917    cmd.arg("-L").arg(&{
918        let mut deps = OsString::from("dependency=");
919        deps.push(cx.files().deps_dir(unit));
920        deps
921    });
922
923    // Be sure that the host path is also listed. This'll ensure that proc-macro
924    // dependencies are correctly found (for reexported macros).
925    if let Kind::Target = unit.kind {
926        cmd.arg("-L").arg(&{
927            let mut deps = OsString::from("dependency=");
928            deps.push(cx.files().host_deps());
929            deps
930        });
931    }
932
933    let dep_targets = cx.dep_targets(unit);
934
935    // If there is not one linkable target but should, rustc fails later
936    // on if there is an `extern crate` for it. This may turn into a hard
937    // error in the future, see PR #4797
938    if !dep_targets
939        .iter()
940        .any(|u| !u.mode.is_doc() && u.target.linkable())
941    {
942        if let Some(u) = dep_targets
943            .iter()
944            .find(|u| !u.mode.is_doc() && u.target.is_lib())
945        {
946            bcx.config.shell().warn(format!(
947                "The package `{}` \
948                 provides no linkable target. The compiler might raise an error while compiling \
949                 `{}`. Consider adding 'dylib' or 'rlib' to key `crate-type` in `{}`'s \
950                 Cargo.toml. This warning might turn into a hard error in the future.",
951                u.target.crate_name(),
952                unit.target.crate_name(),
953                u.target.crate_name()
954            ))?;
955        }
956    }
957
958    for dep in dep_targets {
959        if dep.mode.is_run_custom_build() {
960            cmd.env("OUT_DIR", &cx.files().build_script_out_dir(&dep));
961        }
962        if dep.target.linkable() && !dep.mode.is_doc() {
963            link_to(cmd, cx, unit, &dep)?;
964        }
965    }
966
967    return Ok(());
968
969    fn link_to<'a, 'cfg>(
970        cmd: &mut ProcessBuilder,
971        cx: &mut Context<'a, 'cfg>,
972        current: &Unit<'a>,
973        dep: &Unit<'a>,
974    ) -> CargoResult<()> {
975        let bcx = cx.bcx;
976        for output in cx.outputs(dep)?.iter() {
977            if output.flavor != FileFlavor::Linkable {
978                continue;
979            }
980            let mut v = OsString::new();
981            let name = bcx.extern_crate_name(current, dep)?;
982            v.push(name);
983            v.push("=");
984            v.push(cx.files().out_dir(dep));
985            v.push(&path::MAIN_SEPARATOR.to_string());
986            v.push(&output.path.file_name().unwrap());
987            cmd.arg("--extern").arg(&v);
988        }
989        Ok(())
990    }
991}
992
993fn envify(s: &str) -> String {
994    s.chars()
995        .flat_map(|c| c.to_uppercase())
996        .map(|c| if c == '-' { '_' } else { c })
997        .collect()
998}
999
1000impl Kind {
1001    fn for_target(self, target: &Target) -> Kind {
1002        // Once we start compiling for the `Host` kind we continue doing so, but
1003        // if we are a `Target` kind and then we start compiling for a target
1004        // that needs to be on the host we lift ourselves up to `Host`
1005        match self {
1006            Kind::Host => Kind::Host,
1007            Kind::Target if target.for_host() => Kind::Host,
1008            Kind::Target => Kind::Target,
1009        }
1010    }
1011}
1012
1013fn assert_is_empty(line: &str) -> CargoResult<()> {
1014    if !line.is_empty() {
1015        Err(internal(&format!(
1016            "compiler stdout is not empty: `{}`",
1017            line
1018        )))
1019    } else {
1020        Ok(())
1021    }
1022}
1023
1024fn json_stderr(line: &str, package_id: PackageId, target: &Target) -> CargoResult<()> {
1025    // stderr from rustc/rustdoc can have a mix of JSON and non-JSON output
1026    if line.starts_with('{') {
1027        // Handle JSON lines
1028        let compiler_message = serde_json::from_str(line)
1029            .map_err(|_| internal(&format!("compiler produced invalid json: `{}`", line)))?;
1030
1031        machine_message::emit(&machine_message::FromCompiler {
1032            package_id,
1033            target,
1034            message: compiler_message,
1035        });
1036    } else {
1037        // Forward non-JSON to stderr
1038        writeln!(io::stderr(), "{}", line)?;
1039    }
1040    Ok(())
1041}