pkg_config/
lib.rs

1//! A build dependency for Cargo libraries to find system artifacts through the
2//! `pkg-config` utility.
3//!
4//! This library will shell out to `pkg-config` as part of build scripts and
5//! probe the system to determine how to link to a specified library. The
6//! `Config` structure serves as a method of configuring how `pkg-config` is
7//! invoked in a builder style.
8//!
9//! After running `pkg-config` all appropriate Cargo metadata will be printed on
10//! stdout if the search was successful.
11//!
12//! # Environment variables
13//!
14//! A number of environment variables are available to globally configure how
15//! this crate will invoke `pkg-config`:
16//!
17//! * `FOO_NO_PKG_CONFIG` - if set, this will disable running `pkg-config` when
18//!   probing for the library named `foo`.
19//!
20//! ### Linking
21//!
22//! There are also a number of environment variables which can configure how a
23//! library is linked to (dynamically vs statically). These variables control
24//! whether the `--static` flag is passed. Note that this behavior can be
25//! overridden by configuring explicitly on `Config`. The variables are checked
26//! in the following order:
27//!
28//! * `FOO_STATIC` - pass `--static` for the library `foo`
29//! * `FOO_DYNAMIC` - do not pass `--static` for the library `foo`
30//! * `PKG_CONFIG_ALL_STATIC` - pass `--static` for all libraries
31//! * `PKG_CONFIG_ALL_DYNAMIC` - do not pass `--static` for all libraries
32//!
33//! ### Cross-compilation
34//!
35//! In cross-compilation context, it is useful to manage separately
36//! `PKG_CONFIG_PATH` and a few other variables for the `host` and the `target`
37//! platform.
38//!
39//! The supported variables are: `PKG_CONFIG_PATH`, `PKG_CONFIG_LIBDIR`, and
40//! `PKG_CONFIG_SYSROOT_DIR`.
41//!
42//! Each of these variables can also be supplied with certain prefixes and
43//! suffixes, in the following prioritized order:
44//!
45//! 1. `<var>_<target>` - for example, `PKG_CONFIG_PATH_x86_64-unknown-linux-gnu`
46//! 2. `<var>_<target_with_underscores>` - for example,
47//!    `PKG_CONFIG_PATH_x86_64_unknown_linux_gnu`
48//! 3. `<build-kind>_<var>` - for example, `HOST_PKG_CONFIG_PATH` or
49//!    `TARGET_PKG_CONFIG_PATH`
50//! 4. `<var>` - a plain `PKG_CONFIG_PATH`
51//!
52//! This crate will allow `pkg-config` to be used in cross-compilation
53//! if `PKG_CONFIG_SYSROOT_DIR` or `PKG_CONFIG` is set. You can set
54//! `PKG_CONFIG_ALLOW_CROSS=1` to bypass the compatibility check, but please
55//! note that enabling use of `pkg-config` in cross-compilation without
56//! appropriate sysroot and search paths set is likely to break builds.
57//!
58//! # Example
59//!
60//! Find the system library named `foo`, with minimum version 1.2.3:
61//!
62//! ```no_run
63//! fn main() {
64//!     pkg_config::Config::new().atleast_version("1.2.3").probe("foo").unwrap();
65//! }
66//! ```
67//!
68//! Find the system library named `foo`, with no version requirement (not
69//! recommended):
70//!
71//! ```no_run
72//! fn main() {
73//!     pkg_config::probe_library("foo").unwrap();
74//! }
75//! ```
76//!
77//! Configure how library `foo` is linked to.
78//!
79//! ```no_run
80//! fn main() {
81//!     pkg_config::Config::new().atleast_version("1.2.3").statik(true).probe("foo").unwrap();
82//! }
83//! ```
84
85#![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
99/// Wrapper struct to polyfill methods introduced in 1.57 (`get_envs`, `get_args` etc).
100/// This is needed to reconstruct the pkg-config command for output in a copy-
101/// paste friendly format via `Display`.
102struct 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    /// Libraries specified by -l
124    pub libs: Vec<String>,
125    /// Library search paths specified by -L
126    pub link_paths: Vec<PathBuf>,
127    /// Library file paths specified without -l
128    pub link_files: Vec<PathBuf>,
129    /// Darwin frameworks specified by -framework
130    pub frameworks: Vec<String>,
131    /// Darwin framework search paths specified by -F
132    pub framework_paths: Vec<PathBuf>,
133    /// C/C++ header include paths specified by -I
134    pub include_paths: Vec<PathBuf>,
135    /// Linker options specified by -Wl
136    pub ld_args: Vec<Vec<String>>,
137    /// C/C++ definitions specified by -D
138    pub defines: HashMap<String, Option<String>>,
139    /// Version specified by .pc file's Version field
140    pub version: String,
141    /// Ensure that this struct can only be created via its private `[Library::new]` constructor.
142    /// Users of this crate can only access the struct via `[Config::probe]`.
143    _priv: (),
144}
145
146/// Represents all reasons `pkg-config` might not succeed or be run at all.
147pub enum Error {
148    /// Aborted because of `*_NO_PKG_CONFIG` environment variable.
149    ///
150    /// Contains the name of the responsible environment variable.
151    EnvNoPkgConfig(String),
152
153    /// Detected cross compilation without a custom sysroot.
154    ///
155    /// Ignore the error with `PKG_CONFIG_ALLOW_CROSS=1`,
156    /// which may let `pkg-config` select libraries
157    /// for the host's architecture instead of the target's.
158    CrossCompilation,
159
160    /// Failed to run `pkg-config`.
161    ///
162    /// Contains the command and the cause.
163    Command { command: String, cause: io::Error },
164
165    /// `pkg-config` did not exit successfully after probing a library.
166    ///
167    /// Contains the command and output.
168    Failure { command: String, output: Output },
169
170    /// `pkg-config` did not exit successfully on the first attempt to probe a library.
171    ///
172    /// Contains the command and output.
173    ProbeFailure {
174        name: String,
175        command: String,
176        output: Output,
177    },
178
179    #[doc(hidden)]
180    // please don't match on this, we're likely to add more variants over time
181    __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
230/// Output a command invocation that can be copy-pasted into the terminal.
231/// `Command`'s existing debug implementation is not used for that reason,
232/// as it can sometimes lead to output such as:
233/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" PKG_CONFIG_ALLOW_SYSTEM_LIBS="1" "pkg-config" "--libs" "--cflags" "mylibrary"`
234/// Which cannot be copy-pasted into terminals such as nushell, and is a bit noisy.
235/// This will look something like:
236/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs --cflags mylibrary`
237impl Display for WrappedCommand {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        // Format all explicitly defined environment variables
240        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        // Format all pkg-config arguments
248        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        // Failed `unwrap()` prints Debug representation, but the default debug format lacks helpful instructions for the end users
264        <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                            "" // There's no easy fix for Windows users
296                        };
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                // Give a short explanation of what the error is
325                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                // Give the command run so users can reproduce the error
335                writeln!(f, "> {}\n", command)?;
336
337                // Explain how it was caused
338                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                // There will be no status code if terminated by signal
350                if let Some(_code) = output.status.code() {
351                    // Nix uses a wrapper script for pkg-config that sets the custom
352                    // environment variable PKG_CONFIG_PATH_FOR_TARGET
353                    let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
354
355                    // Find a search path to use
356                    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                    // Guess the most reasonable course of action
365                    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                        // Even on Nix, setting PKG_CONFIG_PATH seems to be a viable option
380                        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                    // Try and nudge the user in the right direction so they don't get stuck
389                    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/// Deprecated in favor of the probe_library function
423#[doc(hidden)]
424pub fn find_library(name: &str) -> Result<Library, String> {
425    probe_library(name).map_err(|e| e.to_string())
426}
427
428/// Simple shortcut for using all default options for finding a library.
429pub 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
439/// Run `pkg-config` to get the value of a variable from a package using
440/// `--variable`.
441///
442/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are
443/// returned by `pkg-config --variable`, which makes them unsuitable to use
444/// during cross-compilation unless specifically designed to be used
445/// at that time.
446pub 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    /// Creates a new set of configuration options which are all initially set
455    /// to "blank".
456    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    /// Indicate whether the `--static` flag should be passed.
470    ///
471    /// This will override the inference from environment variables described in
472    /// the crate documentation.
473    pub fn statik(&mut self, statik: bool) -> &mut Config {
474        self.statik = Some(statik);
475        self
476    }
477
478    /// Indicate that the library must be at least version `vers`.
479    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    /// Indicate that the library must be equal to version `vers`.
486    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    /// Indicate that the library's version must be in `range`.
493    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    /// Add an argument to pass to pkg-config.
511    ///
512    /// It's placed after all of the arguments generated by this library.
513    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    /// Define whether metadata should be emitted for cargo allowing it to
519    /// automatically link the binary. Defaults to `true`.
520    pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
521        self.cargo_metadata = cargo_metadata;
522        self
523    }
524
525    /// Define whether metadata should be emitted for cargo allowing to
526    /// automatically rebuild when environment variables change. Defaults to
527    /// `true`.
528    pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
529        self.env_metadata = env_metadata;
530        self
531    }
532
533    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment
534    /// variable.
535    ///
536    /// This env var is enabled by default.
537    pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
538        self.print_system_libs = print;
539        self
540    }
541
542    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment
543    /// variable.
544    ///
545    /// This env var is enabled by default.
546    pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
547        self.print_system_cflags = print;
548        self
549    }
550
551    /// Deprecated in favor fo the `probe` function
552    #[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    /// Run `pkg-config` to find the library `name`.
558    ///
559    /// This will use all configuration previously set to specify how
560    /// `pkg-config` is run.
561    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    /// True if pkg-config is used for the host system, or configured for cross-compilation
590    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        // Only use pkg-config in host == target situations by default (allowing an
595        // override).
596        if host == target {
597            return true;
598        }
599
600        // pkg-config may not be aware of cross-compilation, and require
601        // a wrapper script that sets up platform-specific prefixes.
602        match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
603            // don't use pkg-config if explicitly disabled
604            Some(ref val) if val == "0" => false,
605            Some(_) => true,
606            None => {
607                // if not disabled, and pkg-config is customized,
608                // then assume it's prepared for cross-compilation
609                self.targeted_env_var("PKG_CONFIG").is_some()
610                    || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
611            }
612        }
613    }
614
615    /// Deprecated in favor of the top level `get_variable` function
616    #[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
756// Implement Default manually since Bound does not implement Default.
757impl 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    /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories)
789    /// using target-specific logic.
790    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                // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc,
804                // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it
805                // receives via the -l command line argument before passing it to the linker:
806                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446
807                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457
808                // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs.
809                // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove
810                // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix.
811                // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll
812                let filename = &filename[prefix.len()..];
813                return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
814            } else {
815                // According to link.exe documentation:
816                // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170
817                //
818                //   LINK doesn't use file extensions to make assumptions about the contents of a file.
819                //   Instead, LINK examines each input file to determine what kind of file it is.
820                //
821                // However, rustc appends `.lib` to the string it receives from the -l command line argument,
822                // which it receives from Cargo via cargo:rustc-link-lib:
823                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828
824                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843
825                // So the only file extension that works for MSVC targets is `.lib`
826                // However, for externally created libraries, there's no
827                // guarantee that the extension is ".lib" so we need to
828                // consider all options.
829                // See:
830                // https://github.com/mesonbuild/meson/issues/8153
831                // https://github.com/rust-lang/rust/issues/114013
832                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        // Handle single-character arguments like `-I/usr/include`
881        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                    // These are provided by the CRT with MSVC
903                    if is_msvc && ["m", "c", "pthread"].contains(&val) {
904                        continue;
905                    }
906
907                    if val.starts_with(':') {
908                        // Pass this flag to linker directly.
909                        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        // Handle multi-character arguments with space-separated value like `-framework foo`
937        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                        // Cargo doesn't have a means to directly specify a file path to link,
968                        // so split up the path into the parent directory and library name.
969                        // TODO: pass file path directly when link-arg library type is stabilized
970                        // https://github.com/rust-lang/rust/issues/99427
971                        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
1035/// System libraries should only be linked dynamically
1036fn 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
1053/// Split output produced by pkg-config --cflags and / or --libs into separate flags.
1054///
1055/// Backslash in output is used to preserve literal meaning of following byte.  Different words are
1056/// separated by unescaped space. Other whitespace characters generally should not occur unescaped
1057/// at all, apart from the newline at the end of output. For compatibility with what others
1058/// consumers of pkg-config output would do in this scenario, they are used here for splitting as
1059/// well.
1060fn 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        // Homebrew is in /usr/local, and it's not a part of the OS
1121        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        // static and dynamic libraries have the same .lib suffix
1177        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}