1use std::collections::{BTreeSet, HashMap};
4use std::ffi::{OsStr, OsString};
5use std::path::Path;
6use std::path::PathBuf;
7
8use cargo_platform::CfgExpr;
9use cargo_util::{ProcessBuilder, paths};
10
11use crate::core::Package;
12use crate::core::compiler::BuildContext;
13use crate::core::compiler::CompileTarget;
14use crate::core::compiler::RustdocFingerprint;
15use crate::core::compiler::apply_env_config;
16use crate::core::compiler::{CompileKind, Unit, UnitHash};
17use crate::util::{CargoResult, GlobalContext};
18
19#[derive(Debug)]
21enum ToolKind {
22 Rustc,
24 Rustdoc,
26 HostProcess,
28 TargetProcess,
30}
31
32impl ToolKind {
33 fn is_rustc_tool(&self) -> bool {
34 matches!(self, ToolKind::Rustc | ToolKind::Rustdoc)
35 }
36}
37
38pub struct Doctest {
40 pub unit: Unit,
42 pub args: Vec<OsString>,
44 pub unstable_opts: bool,
46 pub linker: Option<PathBuf>,
48 pub script_metas: Option<Vec<UnitHash>>,
52
53 pub env: HashMap<String, OsString>,
55}
56
57pub struct UnitOutput {
59 pub unit: Unit,
61 pub path: PathBuf,
63 pub script_metas: Option<Vec<UnitHash>>,
67
68 pub env: HashMap<String, OsString>,
70}
71
72pub struct Compilation<'gctx> {
74 pub tests: Vec<UnitOutput>,
76
77 pub binaries: Vec<UnitOutput>,
79
80 pub cdylibs: Vec<UnitOutput>,
82
83 pub root_crate_names: Vec<String>,
85
86 pub native_dirs: BTreeSet<PathBuf>,
93
94 pub root_output: HashMap<CompileKind, PathBuf>,
96
97 pub deps_output: HashMap<CompileKind, PathBuf>,
100
101 sysroot_target_libdir: HashMap<CompileKind, PathBuf>,
103
104 pub extra_env: HashMap<UnitHash, Vec<(String, String)>>,
110
111 pub to_doc_test: Vec<Doctest>,
113
114 pub rustdoc_fingerprints: Option<HashMap<CompileKind, RustdocFingerprint>>,
118
119 pub host: String,
121
122 gctx: &'gctx GlobalContext,
123
124 rustc_process: ProcessBuilder,
126 rustc_workspace_wrapper_process: ProcessBuilder,
128 primary_rustc_process: Option<ProcessBuilder>,
131
132 runners: HashMap<CompileKind, Option<(PathBuf, Vec<String>)>>,
134 linkers: HashMap<CompileKind, Option<PathBuf>>,
136
137 pub lint_warning_count: usize,
139}
140
141impl<'gctx> Compilation<'gctx> {
142 pub fn new<'a>(bcx: &BuildContext<'a, 'gctx>) -> CargoResult<Compilation<'gctx>> {
143 let rustc_process = bcx.rustc().process();
144 let primary_rustc_process = bcx.build_config.primary_unit_rustc.clone();
145 let rustc_workspace_wrapper_process = bcx.rustc().workspace_process();
146 let host = bcx.host_triple().to_string();
147 let mut runners = bcx
148 .build_config
149 .requested_kinds
150 .iter()
151 .chain(Some(&CompileKind::Host))
152 .map(|kind| Ok((*kind, target_runner(bcx, *kind)?)))
153 .collect::<CargoResult<HashMap<_, _>>>()?;
154 if !bcx.gctx.target_applies_to_host()? {
155 let kind = explicit_host_kind(&host);
160 runners.insert(kind, target_runner(bcx, kind)?);
161 }
162
163 let mut linkers = bcx
164 .build_config
165 .requested_kinds
166 .iter()
167 .chain(Some(&CompileKind::Host))
168 .map(|kind| Ok((*kind, target_linker(bcx, *kind)?)))
169 .collect::<CargoResult<HashMap<_, _>>>()?;
170 if !bcx.gctx.target_applies_to_host()? {
171 let kind = explicit_host_kind(&host);
173 linkers.insert(kind, target_linker(bcx, kind)?);
174 }
175 Ok(Compilation {
176 native_dirs: BTreeSet::new(),
177 root_output: HashMap::new(),
178 deps_output: HashMap::new(),
179 sysroot_target_libdir: get_sysroot_target_libdir(bcx)?,
180 tests: Vec::new(),
181 binaries: Vec::new(),
182 cdylibs: Vec::new(),
183 root_crate_names: Vec::new(),
184 extra_env: HashMap::new(),
185 to_doc_test: Vec::new(),
186 rustdoc_fingerprints: None,
187 gctx: bcx.gctx,
188 host,
189 rustc_process,
190 rustc_workspace_wrapper_process,
191 primary_rustc_process,
192 runners,
193 linkers,
194 lint_warning_count: 0,
195 })
196 }
197
198 pub fn rustc_process(
206 &self,
207 unit: &Unit,
208 is_primary: bool,
209 is_workspace: bool,
210 ) -> CargoResult<ProcessBuilder> {
211 let mut rustc = if is_primary && self.primary_rustc_process.is_some() {
212 self.primary_rustc_process.clone().unwrap()
213 } else if is_workspace {
214 self.rustc_workspace_wrapper_process.clone()
215 } else {
216 self.rustc_process.clone()
217 };
218 if self.gctx.extra_verbose() {
219 rustc.display_env_vars();
220 }
221 let cmd = fill_rustc_tool_env(rustc, unit);
222 self.fill_env(cmd, &unit.pkg, None, unit.kind, ToolKind::Rustc)
223 }
224
225 pub fn rustdoc_process(
227 &self,
228 unit: &Unit,
229 script_metas: Option<&Vec<UnitHash>>,
230 ) -> CargoResult<ProcessBuilder> {
231 let mut rustdoc = ProcessBuilder::new(&*self.gctx.rustdoc()?);
232 if self.gctx.extra_verbose() {
233 rustdoc.display_env_vars();
234 }
235 let cmd = fill_rustc_tool_env(rustdoc, unit);
236 let mut cmd = self.fill_env(cmd, &unit.pkg, script_metas, unit.kind, ToolKind::Rustdoc)?;
237 cmd.retry_with_argfile(true);
238 unit.target.edition().cmd_edition_arg(&mut cmd);
239
240 for crate_type in unit.target.rustc_crate_types() {
241 cmd.arg("--crate-type").arg(crate_type.as_str());
242 }
243
244 Ok(cmd)
245 }
246
247 pub fn host_process<T: AsRef<OsStr>>(
254 &self,
255 cmd: T,
256 pkg: &Package,
257 ) -> CargoResult<ProcessBuilder> {
258 let builder = if !self.gctx.target_applies_to_host()?
261 && let Some((runner, args)) = self
262 .runners
263 .get(&CompileKind::Host)
264 .and_then(|x| x.as_ref())
265 {
266 let mut builder = ProcessBuilder::new(runner);
267 builder.args(args);
268 builder.arg(cmd);
269 builder
270 } else {
271 ProcessBuilder::new(cmd)
272 };
273 self.fill_env(builder, pkg, None, CompileKind::Host, ToolKind::HostProcess)
274 }
275
276 pub fn target_runner(&self, kind: CompileKind) -> Option<&(PathBuf, Vec<String>)> {
277 let target_applies_to_host = self.gctx.target_applies_to_host().unwrap_or(true);
278 let kind = if !target_applies_to_host && kind.is_host() {
279 explicit_host_kind(&self.host)
282 } else {
283 kind
284 };
285 self.runners.get(&kind).and_then(|x| x.as_ref())
286 }
287
288 pub fn host_linker(&self) -> Option<&Path> {
290 self.linkers
291 .get(&CompileKind::Host)
292 .and_then(|x| x.as_ref())
293 .map(|x| x.as_path())
294 }
295
296 pub fn target_linker(&self, kind: CompileKind) -> Option<&Path> {
298 let target_applies_to_host = self.gctx.target_applies_to_host().unwrap_or(true);
299 let kind = if !target_applies_to_host && kind.is_host() {
300 explicit_host_kind(&self.host)
303 } else {
304 kind
305 };
306 self.linkers
307 .get(&kind)
308 .and_then(|x| x.as_ref())
309 .map(|x| x.as_path())
310 }
311
312 pub fn target_process<T: AsRef<OsStr>>(
320 &self,
321 cmd: T,
322 kind: CompileKind,
323 pkg: &Package,
324 script_metas: Option<&Vec<UnitHash>>,
325 ) -> CargoResult<ProcessBuilder> {
326 let builder = if let Some((runner, args)) = self.target_runner(kind) {
327 let mut builder = ProcessBuilder::new(runner);
328 builder.args(args);
329 builder.arg(cmd);
330 builder
331 } else {
332 ProcessBuilder::new(cmd)
333 };
334 let tool_kind = ToolKind::TargetProcess;
335 let mut builder = self.fill_env(builder, pkg, script_metas, kind, tool_kind)?;
336
337 if let Some(client) = self.gctx.jobserver_from_env() {
338 builder.inherit_jobserver(client);
339 }
340
341 Ok(builder)
342 }
343
344 fn fill_env(
350 &self,
351 mut cmd: ProcessBuilder,
352 pkg: &Package,
353 script_metas: Option<&Vec<UnitHash>>,
354 kind: CompileKind,
355 tool_kind: ToolKind,
356 ) -> CargoResult<ProcessBuilder> {
357 let mut search_path = Vec::new();
358 if tool_kind.is_rustc_tool() {
359 if matches!(tool_kind, ToolKind::Rustdoc) {
360 search_path.extend(super::filter_dynamic_search_path(
367 self.native_dirs.iter(),
368 &self.root_output[&CompileKind::Host],
369 ));
370 }
371 search_path.push(self.deps_output[&CompileKind::Host].clone());
372 } else {
373 if let Some(path) = self.root_output.get(&kind) {
374 search_path.extend(super::filter_dynamic_search_path(
375 self.native_dirs.iter(),
376 path,
377 ));
378 search_path.push(path.clone());
379 }
380 search_path.push(self.deps_output[&kind].clone());
381 if self.gctx.cli_unstable().build_std.is_none() ||
386 pkg.proc_macro()
388 {
389 search_path.push(self.sysroot_target_libdir[&kind].clone());
390 }
391 }
392
393 let dylib_path = paths::dylib_path();
394 let dylib_path_is_empty = dylib_path.is_empty();
395 if dylib_path.starts_with(&search_path) {
396 search_path = dylib_path;
397 } else {
398 search_path.extend(dylib_path.into_iter());
399 }
400 if cfg!(target_os = "macos") && dylib_path_is_empty {
401 if let Some(home) = self.gctx.get_env_os("HOME") {
405 search_path.push(PathBuf::from(home).join("lib"));
406 }
407 search_path.push(PathBuf::from("/usr/local/lib"));
408 search_path.push(PathBuf::from("/usr/lib"));
409 }
410 let search_path = paths::join_paths(&search_path, paths::dylib_path_envvar())?;
411
412 cmd.env(paths::dylib_path_envvar(), &search_path);
413 if let Some(meta_vec) = script_metas {
414 for meta in meta_vec {
415 if let Some(env) = self.extra_env.get(meta) {
416 for (k, v) in env {
417 cmd.env(k, v);
418 }
419 }
420 }
421 }
422
423 let cargo_exe = self.gctx.cargo_exe()?;
424 cmd.env(crate::CARGO_ENV, cargo_exe);
425
426 cmd.env("CARGO_MANIFEST_DIR", pkg.root())
431 .env("CARGO_MANIFEST_PATH", pkg.manifest_path())
432 .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
433 .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
434 .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
435 .env("CARGO_PKG_VERSION_PRE", pkg.version().pre.as_str())
436 .env("CARGO_PKG_VERSION", &pkg.version().to_string())
437 .env("CARGO_PKG_NAME", &*pkg.name());
438
439 for (key, value) in pkg.manifest().metadata().env_vars() {
440 cmd.env(key, value.as_ref());
441 }
442
443 cmd.cwd(pkg.root());
444
445 apply_env_config(self.gctx, &mut cmd)?;
446
447 Ok(cmd)
448 }
449}
450
451fn fill_rustc_tool_env(mut cmd: ProcessBuilder, unit: &Unit) -> ProcessBuilder {
454 if unit.target.is_executable() {
455 let name = unit
456 .target
457 .binary_filename()
458 .unwrap_or(unit.target.name().to_string());
459
460 cmd.env("CARGO_BIN_NAME", name);
461 }
462 cmd.env("CARGO_CRATE_NAME", unit.target.crate_name());
463 cmd
464}
465
466fn get_sysroot_target_libdir(
467 bcx: &BuildContext<'_, '_>,
468) -> CargoResult<HashMap<CompileKind, PathBuf>> {
469 bcx.all_kinds
470 .iter()
471 .map(|&kind| {
472 let Some(info) = bcx.target_data.get_info(kind) else {
473 let target = match kind {
474 CompileKind::Host => "host".to_owned(),
475 CompileKind::Target(s) => s.short_name().to_owned(),
476 };
477
478 let dependency = bcx
479 .unit_graph
480 .iter()
481 .find_map(|(u, _)| (u.kind == kind).then_some(u.pkg.summary().package_id()))
482 .unwrap();
483
484 anyhow::bail!(
485 "could not find specification for target `{target}`.\n \
486 Dependency `{dependency}` requires to build for target `{target}`."
487 )
488 };
489
490 Ok((kind, info.sysroot_target_libdir.clone()))
491 })
492 .collect()
493}
494
495fn target_runner(
496 bcx: &BuildContext<'_, '_>,
497 kind: CompileKind,
498) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
499 if let Some(runner) = bcx.target_data.target_config(kind).runner.as_ref() {
500 let path = runner.val.path.clone().resolve_program(bcx.gctx);
501 return Ok(Some((path, runner.val.args.clone())));
502 }
503
504 let target_cfg = bcx.target_data.info(kind).cfg();
506 let mut cfgs = bcx
507 .gctx
508 .target_cfgs()?
509 .iter()
510 .filter_map(|(key, cfg)| cfg.runner.as_ref().map(|runner| (key, runner)))
511 .filter(|(key, _runner)| CfgExpr::matches_key(key, target_cfg));
512 let matching_runner = cfgs.next();
513 if let Some((key, runner)) = cfgs.next() {
514 anyhow::bail!(
515 "several matching instances of `target.'cfg(..)'.runner` in configurations\n\
516 first match `{}` located in {}\n\
517 second match `{}` located in {}",
518 matching_runner.unwrap().0,
519 matching_runner.unwrap().1.definition,
520 key,
521 runner.definition
522 );
523 }
524 Ok(matching_runner.map(|(_k, runner)| {
525 (
526 runner.val.path.clone().resolve_program(bcx.gctx),
527 runner.val.args.clone(),
528 )
529 }))
530}
531
532fn target_linker(bcx: &BuildContext<'_, '_>, kind: CompileKind) -> CargoResult<Option<PathBuf>> {
534 if let Some(path) = bcx
536 .target_data
537 .target_config(kind)
538 .linker
539 .as_ref()
540 .map(|l| l.val.clone().resolve_program(bcx.gctx))
541 {
542 return Ok(Some(path));
543 }
544
545 let target_cfg = bcx.target_data.info(kind).cfg();
547 let mut cfgs = bcx
548 .gctx
549 .target_cfgs()?
550 .iter()
551 .filter_map(|(key, cfg)| cfg.linker.as_ref().map(|linker| (key, linker)))
552 .filter(|(key, _linker)| CfgExpr::matches_key(key, target_cfg));
553 let matching_linker = cfgs.next();
554 if let Some((key, linker)) = cfgs.next() {
555 anyhow::bail!(
556 "several matching instances of `target.'cfg(..)'.linker` in configurations\n\
557 first match `{}` located in {}\n\
558 second match `{}` located in {}",
559 matching_linker.unwrap().0,
560 matching_linker.unwrap().1.definition,
561 key,
562 linker.definition
563 );
564 }
565 Ok(matching_linker.map(|(_k, linker)| linker.val.clone().resolve_program(bcx.gctx)))
566}
567
568fn explicit_host_kind(host: &str) -> CompileKind {
569 let target = CompileTarget::new(host, false).expect("must be a host tuple");
570 CompileKind::Target(target)
571}