1use std::collections::hash_map::{Entry, HashMap};
2use std::collections::{BTreeSet, HashSet};
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::str;
6use std::sync::{Arc, Mutex};
7
8use crate::core::PackageId;
9use crate::util::errors::{CargoResult, CargoResultExt};
10use crate::util::machine_message;
11use crate::util::{self, internal, paths, profile};
12use crate::util::{Cfg, Freshness};
13
14use super::job::Work;
15use super::{fingerprint, Context, Kind, TargetConfig, Unit};
16
17#[derive(Clone, Debug, Hash)]
19pub struct BuildOutput {
20 pub library_paths: Vec<PathBuf>,
22 pub library_links: Vec<String>,
24 pub cfgs: Vec<String>,
26 pub env: Vec<(String, String)>,
28 pub metadata: Vec<(String, String)>,
30 pub rerun_if_changed: Vec<PathBuf>,
33 pub rerun_if_env_changed: Vec<String>,
35 pub warnings: Vec<String>,
37}
38
39pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
41
42pub struct BuildState {
44 pub outputs: Mutex<BuildMap>,
45 overrides: HashMap<(String, Kind), BuildOutput>,
46}
47
48#[derive(Default)]
49pub struct BuildScripts {
50 pub to_link: Vec<(PackageId, Kind)>,
64 seen_to_link: HashSet<(PackageId, Kind)>,
65 pub plugins: BTreeSet<PackageId>,
66}
67
68pub struct BuildDeps {
69 pub build_script_output: PathBuf,
70 pub rerun_if_changed: Vec<PathBuf>,
71 pub rerun_if_env_changed: Vec<String>,
72}
73
74pub fn prepare<'a, 'cfg>(
81 cx: &mut Context<'a, 'cfg>,
82 unit: &Unit<'a>,
83) -> CargoResult<(Work, Work, Freshness)> {
84 let _p = profile::start(format!(
85 "build script prepare: {}/{}",
86 unit.pkg,
87 unit.target.name()
88 ));
89
90 let key = (unit.pkg.package_id(), unit.kind);
91 let overridden = cx.build_script_overridden.contains(&key);
92 let (work_dirty, work_fresh) = if overridden {
93 (Work::noop(), Work::noop())
94 } else {
95 build_work(cx, unit)?
96 };
97
98 if cx.bcx.build_config.build_plan {
99 Ok((work_dirty, work_fresh, Freshness::Dirty))
100 } else {
101 let (freshness, dirty, fresh) = fingerprint::prepare_build_cmd(cx, unit)?;
104
105 Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
106 }
107}
108
109fn emit_build_output(output: &BuildOutput, package_id: PackageId) {
110 let library_paths = output
111 .library_paths
112 .iter()
113 .map(|l| l.display().to_string())
114 .collect::<Vec<_>>();
115
116 machine_message::emit(&machine_message::BuildScript {
117 package_id,
118 linked_libs: &output.library_links,
119 linked_paths: &library_paths,
120 cfgs: &output.cfgs,
121 env: &output.env,
122 });
123}
124
125fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work)> {
126 assert!(unit.mode.is_run_custom_build());
127 let bcx = &cx.bcx;
128 let dependencies = cx.dep_targets(unit);
129 let build_script_unit = dependencies
130 .iter()
131 .find(|d| !d.mode.is_run_custom_build() && d.target.is_custom_build())
132 .expect("running a script not depending on an actual script");
133 let script_dir = cx.files().build_script_dir(build_script_unit);
134 let script_out_dir = cx.files().build_script_out_dir(unit);
135 let build_plan = bcx.build_config.build_plan;
136 let invocation_name = unit.buildkey();
137
138 if let Some(deps) = unit.pkg.manifest().metabuild() {
139 prepare_metabuild(cx, build_script_unit, deps)?;
140 }
141
142 let to_exec = script_dir.join(unit.target.name());
144
145 let to_exec = to_exec.into_os_string();
153 let mut cmd = cx.compilation.host_process(to_exec, unit.pkg)?;
154 let debug = unit.profile.debuginfo.unwrap_or(0) != 0;
155 cmd.env("OUT_DIR", &script_out_dir)
156 .env("CARGO_MANIFEST_DIR", unit.pkg.root())
157 .env("NUM_JOBS", &bcx.jobs().to_string())
158 .env(
159 "TARGET",
160 &match unit.kind {
161 Kind::Host => &bcx.host_triple(),
162 Kind::Target => bcx.target_triple(),
163 },
164 )
165 .env("DEBUG", debug.to_string())
166 .env("OPT_LEVEL", &unit.profile.opt_level.to_string())
167 .env(
168 "PROFILE",
169 if bcx.build_config.release {
170 "release"
171 } else {
172 "debug"
173 },
174 )
175 .env("HOST", &bcx.host_triple())
176 .env("RUSTC", &bcx.rustc.path)
177 .env("RUSTDOC", &*bcx.config.rustdoc()?)
178 .inherit_jobserver(&cx.jobserver);
179
180 if let Some(ref linker) = bcx.target_config.linker {
181 cmd.env("RUSTC_LINKER", linker);
182 }
183
184 if let Some(links) = unit.pkg.manifest().links() {
185 cmd.env("CARGO_MANIFEST_LINKS", links);
186 }
187
188 for feat in bcx.resolve.features(unit.pkg.package_id()).iter() {
191 cmd.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
192 }
193
194 let mut cfg_map = HashMap::new();
195 for cfg in bcx.cfg(unit.kind) {
196 match *cfg {
197 Cfg::Name(ref n) => {
198 cfg_map.insert(n.clone(), None);
199 }
200 Cfg::KeyPair(ref k, ref v) => {
201 if let Some(ref mut values) =
202 *cfg_map.entry(k.clone()).or_insert_with(|| Some(Vec::new()))
203 {
204 values.push(v.clone())
205 }
206 }
207 }
208 }
209 for (k, v) in cfg_map {
210 let k = format!("CARGO_CFG_{}", super::envify(&k));
211 match v {
212 Some(list) => {
213 cmd.env(&k, list.join(","));
214 }
215 None => {
216 cmd.env(&k, "");
217 }
218 }
219 }
220
221 let lib_deps = {
227 dependencies
228 .iter()
229 .filter_map(|unit| {
230 if unit.mode.is_run_custom_build() {
231 Some((
232 unit.pkg.manifest().links().unwrap().to_string(),
233 unit.pkg.package_id(),
234 ))
235 } else {
236 None
237 }
238 })
239 .collect::<Vec<_>>()
240 };
241 let pkg_name = unit.pkg.to_string();
242 let build_state = Arc::clone(&cx.build_state);
243 let id = unit.pkg.package_id();
244 let (output_file, err_file, root_output_file) = {
245 let build_output_parent = script_out_dir.parent().unwrap();
246 let output_file = build_output_parent.join("output");
247 let err_file = build_output_parent.join("stderr");
248 let root_output_file = build_output_parent.join("root-output");
249 (output_file, err_file, root_output_file)
250 };
251 let host_target_root = cx.files().target_root().to_path_buf();
252 let all = (
253 id,
254 pkg_name.clone(),
255 Arc::clone(&build_state),
256 output_file.clone(),
257 script_out_dir.clone(),
258 );
259 let build_scripts = super::load_build_deps(cx, unit);
260 let kind = unit.kind;
261 let json_messages = bcx.build_config.json_messages();
262 let extra_verbose = bcx.config.extra_verbose();
263
264 let prev_script_out_dir = paths::read_bytes(&root_output_file)
267 .and_then(|bytes| util::bytes2path(&bytes))
268 .unwrap_or_else(|_| script_out_dir.clone());
269
270 let prev_output = BuildOutput::parse_file(
271 &output_file,
272 &pkg_name,
273 &prev_script_out_dir,
274 &script_out_dir,
275 )
276 .ok();
277 let deps = BuildDeps::new(&output_file, prev_output.as_ref());
278 cx.build_explicit_deps.insert(*unit, deps);
279
280 fs::create_dir_all(&script_dir)?;
281 fs::create_dir_all(&script_out_dir)?;
282
283 let dirty = Work::new(move |state| {
289 if fs::metadata(&script_out_dir).is_err() {
294 fs::create_dir(&script_out_dir).chain_err(|| {
295 internal(
296 "failed to create script output directory for \
297 build command",
298 )
299 })?;
300 }
301
302 if !build_plan {
307 let build_state = build_state.outputs.lock().unwrap();
308 for (name, id) in lib_deps {
309 let key = (id, kind);
310 let state = build_state.get(&key).ok_or_else(|| {
311 internal(format!(
312 "failed to locate build state for env \
313 vars: {}/{:?}",
314 id, kind
315 ))
316 })?;
317 let data = &state.metadata;
318 for &(ref key, ref value) in data.iter() {
319 cmd.env(
320 &format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
321 value,
322 );
323 }
324 }
325 if let Some(build_scripts) = build_scripts {
326 super::add_plugin_deps(&mut cmd, &build_state, &build_scripts, &host_target_root)?;
327 }
328 }
329
330 if build_plan {
332 state.build_plan(invocation_name, cmd.clone(), Arc::new(Vec::new()));
333 } else {
334 state.running(&cmd);
335 let output = if extra_verbose {
336 let prefix = format!("[{} {}] ", id.name(), id.version());
337 state.capture_output(&cmd, Some(prefix), true)
338 } else {
339 cmd.exec_with_output()
340 };
341 let output = output.map_err(|e| {
342 failure::format_err!(
343 "failed to run custom build command for `{}`\n{}",
344 pkg_name,
345 e
346 )
347 })?;
348
349 paths::write(&output_file, &output.stdout)?;
357 paths::write(&err_file, &output.stderr)?;
358 paths::write(&root_output_file, util::path2bytes(&script_out_dir)?)?;
359 let parsed_output =
360 BuildOutput::parse(&output.stdout, &pkg_name, &script_out_dir, &script_out_dir)?;
361
362 if json_messages {
363 emit_build_output(&parsed_output, id);
364 }
365 build_state.insert(id, kind, parsed_output);
366 }
367 Ok(())
368 });
369
370 let fresh = Work::new(move |_tx| {
374 let (id, pkg_name, build_state, output_file, script_out_dir) = all;
375 let output = match prev_output {
376 Some(output) => output,
377 None => BuildOutput::parse_file(
378 &output_file,
379 &pkg_name,
380 &prev_script_out_dir,
381 &script_out_dir,
382 )?,
383 };
384
385 if json_messages {
386 emit_build_output(&output, id);
387 }
388
389 build_state.insert(id, kind, output);
390 Ok(())
391 });
392
393 Ok((dirty, fresh))
394}
395
396impl BuildState {
397 pub fn new(host_config: &TargetConfig, target_config: &TargetConfig) -> BuildState {
398 let mut overrides = HashMap::new();
399 let i1 = host_config.overrides.iter().map(|p| (p, Kind::Host));
400 let i2 = target_config.overrides.iter().map(|p| (p, Kind::Target));
401 for ((name, output), kind) in i1.chain(i2) {
402 overrides.insert((name.clone(), kind), output.clone());
403 }
404 BuildState {
405 outputs: Mutex::new(HashMap::new()),
406 overrides,
407 }
408 }
409
410 fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
411 self.outputs.lock().unwrap().insert((id, kind), output);
412 }
413}
414
415impl BuildOutput {
416 pub fn parse_file(
417 path: &Path,
418 pkg_name: &str,
419 script_out_dir_when_generated: &Path,
420 script_out_dir: &Path,
421 ) -> CargoResult<BuildOutput> {
422 let contents = paths::read_bytes(path)?;
423 BuildOutput::parse(
424 &contents,
425 pkg_name,
426 script_out_dir_when_generated,
427 script_out_dir,
428 )
429 }
430
431 pub fn parse(
434 input: &[u8],
435 pkg_name: &str,
436 script_out_dir_when_generated: &Path,
437 script_out_dir: &Path,
438 ) -> CargoResult<BuildOutput> {
439 let mut library_paths = Vec::new();
440 let mut library_links = Vec::new();
441 let mut cfgs = Vec::new();
442 let mut env = Vec::new();
443 let mut metadata = Vec::new();
444 let mut rerun_if_changed = Vec::new();
445 let mut rerun_if_env_changed = Vec::new();
446 let mut warnings = Vec::new();
447 let whence = format!("build script of `{}`", pkg_name);
448
449 for line in input.split(|b| *b == b'\n') {
450 let line = match str::from_utf8(line) {
451 Ok(line) => line.trim(),
452 Err(..) => continue,
453 };
454 let mut iter = line.splitn(2, ':');
455 if iter.next() != Some("cargo") {
456 continue;
458 }
459 let data = match iter.next() {
460 Some(val) => val,
461 None => continue,
462 };
463
464 let mut iter = data.splitn(2, '=');
466 let key = iter.next();
467 let value = iter.next();
468 let (key, value) = match (key, value) {
469 (Some(a), Some(b)) => (a, b.trim_end()),
470 _ => failure::bail!("Wrong output in {}: `{}`", whence, line),
472 };
473
474 let value = value.replace(
476 script_out_dir_when_generated.to_str().unwrap(),
477 script_out_dir.to_str().unwrap(),
478 );
479
480 match key {
481 "rustc-flags" => {
482 let (paths, links) = BuildOutput::parse_rustc_flags(&value, &whence)?;
483 library_links.extend(links.into_iter());
484 library_paths.extend(paths.into_iter());
485 }
486 "rustc-link-lib" => library_links.push(value.to_string()),
487 "rustc-link-search" => library_paths.push(PathBuf::from(value)),
488 "rustc-cfg" => cfgs.push(value.to_string()),
489 "rustc-env" => env.push(BuildOutput::parse_rustc_env(&value, &whence)?),
490 "warning" => warnings.push(value.to_string()),
491 "rerun-if-changed" => rerun_if_changed.push(PathBuf::from(value)),
492 "rerun-if-env-changed" => rerun_if_env_changed.push(value.to_string()),
493 _ => metadata.push((key.to_string(), value.to_string())),
494 }
495 }
496
497 Ok(BuildOutput {
498 library_paths,
499 library_links,
500 cfgs,
501 env,
502 metadata,
503 rerun_if_changed,
504 rerun_if_env_changed,
505 warnings,
506 })
507 }
508
509 pub fn parse_rustc_flags(
510 value: &str,
511 whence: &str,
512 ) -> CargoResult<(Vec<PathBuf>, Vec<String>)> {
513 let value = value.trim();
514 let mut flags_iter = value
515 .split(|c: char| c.is_whitespace())
516 .filter(|w| w.chars().any(|c| !c.is_whitespace()));
517 let (mut library_paths, mut library_links) = (Vec::new(), Vec::new());
518 while let Some(flag) = flags_iter.next() {
519 if flag != "-l" && flag != "-L" {
520 failure::bail!(
521 "Only `-l` and `-L` flags are allowed in {}: `{}`",
522 whence,
523 value
524 )
525 }
526 let value = match flags_iter.next() {
527 Some(v) => v,
528 None => failure::bail!(
529 "Flag in rustc-flags has no value in {}: `{}`",
530 whence,
531 value
532 ),
533 };
534 match flag {
535 "-l" => library_links.push(value.to_string()),
536 "-L" => library_paths.push(PathBuf::from(value)),
537
538 _ => failure::bail!("only -l and -L flags are allowed"),
540 };
541 }
542 Ok((library_paths, library_links))
543 }
544
545 pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
546 let mut iter = value.splitn(2, '=');
547 let name = iter.next();
548 let val = iter.next();
549 match (name, val) {
550 (Some(n), Some(v)) => Ok((n.to_owned(), v.to_owned())),
551 _ => failure::bail!("Variable rustc-env has no value in {}: {}", whence, value),
552 }
553 }
554}
555
556fn prepare_metabuild<'a, 'cfg>(
557 cx: &Context<'a, 'cfg>,
558 unit: &Unit<'a>,
559 deps: &[String],
560) -> CargoResult<()> {
561 let mut output = Vec::new();
562 let available_deps = cx.dep_targets(unit);
563 let meta_deps: Vec<_> = deps
565 .iter()
566 .filter_map(|name| {
567 available_deps
568 .iter()
569 .find(|u| u.pkg.name().as_str() == name.as_str())
570 .map(|dep| dep.target.crate_name())
571 })
572 .collect();
573 for dep in &meta_deps {
574 output.push(format!("use {};\n", dep));
575 }
576 output.push("fn main() {\n".to_string());
577 for dep in &meta_deps {
578 output.push(format!(" {}::metabuild();\n", dep));
579 }
580 output.push("}\n".to_string());
581 let output = output.join("");
582 let path = unit.pkg.manifest().metabuild_path(cx.bcx.ws.target_dir());
583 fs::create_dir_all(path.parent().unwrap())?;
584 paths::write_if_changed(path, &output)?;
585 Ok(())
586}
587
588impl BuildDeps {
589 pub fn new(output_file: &Path, output: Option<&BuildOutput>) -> BuildDeps {
590 BuildDeps {
591 build_script_output: output_file.to_path_buf(),
592 rerun_if_changed: output
593 .map(|p| &p.rerun_if_changed)
594 .cloned()
595 .unwrap_or_default(),
596 rerun_if_env_changed: output
597 .map(|p| &p.rerun_if_env_changed)
598 .cloned()
599 .unwrap_or_default(),
600 }
601 }
602}
603
604pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CargoResult<()> {
614 let mut ret = HashMap::new();
615 for unit in units {
616 build(&mut ret, cx, unit)?;
617 }
618 cx.build_scripts
619 .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
620 return Ok(());
621
622 fn build<'a, 'b, 'cfg>(
625 out: &'a mut HashMap<Unit<'b>, BuildScripts>,
626 cx: &mut Context<'b, 'cfg>,
627 unit: &Unit<'b>,
628 ) -> CargoResult<&'a BuildScripts> {
629 if out.contains_key(unit) {
632 return Ok(&out[unit]);
633 }
634
635 {
636 let key = unit
637 .pkg
638 .manifest()
639 .links()
640 .map(|l| (l.to_string(), unit.kind));
641 let build_state = &cx.build_state;
642 if let Some(output) = key.and_then(|k| build_state.overrides.get(&k)) {
643 let key = (unit.pkg.package_id(), unit.kind);
644 cx.build_script_overridden.insert(key);
645 build_state
646 .outputs
647 .lock()
648 .unwrap()
649 .insert(key, output.clone());
650 }
651 }
652
653 let mut ret = BuildScripts::default();
654
655 if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
656 add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
657 }
658
659 let mut targets = cx.dep_targets(unit);
664 targets.sort_by_key(|u| u.pkg.package_id());
665
666 for unit in targets.iter() {
667 let dep_scripts = build(out, cx, unit)?;
668
669 if unit.target.for_host() {
670 ret.plugins
671 .extend(dep_scripts.to_link.iter().map(|p| &p.0).cloned());
672 } else if unit.target.linkable() {
673 for &(pkg, kind) in dep_scripts.to_link.iter() {
674 add_to_link(&mut ret, pkg, kind);
675 }
676 }
677 }
678
679 match out.entry(*unit) {
680 Entry::Vacant(entry) => Ok(entry.insert(ret)),
681 Entry::Occupied(_) => panic!("cyclic dependencies in `build_map`"),
682 }
683 }
684
685 fn add_to_link(scripts: &mut BuildScripts, pkg: PackageId, kind: Kind) {
688 if scripts.seen_to_link.insert((pkg, kind)) {
689 scripts.to_link.push((pkg, kind));
690 }
691 }
692}