1#![doc(html_root_url = "https://docs.rs/pkg-config/0.3")]
86
87use std::collections::HashMap;
88use std::env;
89use std::error;
90use std::ffi::{OsStr, OsString};
91use std::fmt;
92use std::fmt::Display;
93use std::io;
94use std::ops::{Bound, RangeBounds};
95use std::path::PathBuf;
96use std::process::{Command, Output};
97use std::str;
98
99struct WrappedCommand {
103 inner: Command,
104 program: OsString,
105 env_vars: Vec<(OsString, OsString)>,
106 args: Vec<OsString>,
107}
108
109#[derive(Clone, Debug)]
110pub struct Config {
111 statik: Option<bool>,
112 min_version: Bound<String>,
113 max_version: Bound<String>,
114 extra_args: Vec<OsString>,
115 cargo_metadata: bool,
116 env_metadata: bool,
117 print_system_libs: bool,
118 print_system_cflags: bool,
119}
120
121#[derive(Clone, Debug)]
122pub struct Library {
123 pub libs: Vec<String>,
125 pub link_paths: Vec<PathBuf>,
127 pub link_files: Vec<PathBuf>,
129 pub frameworks: Vec<String>,
131 pub framework_paths: Vec<PathBuf>,
133 pub include_paths: Vec<PathBuf>,
135 pub ld_args: Vec<Vec<String>>,
137 pub defines: HashMap<String, Option<String>>,
139 pub version: String,
141 _priv: (),
144}
145
146pub enum Error {
148 EnvNoPkgConfig(String),
152
153 CrossCompilation,
159
160 Command { command: String, cause: io::Error },
164
165 Failure { command: String, output: Output },
169
170 ProbeFailure {
174 name: String,
175 command: String,
176 output: Output,
177 },
178
179 #[doc(hidden)]
180 __Nonexhaustive,
182}
183
184impl WrappedCommand {
185 fn new<S: AsRef<OsStr>>(program: S) -> Self {
186 Self {
187 inner: Command::new(program.as_ref()),
188 program: program.as_ref().to_os_string(),
189 env_vars: Vec::new(),
190 args: Vec::new(),
191 }
192 }
193
194 fn args<I, S>(&mut self, args: I) -> &mut Self
195 where
196 I: IntoIterator<Item = S> + Clone,
197 S: AsRef<OsStr>,
198 {
199 self.inner.args(args.clone());
200 self.args
201 .extend(args.into_iter().map(|arg| arg.as_ref().to_os_string()));
202
203 self
204 }
205
206 fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
207 self.inner.arg(arg.as_ref());
208 self.args.push(arg.as_ref().to_os_string());
209
210 self
211 }
212
213 fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
214 where
215 K: AsRef<OsStr>,
216 V: AsRef<OsStr>,
217 {
218 self.inner.env(key.as_ref(), value.as_ref());
219 self.env_vars
220 .push((key.as_ref().to_os_string(), value.as_ref().to_os_string()));
221
222 self
223 }
224
225 fn output(&mut self) -> io::Result<Output> {
226 self.inner.output()
227 }
228}
229
230impl Display for WrappedCommand {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 let envs = self
241 .env_vars
242 .iter()
243 .map(|(env, arg)| format!("{}={}", env.to_string_lossy(), arg.to_string_lossy()))
244 .collect::<Vec<String>>()
245 .join(" ");
246
247 let args = self
249 .args
250 .iter()
251 .map(|arg| arg.to_string_lossy().to_string())
252 .collect::<Vec<String>>()
253 .join(" ");
254
255 write!(f, "{} {} {}", envs, self.program.to_string_lossy(), args)
256 }
257}
258
259impl error::Error for Error {}
260
261impl fmt::Debug for Error {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
263 <Error as fmt::Display>::fmt(self, f)
265 }
266}
267
268impl fmt::Display for Error {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
270 match *self {
271 Error::EnvNoPkgConfig(ref name) => write!(f, "Aborted because {} is set", name),
272 Error::CrossCompilation => f.write_str(
273 "pkg-config has not been configured to support cross-compilation.\n\
274 \n\
275 Install a sysroot for the target platform and configure it via\n\
276 PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\n\
277 cross-compiling wrapper for pkg-config and set it via\n\
278 PKG_CONFIG environment variable.",
279 ),
280 Error::Command {
281 ref command,
282 ref cause,
283 } => {
284 match cause.kind() {
285 io::ErrorKind::NotFound => {
286 let crate_name =
287 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "sys".to_owned());
288 let instructions = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
289 "Try `brew install pkg-config` if you have Homebrew.\n"
290 } else if cfg!(unix) {
291 "Try `apt install pkg-config`, or `yum install pkg-config`,\n\
292 or `pkg install pkg-config`, or `apk add pkgconfig` \
293 depending on your distribution.\n"
294 } else {
295 "" };
297 write!(f, "Could not run `{command}`\n\
298 The pkg-config command could not be found.\n\
299 \n\
300 Most likely, you need to install a pkg-config package for your OS.\n\
301 {instructions}\
302 \n\
303 If you've already installed it, ensure the pkg-config command is one of the\n\
304 directories in the PATH environment variable.\n\
305 \n\
306 If you did not expect this build to link to a pre-installed system library,\n\
307 then check documentation of the {crate_name} crate for an option to\n\
308 build the library from source, or disable features or dependencies\n\
309 that require pkg-config.", command = command, instructions = instructions, crate_name = crate_name)
310 }
311 _ => write!(f, "Failed to run command `{}`, because: {}", command, cause),
312 }
313 }
314 Error::ProbeFailure {
315 ref name,
316 ref command,
317 ref output,
318 } => {
319 let crate_name =
320 env::var("CARGO_PKG_NAME").unwrap_or(String::from("<NO CRATE NAME>"));
321
322 writeln!(f, "")?;
323
324 writeln!(
326 f,
327 "pkg-config {}",
328 match output.status.code() {
329 Some(code) => format!("exited with status code {}", code),
330 None => "was terminated by signal".to_string(),
331 }
332 )?;
333
334 writeln!(f, "> {}\n", command)?;
336
337 writeln!(
339 f,
340 "The system library `{}` required by crate `{}` was not found.",
341 name, crate_name
342 )?;
343 writeln!(
344 f,
345 "The file `{}.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.",
346 name
347 )?;
348
349 if let Some(_code) = output.status.code() {
351 let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
354
355 let mut search_data = None;
357 for location in search_locations.iter() {
358 if let Ok(search_path) = env::var(location) {
359 search_data = Some((location, search_path));
360 break;
361 }
362 }
363
364 let hint = if let Some((search_location, search_path)) = search_data {
366 writeln!(
367 f,
368 "{} contains the following:\n{}",
369 search_location,
370 search_path
371 .split(':')
372 .map(|path| format!(" - {}", path))
373 .collect::<Vec<String>>()
374 .join("\n"),
375 )?;
376
377 format!("you may need to install a package such as {name}, {name}-dev or {name}-devel.", name=name)
378 } else {
379 writeln!(f, "The PKG_CONFIG_PATH environment variable is not set.")?;
381
382 format!(
383 "if you have installed the library, try setting PKG_CONFIG_PATH to the directory containing `{}.pc`.",
384 name
385 )
386 };
387
388 writeln!(f, "\nHINT: {}", hint)?;
390 }
391
392 Ok(())
393 }
394 Error::Failure {
395 ref command,
396 ref output,
397 } => {
398 write!(
399 f,
400 "`{}` did not exit successfully: {}",
401 command, output.status
402 )?;
403 format_output(output, f)
404 }
405 Error::__Nonexhaustive => panic!(),
406 }
407 }
408}
409
410fn format_output(output: &Output, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 let stdout = String::from_utf8_lossy(&output.stdout);
412 if !stdout.is_empty() {
413 write!(f, "\n--- stdout\n{}", stdout)?;
414 }
415 let stderr = String::from_utf8_lossy(&output.stderr);
416 if !stderr.is_empty() {
417 write!(f, "\n--- stderr\n{}", stderr)?;
418 }
419 Ok(())
420}
421
422#[doc(hidden)]
424pub fn find_library(name: &str) -> Result<Library, String> {
425 probe_library(name).map_err(|e| e.to_string())
426}
427
428pub fn probe_library(name: &str) -> Result<Library, Error> {
430 Config::new().probe(name)
431}
432
433#[doc(hidden)]
434#[deprecated(note = "use config.target_supported() instance method instead")]
435pub fn target_supported() -> bool {
436 Config::new().target_supported()
437}
438
439pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> {
447 let arg = format!("--variable={}", variable);
448 let cfg = Config::new();
449 let out = cfg.run(package, &[&arg])?;
450 Ok(str::from_utf8(&out).unwrap().trim_end().to_owned())
451}
452
453impl Config {
454 pub fn new() -> Config {
457 Config {
458 statik: None,
459 min_version: Bound::Unbounded,
460 max_version: Bound::Unbounded,
461 extra_args: vec![],
462 print_system_cflags: true,
463 print_system_libs: true,
464 cargo_metadata: true,
465 env_metadata: true,
466 }
467 }
468
469 pub fn statik(&mut self, statik: bool) -> &mut Config {
474 self.statik = Some(statik);
475 self
476 }
477
478 pub fn atleast_version(&mut self, vers: &str) -> &mut Config {
480 self.min_version = Bound::Included(vers.to_string());
481 self.max_version = Bound::Unbounded;
482 self
483 }
484
485 pub fn exactly_version(&mut self, vers: &str) -> &mut Config {
487 self.min_version = Bound::Included(vers.to_string());
488 self.max_version = Bound::Included(vers.to_string());
489 self
490 }
491
492 pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config
494 where
495 R: RangeBounds<&'a str>,
496 {
497 self.min_version = match range.start_bound() {
498 Bound::Included(vers) => Bound::Included(vers.to_string()),
499 Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
500 Bound::Unbounded => Bound::Unbounded,
501 };
502 self.max_version = match range.end_bound() {
503 Bound::Included(vers) => Bound::Included(vers.to_string()),
504 Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
505 Bound::Unbounded => Bound::Unbounded,
506 };
507 self
508 }
509
510 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config {
514 self.extra_args.push(arg.as_ref().to_os_string());
515 self
516 }
517
518 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
521 self.cargo_metadata = cargo_metadata;
522 self
523 }
524
525 pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
529 self.env_metadata = env_metadata;
530 self
531 }
532
533 pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
538 self.print_system_libs = print;
539 self
540 }
541
542 pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
547 self.print_system_cflags = print;
548 self
549 }
550
551 #[doc(hidden)]
553 pub fn find(&self, name: &str) -> Result<Library, String> {
554 self.probe(name).map_err(|e| e.to_string())
555 }
556
557 pub fn probe(&self, name: &str) -> Result<Library, Error> {
562 let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name));
563 if self.env_var_os(&abort_var_name).is_some() {
564 return Err(Error::EnvNoPkgConfig(abort_var_name));
565 } else if !self.target_supported() {
566 return Err(Error::CrossCompilation);
567 }
568
569 let mut library = Library::new();
570
571 let output = self
572 .run(name, &["--libs", "--cflags"])
573 .map_err(|e| match e {
574 Error::Failure { command, output } => Error::ProbeFailure {
575 name: name.to_owned(),
576 command,
577 output,
578 },
579 other => other,
580 })?;
581 library.parse_libs_cflags(name, &output, self);
582
583 let output = self.run(name, &["--modversion"])?;
584 library.parse_modversion(str::from_utf8(&output).unwrap());
585
586 Ok(library)
587 }
588
589 pub fn target_supported(&self) -> bool {
591 let target = env::var_os("TARGET").unwrap_or_default();
592 let host = env::var_os("HOST").unwrap_or_default();
593
594 if host == target {
597 return true;
598 }
599
600 match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
603 Some(ref val) if val == "0" => false,
605 Some(_) => true,
606 None => {
607 self.targeted_env_var("PKG_CONFIG").is_some()
610 || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
611 }
612 }
613 }
614
615 #[doc(hidden)]
617 pub fn get_variable(package: &str, variable: &str) -> Result<String, String> {
618 get_variable(package, variable).map_err(|e| e.to_string())
619 }
620
621 fn targeted_env_var(&self, var_base: &str) -> Option<OsString> {
622 match (env::var("TARGET"), env::var("HOST")) {
623 (Ok(target), Ok(host)) => {
624 let kind = if host == target { "HOST" } else { "TARGET" };
625 let target_u = target.replace('-', "_");
626
627 self.env_var_os(&format!("{}_{}", var_base, target))
628 .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u)))
629 .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base)))
630 .or_else(|| self.env_var_os(var_base))
631 }
632 (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => {
633 self.env_var_os(var_base)
634 }
635 (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => {
636 panic!(
637 "HOST or TARGET environment variable is not valid unicode: {:?}",
638 s
639 )
640 }
641 }
642 }
643
644 fn env_var_os(&self, name: &str) -> Option<OsString> {
645 if self.env_metadata {
646 println!("cargo:rerun-if-env-changed={}", name);
647 }
648 env::var_os(name)
649 }
650
651 fn is_static(&self, name: &str) -> bool {
652 self.statik.unwrap_or_else(|| self.infer_static(name))
653 }
654
655 fn run(&self, name: &str, args: &[&str]) -> Result<Vec<u8>, Error> {
656 let pkg_config_exe = self.targeted_env_var("PKG_CONFIG");
657 let fallback_exe = if pkg_config_exe.is_none() {
658 Some(OsString::from("pkgconf"))
659 } else {
660 None
661 };
662 let exe = pkg_config_exe.unwrap_or_else(|| OsString::from("pkg-config"));
663
664 let mut cmd = self.command(exe, name, args);
665
666 match cmd.output().or_else(|e| {
667 if let Some(exe) = fallback_exe {
668 self.command(exe, name, args).output()
669 } else {
670 Err(e)
671 }
672 }) {
673 Ok(output) => {
674 if output.status.success() {
675 Ok(output.stdout)
676 } else {
677 Err(Error::Failure {
678 command: format!("{}", cmd),
679 output,
680 })
681 }
682 }
683 Err(cause) => Err(Error::Command {
684 command: format!("{}", cmd),
685 cause,
686 }),
687 }
688 }
689
690 fn command(&self, exe: OsString, name: &str, args: &[&str]) -> WrappedCommand {
691 let mut cmd = WrappedCommand::new(exe);
692 if self.is_static(name) {
693 cmd.arg("--static");
694 }
695 cmd.args(args).args(&self.extra_args);
696
697 if let Some(value) = self.targeted_env_var("PKG_CONFIG_PATH") {
698 cmd.env("PKG_CONFIG_PATH", value);
699 }
700 if let Some(value) = self.targeted_env_var("PKG_CONFIG_LIBDIR") {
701 cmd.env("PKG_CONFIG_LIBDIR", value);
702 }
703 if let Some(value) = self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR") {
704 cmd.env("PKG_CONFIG_SYSROOT_DIR", value);
705 }
706 if self.print_system_libs {
707 cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1");
708 }
709 if self.print_system_cflags {
710 cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1");
711 }
712 cmd.arg(name);
713 match self.min_version {
714 Bound::Included(ref version) => {
715 cmd.arg(&format!("{} >= {}", name, version));
716 }
717 Bound::Excluded(ref version) => {
718 cmd.arg(&format!("{} > {}", name, version));
719 }
720 _ => (),
721 }
722 match self.max_version {
723 Bound::Included(ref version) => {
724 cmd.arg(&format!("{} <= {}", name, version));
725 }
726 Bound::Excluded(ref version) => {
727 cmd.arg(&format!("{} < {}", name, version));
728 }
729 _ => (),
730 }
731 cmd
732 }
733
734 fn print_metadata(&self, s: &str) {
735 if self.cargo_metadata {
736 println!("cargo:{}", s);
737 }
738 }
739
740 fn infer_static(&self, name: &str) -> bool {
741 let name = envify(name);
742 if self.env_var_os(&format!("{}_STATIC", name)).is_some() {
743 true
744 } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() {
745 false
746 } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() {
747 true
748 } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() {
749 false
750 } else {
751 false
752 }
753 }
754}
755
756impl Default for Config {
758 fn default() -> Config {
759 Config {
760 statik: None,
761 min_version: Bound::Unbounded,
762 max_version: Bound::Unbounded,
763 extra_args: vec![],
764 print_system_cflags: false,
765 print_system_libs: false,
766 cargo_metadata: false,
767 env_metadata: false,
768 }
769 }
770}
771
772impl Library {
773 fn new() -> Library {
774 Library {
775 libs: Vec::new(),
776 link_paths: Vec::new(),
777 link_files: Vec::new(),
778 include_paths: Vec::new(),
779 ld_args: Vec::new(),
780 frameworks: Vec::new(),
781 framework_paths: Vec::new(),
782 defines: HashMap::new(),
783 version: String::new(),
784 _priv: (),
785 }
786 }
787
788 fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> {
791 fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> {
792 for suffix in suffixes {
793 if filename.ends_with(suffix) {
794 return Some(&filename[..filename.len() - suffix.len()]);
795 }
796 }
797 None
798 }
799
800 let prefix = "lib";
801 if target.contains("windows") {
802 if target.contains("gnu") && filename.starts_with(prefix) {
803 let filename = &filename[prefix.len()..];
813 return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
814 } else {
815 return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
833 }
834 } else if target.contains("apple") {
835 if filename.starts_with(prefix) {
836 let filename = &filename[prefix.len()..];
837 return test_suffixes(filename, &[".a", ".so", ".dylib"]);
838 }
839 return None;
840 } else {
841 if filename.starts_with(prefix) {
842 let filename = &filename[prefix.len()..];
843 return test_suffixes(filename, &[".a", ".so"]);
844 }
845 return None;
846 }
847 }
848
849 fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) {
850 let target = env::var("TARGET");
851 let is_msvc = target
852 .as_ref()
853 .map(|target| target.contains("msvc"))
854 .unwrap_or(false);
855
856 let system_roots = if cfg!(target_os = "macos") {
857 vec![PathBuf::from("/Library"), PathBuf::from("/System")]
858 } else {
859 let sysroot = config
860 .env_var_os("PKG_CONFIG_SYSROOT_DIR")
861 .or_else(|| config.env_var_os("SYSROOT"))
862 .map(PathBuf::from);
863
864 if cfg!(target_os = "windows") {
865 if let Some(sysroot) = sysroot {
866 vec![sysroot]
867 } else {
868 vec![]
869 }
870 } else {
871 vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))]
872 }
873 };
874
875 let mut dirs = Vec::new();
876 let statik = config.is_static(name);
877
878 let words = split_flags(output);
879
880 let parts = words
882 .iter()
883 .filter(|l| l.len() > 2)
884 .map(|arg| (&arg[0..2], &arg[2..]));
885 for (flag, val) in parts {
886 match flag {
887 "-L" => {
888 let meta = format!("rustc-link-search=native={}", val);
889 config.print_metadata(&meta);
890 dirs.push(PathBuf::from(val));
891 self.link_paths.push(PathBuf::from(val));
892 }
893 "-F" => {
894 let meta = format!("rustc-link-search=framework={}", val);
895 config.print_metadata(&meta);
896 self.framework_paths.push(PathBuf::from(val));
897 }
898 "-I" => {
899 self.include_paths.push(PathBuf::from(val));
900 }
901 "-l" => {
902 if is_msvc && ["m", "c", "pthread"].contains(&val) {
904 continue;
905 }
906
907 if val.starts_with(':') {
908 let meta = format!("rustc-link-arg={}{}", flag, val);
910 config.print_metadata(&meta);
911 } else if statik && is_static_available(val, &system_roots, &dirs) {
912 let meta = format!("rustc-link-lib=static={}", val);
913 config.print_metadata(&meta);
914 } else {
915 let meta = format!("rustc-link-lib={}", val);
916 config.print_metadata(&meta);
917 }
918
919 self.libs.push(val.to_string());
920 }
921 "-D" => {
922 let mut iter = val.split('=');
923 self.defines.insert(
924 iter.next().unwrap().to_owned(),
925 iter.next().map(|s| s.to_owned()),
926 );
927 }
928 "-u" => {
929 let meta = format!("rustc-link-arg=-Wl,-u,{}", val);
930 config.print_metadata(&meta);
931 }
932 _ => {}
933 }
934 }
935
936 let mut iter = words.iter().flat_map(|arg| {
938 if arg.starts_with("-Wl,") {
939 arg[4..].split(',').collect()
940 } else {
941 vec![arg.as_ref()]
942 }
943 });
944 while let Some(part) = iter.next() {
945 match part {
946 "-framework" => {
947 if let Some(lib) = iter.next() {
948 let meta = format!("rustc-link-lib=framework={}", lib);
949 config.print_metadata(&meta);
950 self.frameworks.push(lib.to_string());
951 }
952 }
953 "-isystem" | "-iquote" | "-idirafter" => {
954 if let Some(inc) = iter.next() {
955 self.include_paths.push(PathBuf::from(inc));
956 }
957 }
958 "-undefined" | "--undefined" => {
959 if let Some(symbol) = iter.next() {
960 let meta = format!("rustc-link-arg=-Wl,{},{}", part, symbol);
961 config.print_metadata(&meta);
962 }
963 }
964 _ => {
965 let path = std::path::Path::new(part);
966 if path.is_file() {
967 if let (Some(dir), Some(file_name), Ok(target)) =
972 (path.parent(), path.file_name(), &target)
973 {
974 match Self::extract_lib_from_filename(
975 target,
976 &file_name.to_string_lossy(),
977 ) {
978 Some(lib_basename) => {
979 let link_search =
980 format!("rustc-link-search={}", dir.display());
981 config.print_metadata(&link_search);
982
983 let link_lib = format!("rustc-link-lib={}", lib_basename);
984 config.print_metadata(&link_lib);
985 self.link_files.push(PathBuf::from(path));
986 }
987 None => {
988 println!("cargo:warning=File path {} found in pkg-config file for {}, but could not extract library base name to pass to linker command line", path.display(), name);
989 }
990 }
991 }
992 }
993 }
994 }
995 }
996
997 let linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,"));
998 for option in linker_options {
999 let mut pop = false;
1000 let mut ld_option = vec![];
1001 for subopt in option[4..].split(',') {
1002 if pop {
1003 pop = false;
1004 continue;
1005 }
1006
1007 if subopt == "-framework" {
1008 pop = true;
1009 continue;
1010 }
1011
1012 ld_option.push(subopt);
1013 }
1014
1015 let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(","));
1016 config.print_metadata(&meta);
1017
1018 self.ld_args
1019 .push(ld_option.into_iter().map(String::from).collect());
1020 }
1021 }
1022
1023 fn parse_modversion(&mut self, output: &str) {
1024 self.version.push_str(output.lines().next().unwrap().trim());
1025 }
1026}
1027
1028fn envify(name: &str) -> String {
1029 name.chars()
1030 .map(|c| c.to_ascii_uppercase())
1031 .map(|c| if c == '-' { '_' } else { c })
1032 .collect()
1033}
1034
1035fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool {
1037 let libnames = {
1038 let mut names = vec![format!("lib{}.a", name)];
1039
1040 if cfg!(target_os = "windows") {
1041 names.push(format!("{}.lib", name));
1042 }
1043
1044 names
1045 };
1046
1047 dirs.iter().any(|dir| {
1048 let library_exists = libnames.iter().any(|libname| dir.join(&libname).exists());
1049 library_exists && !system_roots.iter().any(|sys| dir.starts_with(sys))
1050 })
1051}
1052
1053fn split_flags(output: &[u8]) -> Vec<String> {
1061 let mut word = Vec::new();
1062 let mut words = Vec::new();
1063 let mut escaped = false;
1064
1065 for &b in output {
1066 match b {
1067 _ if escaped => {
1068 escaped = false;
1069 word.push(b);
1070 }
1071 b'\\' => escaped = true,
1072 b'\t' | b'\n' | b'\r' | b' ' => {
1073 if !word.is_empty() {
1074 words.push(String::from_utf8(word).unwrap());
1075 word = Vec::new();
1076 }
1077 }
1078 _ => word.push(b),
1079 }
1080 }
1081
1082 if !word.is_empty() {
1083 words.push(String::from_utf8(word).unwrap());
1084 }
1085
1086 words
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091 use super::*;
1092
1093 #[test]
1094 #[cfg(target_os = "macos")]
1095 fn system_library_mac_test() {
1096 use std::path::Path;
1097
1098 let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")];
1099
1100 assert!(!is_static_available(
1101 "PluginManager",
1102 &system_roots,
1103 &[PathBuf::from("/Library/Frameworks")]
1104 ));
1105 assert!(!is_static_available(
1106 "python2.7",
1107 &system_roots,
1108 &[PathBuf::from(
1109 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config"
1110 )]
1111 ));
1112 assert!(!is_static_available(
1113 "ffi_convenience",
1114 &system_roots,
1115 &[PathBuf::from(
1116 "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs"
1117 )]
1118 ));
1119
1120 if Path::new("/usr/local/lib/libpng16.a").exists() {
1122 assert!(is_static_available(
1123 "png16",
1124 &system_roots,
1125 &[PathBuf::from("/usr/local/lib")]
1126 ));
1127
1128 let libpng = Config::new()
1129 .range_version("1".."99")
1130 .probe("libpng16")
1131 .unwrap();
1132 assert!(libpng.version.find('\n').is_none());
1133 }
1134 }
1135
1136 #[test]
1137 #[cfg(target_os = "linux")]
1138 fn system_library_linux_test() {
1139 assert!(!is_static_available(
1140 "util",
1141 &[PathBuf::from("/usr")],
1142 &[PathBuf::from("/usr/lib/x86_64-linux-gnu")]
1143 ));
1144 assert!(!is_static_available(
1145 "dialog",
1146 &[PathBuf::from("/usr")],
1147 &[PathBuf::from("/usr/lib")]
1148 ));
1149 }
1150
1151 fn test_library_filename(target: &str, filename: &str) {
1152 assert_eq!(
1153 Library::extract_lib_from_filename(target, filename),
1154 Some("foo")
1155 );
1156 }
1157
1158 #[test]
1159 fn link_filename_linux() {
1160 let target = "x86_64-unknown-linux-gnu";
1161 test_library_filename(target, "libfoo.a");
1162 test_library_filename(target, "libfoo.so");
1163 }
1164
1165 #[test]
1166 fn link_filename_apple() {
1167 let target = "x86_64-apple-darwin";
1168 test_library_filename(target, "libfoo.a");
1169 test_library_filename(target, "libfoo.so");
1170 test_library_filename(target, "libfoo.dylib");
1171 }
1172
1173 #[test]
1174 fn link_filename_msvc() {
1175 let target = "x86_64-pc-windows-msvc";
1176 test_library_filename(target, "foo.lib");
1178 }
1179
1180 #[test]
1181 fn link_filename_mingw() {
1182 let target = "x86_64-pc-windows-gnu";
1183 test_library_filename(target, "foo.lib");
1184 test_library_filename(target, "libfoo.a");
1185 test_library_filename(target, "foo.dll");
1186 test_library_filename(target, "foo.dll.a");
1187 }
1188}