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
230fn quote_if_needed(arg: String) -> String {
238 if arg.contains(' ') {
239 format!("'{}'", arg)
240 } else {
241 arg
242 }
243}
244
245impl Display for WrappedCommand {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 let envs = self
256 .env_vars
257 .iter()
258 .map(|(env, arg)| format!("{}={}", env.to_string_lossy(), arg.to_string_lossy()))
259 .collect::<Vec<String>>()
260 .join(" ");
261
262 let args = self
264 .args
265 .iter()
266 .map(|arg| quote_if_needed(arg.to_string_lossy().to_string()))
267 .collect::<Vec<String>>()
268 .join(" ");
269
270 write!(f, "{} {} {}", envs, self.program.to_string_lossy(), args)
271 }
272}
273
274impl error::Error for Error {}
275
276impl fmt::Debug for Error {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
278 <Error as fmt::Display>::fmt(self, f)
280 }
281}
282
283impl fmt::Display for Error {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
285 match *self {
286 Error::EnvNoPkgConfig(ref name) => write!(f, "Aborted because {} is set", name),
287 Error::CrossCompilation => f.write_str(
288 "pkg-config has not been configured to support cross-compilation.\n\
289 \n\
290 Install a sysroot for the target platform and configure it via\n\
291 PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\n\
292 cross-compiling wrapper for pkg-config and set it via\n\
293 PKG_CONFIG environment variable.",
294 ),
295 Error::Command {
296 ref command,
297 ref cause,
298 } => {
299 match cause.kind() {
300 io::ErrorKind::NotFound => {
301 let crate_name =
302 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "sys".to_owned());
303 let instructions = if cfg!(target_os = "macos") {
304 "Try `brew install pkgconf` if you have Homebrew.\n"
305 } else if cfg!(target_os = "ios") {
306 "" } else if cfg!(unix) {
308 "Try `apt install pkg-config`, or `yum install pkg-config`, or `brew install pkgconf`\n\
309 or `pkg install pkg-config`, or `apk add pkgconfig` \
310 depending on your distribution.\n"
311 } else {
312 "" };
314 write!(f, "Could not run `{command}`\n\
315 The pkg-config command could not be found.\n\
316 \n\
317 Most likely, you need to install a pkg-config package for your OS.\n\
318 {instructions}\
319 \n\
320 If you've already installed it, ensure the pkg-config command is one of the\n\
321 directories in the PATH environment variable.\n\
322 \n\
323 If you did not expect this build to link to a pre-installed system library,\n\
324 then check documentation of the {crate_name} crate for an option to\n\
325 build the library from source, or disable features or dependencies\n\
326 that require pkg-config.", command = command, instructions = instructions, crate_name = crate_name)
327 }
328 _ => write!(f, "Failed to run command `{}`, because: {}", command, cause),
329 }
330 }
331 Error::ProbeFailure {
332 ref name,
333 ref command,
334 ref output,
335 } => {
336 let crate_name =
337 env::var("CARGO_PKG_NAME").unwrap_or(String::from("<NO CRATE NAME>"));
338
339 writeln!(f, "")?;
340
341 writeln!(
343 f,
344 "pkg-config {}",
345 match output.status.code() {
346 Some(code) => format!("exited with status code {}", code),
347 None => "was terminated by signal".to_string(),
348 }
349 )?;
350
351 writeln!(f, "> {}\n", command)?;
353
354 writeln!(
356 f,
357 "The system library `{}` required by crate `{}` was not found.",
358 name, crate_name
359 )?;
360 writeln!(
361 f,
362 "The file `{}.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.",
363 name
364 )?;
365
366 if let Some(_code) = output.status.code() {
368 let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
371
372 let mut search_data = None;
374 for location in search_locations.iter() {
375 if let Ok(search_path) = env::var(location) {
376 search_data = Some((location, search_path));
377 break;
378 }
379 }
380
381 let hint = if let Some((search_location, search_path)) = search_data {
383 writeln!(
384 f,
385 "{} contains the following:\n{}",
386 search_location,
387 search_path
388 .split(':')
389 .map(|path| format!(" - {}", path))
390 .collect::<Vec<String>>()
391 .join("\n"),
392 )?;
393
394 format!("you may need to install a package such as {name}, {name}-dev or {name}-devel.", name=name)
395 } else {
396 writeln!(f, "The PKG_CONFIG_PATH environment variable is not set.")?;
398
399 format!(
400 "if you have installed the library, try setting PKG_CONFIG_PATH to the directory containing `{}.pc`.",
401 name
402 )
403 };
404
405 writeln!(f, "\nHINT: {}", hint)?;
407 }
408
409 Ok(())
410 }
411 Error::Failure {
412 ref command,
413 ref output,
414 } => {
415 write!(
416 f,
417 "`{}` did not exit successfully: {}",
418 command, output.status
419 )?;
420 format_output(output, f)
421 }
422 Error::__Nonexhaustive => panic!(),
423 }
424 }
425}
426
427fn format_output(output: &Output, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428 let stdout = String::from_utf8_lossy(&output.stdout);
429 if !stdout.is_empty() {
430 write!(f, "\n--- stdout\n{}", stdout)?;
431 }
432 let stderr = String::from_utf8_lossy(&output.stderr);
433 if !stderr.is_empty() {
434 write!(f, "\n--- stderr\n{}", stderr)?;
435 }
436 Ok(())
437}
438
439#[doc(hidden)]
441pub fn find_library(name: &str) -> Result<Library, String> {
442 probe_library(name).map_err(|e| e.to_string())
443}
444
445pub fn probe_library(name: &str) -> Result<Library, Error> {
447 Config::new().probe(name)
448}
449
450#[doc(hidden)]
451#[deprecated(note = "use config.target_supported() instance method instead")]
452pub fn target_supported() -> bool {
453 Config::new().target_supported()
454}
455
456pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> {
464 let arg = format!("--variable={}", variable);
465 let cfg = Config::new();
466 let out = cfg.run(package, &[&arg])?;
467 Ok(str::from_utf8(&out).unwrap().trim_end().to_owned())
468}
469
470impl Config {
471 pub fn new() -> Config {
474 Config {
475 statik: None,
476 min_version: Bound::Unbounded,
477 max_version: Bound::Unbounded,
478 extra_args: vec![],
479 print_system_cflags: true,
480 print_system_libs: true,
481 cargo_metadata: true,
482 env_metadata: true,
483 }
484 }
485
486 pub fn statik(&mut self, statik: bool) -> &mut Config {
491 self.statik = Some(statik);
492 self
493 }
494
495 pub fn atleast_version(&mut self, vers: &str) -> &mut Config {
497 self.min_version = Bound::Included(vers.to_string());
498 self.max_version = Bound::Unbounded;
499 self
500 }
501
502 pub fn exactly_version(&mut self, vers: &str) -> &mut Config {
504 self.min_version = Bound::Included(vers.to_string());
505 self.max_version = Bound::Included(vers.to_string());
506 self
507 }
508
509 pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config
511 where
512 R: RangeBounds<&'a str>,
513 {
514 self.min_version = match range.start_bound() {
515 Bound::Included(vers) => Bound::Included(vers.to_string()),
516 Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
517 Bound::Unbounded => Bound::Unbounded,
518 };
519 self.max_version = match range.end_bound() {
520 Bound::Included(vers) => Bound::Included(vers.to_string()),
521 Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
522 Bound::Unbounded => Bound::Unbounded,
523 };
524 self
525 }
526
527 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config {
531 self.extra_args.push(arg.as_ref().to_os_string());
532 self
533 }
534
535 pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
538 self.cargo_metadata = cargo_metadata;
539 self
540 }
541
542 pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
546 self.env_metadata = env_metadata;
547 self
548 }
549
550 pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
555 self.print_system_libs = print;
556 self
557 }
558
559 pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
564 self.print_system_cflags = print;
565 self
566 }
567
568 #[doc(hidden)]
570 pub fn find(&self, name: &str) -> Result<Library, String> {
571 self.probe(name).map_err(|e| e.to_string())
572 }
573
574 pub fn probe(&self, name: &str) -> Result<Library, Error> {
579 let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name));
580 if self.env_var_os(&abort_var_name).is_some() {
581 return Err(Error::EnvNoPkgConfig(abort_var_name));
582 } else if !self.target_supported() {
583 return Err(Error::CrossCompilation);
584 }
585
586 let mut library = Library::new();
587
588 let output = self
589 .run(name, &["--libs", "--cflags"])
590 .map_err(|e| match e {
591 Error::Failure { command, output } => Error::ProbeFailure {
592 name: name.to_owned(),
593 command,
594 output,
595 },
596 other => other,
597 })?;
598 library.parse_libs_cflags(name, &output, self);
599
600 let output = self.run(name, &["--modversion"])?;
601 library.parse_modversion(str::from_utf8(&output).unwrap());
602
603 Ok(library)
604 }
605
606 pub fn target_supported(&self) -> bool {
608 let target = env::var_os("TARGET").unwrap_or_default();
609 let host = env::var_os("HOST").unwrap_or_default();
610
611 if host == target {
614 return true;
615 }
616
617 match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
620 Some(ref val) if val == "0" => false,
622 Some(_) => true,
623 None => {
624 self.targeted_env_var("PKG_CONFIG").is_some()
627 || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
628 }
629 }
630 }
631
632 #[doc(hidden)]
634 pub fn get_variable(package: &str, variable: &str) -> Result<String, String> {
635 get_variable(package, variable).map_err(|e| e.to_string())
636 }
637
638 fn targeted_env_var(&self, var_base: &str) -> Option<OsString> {
639 match (env::var("TARGET"), env::var("HOST")) {
640 (Ok(target), Ok(host)) => {
641 let kind = if host == target { "HOST" } else { "TARGET" };
642 let target_u = target.replace('-', "_");
643
644 self.env_var_os(&format!("{}_{}", var_base, target))
645 .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u)))
646 .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base)))
647 .or_else(|| self.env_var_os(var_base))
648 }
649 (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => {
650 self.env_var_os(var_base)
651 }
652 (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => {
653 panic!(
654 "HOST or TARGET environment variable is not valid unicode: {:?}",
655 s
656 )
657 }
658 }
659 }
660
661 fn env_var_os(&self, name: &str) -> Option<OsString> {
662 if self.env_metadata {
663 println!("cargo:rerun-if-env-changed={}", name);
664 }
665 env::var_os(name)
666 }
667
668 fn is_static(&self, name: &str) -> bool {
669 self.statik.unwrap_or_else(|| self.infer_static(name))
670 }
671
672 fn run(&self, name: &str, args: &[&str]) -> Result<Vec<u8>, Error> {
673 let pkg_config_exe = self.targeted_env_var("PKG_CONFIG");
674 let fallback_exe = if pkg_config_exe.is_none() {
675 Some(OsString::from("pkgconf"))
676 } else {
677 None
678 };
679 let exe = pkg_config_exe.unwrap_or_else(|| OsString::from("pkg-config"));
680
681 let mut cmd = self.command(exe, name, args);
682
683 match cmd.output().or_else(|e| {
684 if let Some(exe) = fallback_exe {
685 self.command(exe, name, args).output()
686 } else {
687 Err(e)
688 }
689 }) {
690 Ok(output) => {
691 if output.status.success() {
692 Ok(output.stdout)
693 } else {
694 Err(Error::Failure {
695 command: format!("{}", cmd),
696 output,
697 })
698 }
699 }
700 Err(cause) => Err(Error::Command {
701 command: format!("{}", cmd),
702 cause,
703 }),
704 }
705 }
706
707 fn command(&self, exe: OsString, name: &str, args: &[&str]) -> WrappedCommand {
708 let mut cmd = WrappedCommand::new(exe);
709 if self.is_static(name) {
710 cmd.arg("--static");
711 }
712 cmd.args(args).args(&self.extra_args);
713
714 if let Some(value) = self.targeted_env_var("PKG_CONFIG_PATH") {
715 cmd.env("PKG_CONFIG_PATH", value);
716 }
717 if let Some(value) = self.targeted_env_var("PKG_CONFIG_LIBDIR") {
718 cmd.env("PKG_CONFIG_LIBDIR", value);
719 }
720 if let Some(value) = self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR") {
721 cmd.env("PKG_CONFIG_SYSROOT_DIR", value);
722 }
723 if self.print_system_libs {
724 cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1");
725 }
726 if self.print_system_cflags {
727 cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1");
728 }
729 cmd.arg(name);
730 match self.min_version {
731 Bound::Included(ref version) => {
732 cmd.arg(&format!("{} >= {}", name, version));
733 }
734 Bound::Excluded(ref version) => {
735 cmd.arg(&format!("{} > {}", name, version));
736 }
737 _ => (),
738 }
739 match self.max_version {
740 Bound::Included(ref version) => {
741 cmd.arg(&format!("{} <= {}", name, version));
742 }
743 Bound::Excluded(ref version) => {
744 cmd.arg(&format!("{} < {}", name, version));
745 }
746 _ => (),
747 }
748 cmd
749 }
750
751 fn print_metadata(&self, s: &str) {
752 if self.cargo_metadata {
753 println!("cargo:{}", s);
754 }
755 }
756
757 fn infer_static(&self, name: &str) -> bool {
758 let name = envify(name);
759 if self.env_var_os(&format!("{}_STATIC", name)).is_some() {
760 true
761 } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() {
762 false
763 } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() {
764 true
765 } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() {
766 false
767 } else {
768 false
769 }
770 }
771}
772
773impl Default for Config {
775 fn default() -> Config {
776 Config {
777 statik: None,
778 min_version: Bound::Unbounded,
779 max_version: Bound::Unbounded,
780 extra_args: vec![],
781 print_system_cflags: false,
782 print_system_libs: false,
783 cargo_metadata: false,
784 env_metadata: false,
785 }
786 }
787}
788
789impl Library {
790 fn new() -> Library {
791 Library {
792 libs: Vec::new(),
793 link_paths: Vec::new(),
794 link_files: Vec::new(),
795 include_paths: Vec::new(),
796 ld_args: Vec::new(),
797 frameworks: Vec::new(),
798 framework_paths: Vec::new(),
799 defines: HashMap::new(),
800 version: String::new(),
801 _priv: (),
802 }
803 }
804
805 fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> {
808 fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> {
809 for suffix in suffixes {
810 if filename.ends_with(suffix) {
811 return Some(&filename[..filename.len() - suffix.len()]);
812 }
813 }
814 None
815 }
816
817 let prefix = "lib";
818 if target.contains("windows") {
819 if target.contains("gnu") && filename.starts_with(prefix) {
820 let filename = &filename[prefix.len()..];
830 return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
831 } else {
832 return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
850 }
851 } else if target.contains("apple") {
852 if filename.starts_with(prefix) {
853 let filename = &filename[prefix.len()..];
854 return test_suffixes(filename, &[".a", ".so", ".dylib"]);
855 }
856 return None;
857 } else {
858 if filename.starts_with(prefix) {
859 let filename = &filename[prefix.len()..];
860 return test_suffixes(filename, &[".a", ".so"]);
861 }
862 return None;
863 }
864 }
865
866 fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) {
867 let target = env::var("TARGET");
868 let is_msvc = target
869 .as_ref()
870 .map(|target| target.contains("msvc"))
871 .unwrap_or(false);
872
873 let system_roots = if cfg!(target_os = "macos") {
874 vec![PathBuf::from("/Library"), PathBuf::from("/System")]
875 } else {
876 let sysroot = config
877 .env_var_os("PKG_CONFIG_SYSROOT_DIR")
878 .or_else(|| config.env_var_os("SYSROOT"))
879 .map(PathBuf::from);
880
881 if cfg!(target_os = "windows") {
882 if let Some(sysroot) = sysroot {
883 vec![sysroot]
884 } else {
885 vec![]
886 }
887 } else {
888 vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))]
889 }
890 };
891
892 let mut dirs = Vec::new();
893 let statik = config.is_static(name);
894
895 let words = split_flags(output);
896
897 let parts = words
899 .iter()
900 .filter(|l| l.len() > 2)
901 .map(|arg| (&arg[0..2], &arg[2..]));
902 for (flag, val) in parts {
903 match flag {
904 "-L" => {
905 let meta = format!("rustc-link-search=native={}", val);
906 config.print_metadata(&meta);
907 dirs.push(PathBuf::from(val));
908 self.link_paths.push(PathBuf::from(val));
909 }
910 "-F" => {
911 let meta = format!("rustc-link-search=framework={}", val);
912 config.print_metadata(&meta);
913 self.framework_paths.push(PathBuf::from(val));
914 }
915 "-I" => {
916 self.include_paths.push(PathBuf::from(val));
917 }
918 "-l" => {
919 if is_msvc && ["m", "c", "pthread"].contains(&val) {
921 continue;
922 }
923
924 if val.starts_with(':') {
925 let meta = format!("rustc-link-arg={}{}", flag, val);
927 config.print_metadata(&meta);
928 } else if statik && is_static_available(val, &system_roots, &dirs) {
929 let meta = format!("rustc-link-lib=static={}", val);
930 config.print_metadata(&meta);
931 } else {
932 let meta = format!("rustc-link-lib={}", val);
933 config.print_metadata(&meta);
934 }
935
936 self.libs.push(val.to_string());
937 }
938 "-D" => {
939 let mut iter = val.split('=');
940 self.defines.insert(
941 iter.next().unwrap().to_owned(),
942 iter.next().map(|s| s.to_owned()),
943 );
944 }
945 "-u" => {
946 let meta = format!("rustc-link-arg=-Wl,-u,{}", val);
947 config.print_metadata(&meta);
948 }
949 _ => {}
950 }
951 }
952
953 let mut iter = words.iter().flat_map(|arg| {
955 if arg.starts_with("-Wl,") {
956 arg[4..].split(',').collect()
957 } else {
958 vec![arg.as_ref()]
959 }
960 });
961 while let Some(part) = iter.next() {
962 match part {
963 "-framework" => {
964 if let Some(lib) = iter.next() {
965 let meta = format!("rustc-link-lib=framework={}", lib);
966 config.print_metadata(&meta);
967 self.frameworks.push(lib.to_string());
968 }
969 }
970 "-isystem" | "-iquote" | "-idirafter" => {
971 if let Some(inc) = iter.next() {
972 self.include_paths.push(PathBuf::from(inc));
973 }
974 }
975 "-undefined" | "--undefined" => {
976 if let Some(symbol) = iter.next() {
977 let meta = format!("rustc-link-arg=-Wl,{},{}", part, symbol);
978 config.print_metadata(&meta);
979 }
980 }
981 _ => {
982 let path = std::path::Path::new(part);
983 if path.is_file() {
984 if let (Some(dir), Some(file_name), Ok(target)) =
989 (path.parent(), path.file_name(), &target)
990 {
991 match Self::extract_lib_from_filename(
992 target,
993 &file_name.to_string_lossy(),
994 ) {
995 Some(lib_basename) => {
996 let link_search =
997 format!("rustc-link-search={}", dir.display());
998 config.print_metadata(&link_search);
999
1000 let link_lib = format!("rustc-link-lib={}", lib_basename);
1001 config.print_metadata(&link_lib);
1002 self.link_files.push(PathBuf::from(path));
1003 }
1004 None => {
1005 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);
1006 }
1007 }
1008 }
1009 }
1010 }
1011 }
1012 }
1013
1014 let linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,"));
1015 for option in linker_options {
1016 let mut pop = false;
1017 let mut ld_option = vec![];
1018 for subopt in option[4..].split(',') {
1019 if pop {
1020 pop = false;
1021 continue;
1022 }
1023
1024 if subopt == "-framework" {
1025 pop = true;
1026 continue;
1027 }
1028
1029 ld_option.push(subopt);
1030 }
1031
1032 let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(","));
1033 config.print_metadata(&meta);
1034
1035 self.ld_args
1036 .push(ld_option.into_iter().map(String::from).collect());
1037 }
1038 }
1039
1040 fn parse_modversion(&mut self, output: &str) {
1041 self.version.push_str(output.lines().next().unwrap().trim());
1042 }
1043}
1044
1045fn envify(name: &str) -> String {
1046 name.chars()
1047 .map(|c| c.to_ascii_uppercase())
1048 .map(|c| if c == '-' { '_' } else { c })
1049 .collect()
1050}
1051
1052fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool {
1054 let libnames = {
1055 let mut names = vec![format!("lib{}.a", name)];
1056
1057 if cfg!(target_os = "windows") {
1058 names.push(format!("{}.lib", name));
1059 }
1060
1061 names
1062 };
1063
1064 dirs.iter().any(|dir| {
1065 let library_exists = libnames.iter().any(|libname| dir.join(&libname).exists());
1066 library_exists && !system_roots.iter().any(|sys| dir.starts_with(sys))
1067 })
1068}
1069
1070fn split_flags(output: &[u8]) -> Vec<String> {
1078 let mut word = Vec::new();
1079 let mut words = Vec::new();
1080 let mut escaped = false;
1081
1082 for &b in output {
1083 match b {
1084 _ if escaped => {
1085 escaped = false;
1086 word.push(b);
1087 }
1088 b'\\' => escaped = true,
1089 b'\t' | b'\n' | b'\r' | b' ' => {
1090 if !word.is_empty() {
1091 words.push(String::from_utf8(word).unwrap());
1092 word = Vec::new();
1093 }
1094 }
1095 _ => word.push(b),
1096 }
1097 }
1098
1099 if !word.is_empty() {
1100 words.push(String::from_utf8(word).unwrap());
1101 }
1102
1103 words
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108 use super::*;
1109
1110 #[test]
1111 #[cfg(target_os = "macos")]
1112 fn system_library_mac_test() {
1113 use std::path::Path;
1114
1115 let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")];
1116
1117 assert!(!is_static_available(
1118 "PluginManager",
1119 &system_roots,
1120 &[PathBuf::from("/Library/Frameworks")]
1121 ));
1122 assert!(!is_static_available(
1123 "python2.7",
1124 &system_roots,
1125 &[PathBuf::from(
1126 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config"
1127 )]
1128 ));
1129 assert!(!is_static_available(
1130 "ffi_convenience",
1131 &system_roots,
1132 &[PathBuf::from(
1133 "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs"
1134 )]
1135 ));
1136
1137 if Path::new("/usr/local/lib/libpng16.a").exists() {
1139 assert!(is_static_available(
1140 "png16",
1141 &system_roots,
1142 &[PathBuf::from("/usr/local/lib")]
1143 ));
1144
1145 let libpng = Config::new()
1146 .range_version("1".."99")
1147 .probe("libpng16")
1148 .unwrap();
1149 assert!(libpng.version.find('\n').is_none());
1150 }
1151 }
1152
1153 #[test]
1154 #[cfg(target_os = "linux")]
1155 fn system_library_linux_test() {
1156 assert!(!is_static_available(
1157 "util",
1158 &[PathBuf::from("/usr")],
1159 &[PathBuf::from("/usr/lib/x86_64-linux-gnu")]
1160 ));
1161 assert!(!is_static_available(
1162 "dialog",
1163 &[PathBuf::from("/usr")],
1164 &[PathBuf::from("/usr/lib")]
1165 ));
1166 }
1167
1168 fn test_library_filename(target: &str, filename: &str) {
1169 assert_eq!(
1170 Library::extract_lib_from_filename(target, filename),
1171 Some("foo")
1172 );
1173 }
1174
1175 #[test]
1176 fn link_filename_linux() {
1177 let target = "x86_64-unknown-linux-gnu";
1178 test_library_filename(target, "libfoo.a");
1179 test_library_filename(target, "libfoo.so");
1180 }
1181
1182 #[test]
1183 fn link_filename_apple() {
1184 let target = "x86_64-apple-darwin";
1185 test_library_filename(target, "libfoo.a");
1186 test_library_filename(target, "libfoo.so");
1187 test_library_filename(target, "libfoo.dylib");
1188 }
1189
1190 #[test]
1191 fn link_filename_msvc() {
1192 let target = "x86_64-pc-windows-msvc";
1193 test_library_filename(target, "foo.lib");
1195 }
1196
1197 #[test]
1198 fn link_filename_mingw() {
1199 let target = "x86_64-pc-windows-gnu";
1200 test_library_filename(target, "foo.lib");
1201 test_library_filename(target, "libfoo.a");
1202 test_library_filename(target, "foo.dll");
1203 test_library_filename(target, "foo.dll.a");
1204 }
1205}