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/// Quote an argument that has spaces in it.
231/// When our `WrappedCommand` is printed to the terminal, arguments that contain spaces needed to be quoted.
232/// Otherwise, we will have output such as:
233/// `pkg-config --libs --cflags foo foo < 3.11`
234/// which cannot be used in a terminal - it will attempt to read a file named 3.11 and provide it as stdin for pkg-config.
235/// Using this function, we instead get the correct output:
236/// `pkg-config --libs --cflags foo 'foo < 3.11'`
237fn quote_if_needed(arg: String) -> String {
238    if arg.contains(' ') {
239        format!("'{}'", arg)
240    } else {
241        arg
242    }
243}
244
245/// Output a command invocation that can be copy-pasted into the terminal.
246/// `Command`'s existing debug implementation is not used for that reason,
247/// as it can sometimes lead to output such as:
248/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" PKG_CONFIG_ALLOW_SYSTEM_LIBS="1" "pkg-config" "--libs" "--cflags" "mylibrary"`
249/// Which cannot be copy-pasted into terminals such as nushell, and is a bit noisy.
250/// This will look something like:
251/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs --cflags mylibrary`
252impl Display for WrappedCommand {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        // Format all explicitly defined environment variables
255        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        // Format all pkg-config arguments
263        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        // Failed `unwrap()` prints Debug representation, but the default debug format lacks helpful instructions for the end users
279        <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                            "" // iOS cross-compilation requires a custom setup, no easy fix
307                        } 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                            "" // There's no easy fix for Windows users
313                        };
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                // Give a short explanation of what the error is
342                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                // Give the command run so users can reproduce the error
352                writeln!(f, "> {}\n", command)?;
353
354                // Explain how it was caused
355                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                // There will be no status code if terminated by signal
367                if let Some(_code) = output.status.code() {
368                    // Nix uses a wrapper script for pkg-config that sets the custom
369                    // environment variable PKG_CONFIG_PATH_FOR_TARGET
370                    let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
371
372                    // Find a search path to use
373                    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                    // Guess the most reasonable course of action
382                    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                        // Even on Nix, setting PKG_CONFIG_PATH seems to be a viable option
397                        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                    // Try and nudge the user in the right direction so they don't get stuck
406                    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/// Deprecated in favor of the probe_library function
440#[doc(hidden)]
441pub fn find_library(name: &str) -> Result<Library, String> {
442    probe_library(name).map_err(|e| e.to_string())
443}
444
445/// Simple shortcut for using all default options for finding a library.
446pub 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
456/// Run `pkg-config` to get the value of a variable from a package using
457/// `--variable`.
458///
459/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are
460/// returned by `pkg-config --variable`, which makes them unsuitable to use
461/// during cross-compilation unless specifically designed to be used
462/// at that time.
463pub 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    /// Creates a new set of configuration options which are all initially set
472    /// to "blank".
473    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    /// Indicate whether the `--static` flag should be passed.
487    ///
488    /// This will override the inference from environment variables described in
489    /// the crate documentation.
490    pub fn statik(&mut self, statik: bool) -> &mut Config {
491        self.statik = Some(statik);
492        self
493    }
494
495    /// Indicate that the library must be at least version `vers`.
496    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    /// Indicate that the library must be equal to version `vers`.
503    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    /// Indicate that the library's version must be in `range`.
510    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    /// Add an argument to pass to pkg-config.
528    ///
529    /// It's placed after all of the arguments generated by this library.
530    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    /// Define whether metadata should be emitted for cargo allowing it to
536    /// automatically link the binary. Defaults to `true`.
537    pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
538        self.cargo_metadata = cargo_metadata;
539        self
540    }
541
542    /// Define whether metadata should be emitted for cargo allowing to
543    /// automatically rebuild when environment variables change. Defaults to
544    /// `true`.
545    pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
546        self.env_metadata = env_metadata;
547        self
548    }
549
550    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment
551    /// variable.
552    ///
553    /// This env var is enabled by default.
554    pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
555        self.print_system_libs = print;
556        self
557    }
558
559    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment
560    /// variable.
561    ///
562    /// This env var is enabled by default.
563    pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
564        self.print_system_cflags = print;
565        self
566    }
567
568    /// Deprecated in favor fo the `probe` function
569    #[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    /// Run `pkg-config` to find the library `name`.
575    ///
576    /// This will use all configuration previously set to specify how
577    /// `pkg-config` is run.
578    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    /// True if pkg-config is used for the host system, or configured for cross-compilation
607    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        // Only use pkg-config in host == target situations by default (allowing an
612        // override).
613        if host == target {
614            return true;
615        }
616
617        // pkg-config may not be aware of cross-compilation, and require
618        // a wrapper script that sets up platform-specific prefixes.
619        match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
620            // don't use pkg-config if explicitly disabled
621            Some(ref val) if val == "0" => false,
622            Some(_) => true,
623            None => {
624                // if not disabled, and pkg-config is customized,
625                // then assume it's prepared for cross-compilation
626                self.targeted_env_var("PKG_CONFIG").is_some()
627                    || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
628            }
629        }
630    }
631
632    /// Deprecated in favor of the top level `get_variable` function
633    #[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
773// Implement Default manually since Bound does not implement Default.
774impl 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    /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories)
806    /// using target-specific logic.
807    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                // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc,
821                // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it
822                // receives via the -l command line argument before passing it to the linker:
823                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446
824                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457
825                // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs.
826                // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove
827                // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix.
828                // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll
829                let filename = &filename[prefix.len()..];
830                return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
831            } else {
832                // According to link.exe documentation:
833                // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170
834                //
835                //   LINK doesn't use file extensions to make assumptions about the contents of a file.
836                //   Instead, LINK examines each input file to determine what kind of file it is.
837                //
838                // However, rustc appends `.lib` to the string it receives from the -l command line argument,
839                // which it receives from Cargo via cargo:rustc-link-lib:
840                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828
841                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843
842                // So the only file extension that works for MSVC targets is `.lib`
843                // However, for externally created libraries, there's no
844                // guarantee that the extension is ".lib" so we need to
845                // consider all options.
846                // See:
847                // https://github.com/mesonbuild/meson/issues/8153
848                // https://github.com/rust-lang/rust/issues/114013
849                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        // Handle single-character arguments like `-I/usr/include`
898        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                    // These are provided by the CRT with MSVC
920                    if is_msvc && ["m", "c", "pthread"].contains(&val) {
921                        continue;
922                    }
923
924                    if val.starts_with(':') {
925                        // Pass this flag to linker directly.
926                        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        // Handle multi-character arguments with space-separated value like `-framework foo`
954        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                        // Cargo doesn't have a means to directly specify a file path to link,
985                        // so split up the path into the parent directory and library name.
986                        // TODO: pass file path directly when link-arg library type is stabilized
987                        // https://github.com/rust-lang/rust/issues/99427
988                        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
1052/// System libraries should only be linked dynamically
1053fn 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
1070/// Split output produced by pkg-config --cflags and / or --libs into separate flags.
1071///
1072/// Backslash in output is used to preserve literal meaning of following byte.  Different words are
1073/// separated by unescaped space. Other whitespace characters generally should not occur unescaped
1074/// at all, apart from the newline at the end of output. For compatibility with what others
1075/// consumers of pkg-config output would do in this scenario, they are used here for splitting as
1076/// well.
1077fn 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        // Homebrew is in /usr/local, and it's not a part of the OS
1138        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        // static and dynamic libraries have the same .lib suffix
1194        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}