Skip to main content

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    probe_cflags: bool,
120}
121
122#[derive(Clone, Debug)]
123pub struct Library {
124    /// Libraries specified by -l
125    pub libs: Vec<String>,
126    /// Library search paths specified by -L
127    pub link_paths: Vec<PathBuf>,
128    /// Library file paths specified without -l
129    pub link_files: Vec<PathBuf>,
130    /// Darwin frameworks specified by -framework
131    pub frameworks: Vec<String>,
132    /// Darwin framework search paths specified by -F
133    pub framework_paths: Vec<PathBuf>,
134    /// C/C++ header include paths specified by -I
135    pub include_paths: Vec<PathBuf>,
136    /// Linker options specified by -Wl
137    pub ld_args: Vec<Vec<String>>,
138    /// C/C++ definitions specified by -D
139    pub defines: HashMap<String, Option<String>>,
140    /// Version specified by .pc file's Version field
141    pub version: String,
142    /// Ensure that this struct can only be created via its private `[Library::new]` constructor.
143    /// Users of this crate can only access the struct via `[Config::probe]`.
144    _priv: (),
145}
146
147/// Represents all reasons `pkg-config` might not succeed or be run at all.
148#[non_exhaustive]
149pub enum Error {
150    /// Aborted because of `*_NO_PKG_CONFIG` environment variable.
151    ///
152    /// Contains the name of the responsible environment variable.
153    EnvNoPkgConfig(String),
154
155    /// Detected cross compilation without a custom sysroot.
156    ///
157    /// Ignore the error with `PKG_CONFIG_ALLOW_CROSS=1`,
158    /// which may let `pkg-config` select libraries
159    /// for the host's architecture instead of the target's.
160    CrossCompilation,
161
162    /// Failed to run `pkg-config`.
163    ///
164    /// Contains the command and the cause.
165    Command { command: String, cause: io::Error },
166
167    /// `pkg-config` did not exit successfully after probing a library.
168    ///
169    /// Contains the command and output.
170    Failure { command: String, output: Output },
171
172    /// `pkg-config` did not exit successfully on the first attempt to probe a library.
173    ///
174    /// Contains the command and output.
175    ProbeFailure {
176        name: String,
177        command: String,
178        output: Output,
179    },
180}
181
182impl WrappedCommand {
183    fn new<S: AsRef<OsStr>>(program: S) -> Self {
184        Self {
185            inner: Command::new(program.as_ref()),
186            program: program.as_ref().to_os_string(),
187            env_vars: Vec::new(),
188            args: Vec::new(),
189        }
190    }
191
192    fn args<I, S>(&mut self, args: I) -> &mut Self
193    where
194        I: IntoIterator<Item = S> + Clone,
195        S: AsRef<OsStr>,
196    {
197        self.inner.args(args.clone());
198        self.args
199            .extend(args.into_iter().map(|arg| arg.as_ref().to_os_string()));
200
201        self
202    }
203
204    fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
205        self.inner.arg(arg.as_ref());
206        self.args.push(arg.as_ref().to_os_string());
207
208        self
209    }
210
211    fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
212    where
213        K: AsRef<OsStr>,
214        V: AsRef<OsStr>,
215    {
216        self.inner.env(key.as_ref(), value.as_ref());
217        self.env_vars
218            .push((key.as_ref().to_os_string(), value.as_ref().to_os_string()));
219
220        self
221    }
222
223    fn output(&mut self) -> io::Result<Output> {
224        self.inner.output()
225    }
226}
227
228/// Quote an argument that has spaces in it.
229/// When our `WrappedCommand` is printed to the terminal, arguments that contain spaces needed to be quoted.
230/// Otherwise, we will have output such as:
231/// `pkg-config --libs --cflags foo foo < 3.11`
232/// 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.
233/// Using this function, we instead get the correct output:
234/// `pkg-config --libs --cflags foo 'foo < 3.11'`
235fn quote_if_needed(arg: String) -> String {
236    if arg.contains(' ') {
237        format!("'{}'", arg)
238    } else {
239        arg
240    }
241}
242
243/// Output a command invocation that can be copy-pasted into the terminal.
244/// `Command`'s existing debug implementation is not used for that reason,
245/// as it can sometimes lead to output such as:
246/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" PKG_CONFIG_ALLOW_SYSTEM_LIBS="1" "pkg-config" "--libs" "--cflags" "mylibrary"`
247/// Which cannot be copy-pasted into terminals such as nushell, and is a bit noisy.
248/// This will look something like:
249/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs --cflags mylibrary`
250impl Display for WrappedCommand {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        // Format all explicitly defined environment variables
253        let envs = self
254            .env_vars
255            .iter()
256            .map(|(env, arg)| format!("{}={}", env.to_string_lossy(), arg.to_string_lossy()))
257            .collect::<Vec<String>>()
258            .join(" ");
259
260        // Format all pkg-config arguments
261        let args = self
262            .args
263            .iter()
264            .map(|arg| quote_if_needed(arg.to_string_lossy().to_string()))
265            .collect::<Vec<String>>()
266            .join(" ");
267
268        write!(f, "{} {} {}", envs, self.program.to_string_lossy(), args)
269    }
270}
271
272impl error::Error for Error {}
273
274impl fmt::Debug for Error {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
276        // Failed `unwrap()` prints Debug representation, but the default debug format lacks helpful instructions for the end users
277        <Error as fmt::Display>::fmt(self, f)
278    }
279}
280
281impl fmt::Display for Error {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
283        match *self {
284            Error::EnvNoPkgConfig(ref name) => write!(f, "Aborted because {} is set", name),
285            Error::CrossCompilation => f.write_str(
286                "pkg-config has not been configured to support cross-compilation.\n\
287                \n\
288                Install a sysroot for the target platform and configure it via\n\
289                PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\n\
290                cross-compiling wrapper for pkg-config and set it via\n\
291                PKG_CONFIG environment variable.",
292            ),
293            Error::Command {
294                ref command,
295                ref cause,
296            } => {
297                match cause.kind() {
298                    io::ErrorKind::NotFound => {
299                        let crate_name =
300                            std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "sys".to_owned());
301                        let instructions = if cfg!(target_os = "macos") {
302                            "Try `brew install pkgconf` if you have Homebrew.\n"
303                        } else if cfg!(target_os = "ios") {
304                            "" // iOS cross-compilation requires a custom setup, no easy fix
305                        } else if cfg!(unix) {
306                            "Try `apt install pkg-config`, or `yum install pkg-config`, or `brew install pkgconf`\n\
307                            or `pkg install pkg-config`, or `apk add pkgconfig` \
308                            depending on your distribution.\n"
309                        } else {
310                            "" // There's no easy fix for Windows users
311                        };
312                        write!(f, "Could not run `{command}`\n\
313                        The pkg-config command could not be found.\n\
314                        \n\
315                        Most likely, you need to install a pkg-config package for your OS.\n\
316                        {instructions}\
317                        \n\
318                        If you've already installed it, ensure the pkg-config command is one of the\n\
319                        directories in the PATH environment variable.\n\
320                        \n\
321                        If you did not expect this build to link to a pre-installed system library,\n\
322                        then check documentation of the {crate_name} crate for an option to\n\
323                        build the library from source, or disable features or dependencies\n\
324                        that require pkg-config.", command = command, instructions = instructions, crate_name = crate_name)
325                    }
326                    _ => write!(f, "Failed to run command `{}`, because: {}", command, cause),
327                }
328            }
329            Error::ProbeFailure {
330                ref name,
331                ref command,
332                ref output,
333            } => {
334                let crate_name =
335                    env::var("CARGO_PKG_NAME").unwrap_or(String::from("<NO CRATE NAME>"));
336
337                writeln!(f)?;
338
339                // Give a short explanation of what the error is
340                writeln!(
341                    f,
342                    "pkg-config {}",
343                    match output.status.code() {
344                        Some(code) => format!("exited with status code {}", code),
345                        None => "was terminated by signal".to_string(),
346                    }
347                )?;
348
349                // Give the command run so users can reproduce the error
350                writeln!(f, "> {}\n", command)?;
351
352                // Show pkg-config's own error output, this often contains the
353                // actual reason for the failure (e.g. a missing transitive
354                // dependency) which is more specific than our generic message.
355                let stderr = String::from_utf8_lossy(&output.stderr);
356                if !stderr.is_empty() {
357                    writeln!(f, "pkg-config output:")?;
358                    for line in stderr.lines() {
359                        writeln!(f, "  {}", line)?;
360                    }
361                    writeln!(f)?;
362                }
363
364                // Explain how it was caused
365                writeln!(
366                    f,
367                    "The system library `{}` required by crate `{}` was not found.",
368                    name, crate_name
369                )?;
370                writeln!(
371                    f,
372                    "The file `{}.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.",
373                    name
374                )?;
375
376                // There will be no status code if terminated by signal
377                if let Some(_code) = output.status.code() {
378                    // Nix uses a wrapper script for pkg-config that sets the custom
379                    // environment variable PKG_CONFIG_PATH_FOR_TARGET
380                    let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
381
382                    // Find a search path to use
383                    let mut search_data = None;
384                    for location in search_locations.iter() {
385                        if let Ok(search_path) = env::var(location) {
386                            search_data = Some((location, search_path));
387                            break;
388                        }
389                    }
390
391                    // Guess the most reasonable course of action
392                    let hint = if let Some((search_location, search_path)) = search_data {
393                        writeln!(
394                            f,
395                            "{} contains the following:\n{}",
396                            search_location,
397                            search_path
398                                .split(':')
399                                .map(|path| format!("    - {}", path))
400                                .collect::<Vec<String>>()
401                                .join("\n"),
402                        )?;
403
404                        format!("you may need to install a package such as {name}, {name}-dev or {name}-devel.", name=name)
405                    } else {
406                        // Even on Nix, setting PKG_CONFIG_PATH seems to be a viable option
407                        writeln!(f, "The PKG_CONFIG_PATH environment variable is not set.")?;
408
409                        format!(
410                            "if you have installed the library, try setting PKG_CONFIG_PATH to the directory containing `{}.pc`.",
411                            name
412                        )
413                    };
414
415                    // Try and nudge the user in the right direction so they don't get stuck
416                    writeln!(f, "\nHINT: {}", hint)?;
417                }
418
419                Ok(())
420            }
421            Error::Failure {
422                ref command,
423                ref output,
424            } => {
425                write!(
426                    f,
427                    "`{}` did not exit successfully: {}",
428                    command, output.status
429                )?;
430                format_output(output, f)
431            }
432        }
433    }
434}
435
436fn format_output(output: &Output, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437    let stdout = String::from_utf8_lossy(&output.stdout);
438    if !stdout.is_empty() {
439        write!(f, "\n--- stdout\n{}", stdout)?;
440    }
441    let stderr = String::from_utf8_lossy(&output.stderr);
442    if !stderr.is_empty() {
443        write!(f, "\n--- stderr\n{}", stderr)?;
444    }
445    Ok(())
446}
447
448/// Deprecated in favor of the probe_library function
449#[doc(hidden)]
450pub fn find_library(name: &str) -> Result<Library, String> {
451    probe_library(name).map_err(|e| e.to_string())
452}
453
454/// Simple shortcut for using all default options for finding a library.
455pub fn probe_library(name: &str) -> Result<Library, Error> {
456    Config::new().probe(name)
457}
458
459#[doc(hidden)]
460#[deprecated(note = "use config.target_supported() instance method instead")]
461pub fn target_supported() -> bool {
462    Config::new().target_supported()
463}
464
465/// Run `pkg-config` to get the value of a variable from a package using
466/// `--variable`.
467///
468/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are
469/// returned by `pkg-config --variable`, which makes them unsuitable to use
470/// during cross-compilation unless specifically designed to be used
471/// at that time.
472pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> {
473    let arg = format!("--variable={}", variable);
474    let cfg = Config::new();
475    let out = cfg.run(package, &[&arg])?;
476    Ok(str::from_utf8(&out).unwrap().trim_end().to_owned())
477}
478
479impl Config {
480    /// Creates a new set of configuration options which are all initially set
481    /// to "blank".
482    pub fn new() -> Config {
483        Config {
484            statik: None,
485            min_version: Bound::Unbounded,
486            max_version: Bound::Unbounded,
487            extra_args: vec![],
488            print_system_cflags: true,
489            print_system_libs: true,
490            cargo_metadata: true,
491            env_metadata: true,
492            probe_cflags: true,
493        }
494    }
495
496    /// Indicate whether the `--static` flag should be passed.
497    ///
498    /// This will override the inference from environment variables described in
499    /// the crate documentation.
500    pub fn statik(&mut self, statik: bool) -> &mut Config {
501        self.statik = Some(statik);
502        self
503    }
504
505    /// Indicate that the library must be at least version `vers`.
506    pub fn atleast_version(&mut self, vers: &str) -> &mut Config {
507        self.min_version = Bound::Included(vers.to_string());
508        self.max_version = Bound::Unbounded;
509        self
510    }
511
512    /// Indicate that the library must be equal to version `vers`.
513    pub fn exactly_version(&mut self, vers: &str) -> &mut Config {
514        self.min_version = Bound::Included(vers.to_string());
515        self.max_version = Bound::Included(vers.to_string());
516        self
517    }
518
519    /// Indicate that the library's version must be in `range`.
520    pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config
521    where
522        R: RangeBounds<&'a str>,
523    {
524        self.min_version = match range.start_bound() {
525            Bound::Included(vers) => Bound::Included(vers.to_string()),
526            Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
527            Bound::Unbounded => Bound::Unbounded,
528        };
529        self.max_version = match range.end_bound() {
530            Bound::Included(vers) => Bound::Included(vers.to_string()),
531            Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
532            Bound::Unbounded => Bound::Unbounded,
533        };
534        self
535    }
536
537    /// Add an argument to pass to pkg-config.
538    ///
539    /// It's placed after all of the arguments generated by this library.
540    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config {
541        self.extra_args.push(arg.as_ref().to_os_string());
542        self
543    }
544
545    /// Define whether metadata should be emitted for cargo allowing it to
546    /// automatically link the binary. Defaults to `true`.
547    pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
548        self.cargo_metadata = cargo_metadata;
549        self
550    }
551
552    /// Define whether metadata should be emitted for cargo allowing to
553    /// automatically rebuild when environment variables change. Defaults to
554    /// `true`.
555    pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
556        self.env_metadata = env_metadata;
557        self
558    }
559
560    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment
561    /// variable.
562    ///
563    /// This env var is enabled by default.
564    pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
565        self.print_system_libs = print;
566        self
567    }
568
569    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment
570    /// variable.
571    ///
572    /// This env var is enabled by default.
573    pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
574        self.print_system_cflags = print;
575        self
576    }
577
578    /// Enable or disable passing `--cflags` to `pkg-config`.
579    ///
580    /// This is enabled by default.
581    pub fn probe_cflags(&mut self, probe: bool) -> &mut Config {
582        self.probe_cflags = probe;
583        self
584    }
585
586    /// Deprecated in favor of the `probe` function
587    #[doc(hidden)]
588    pub fn find(&self, name: &str) -> Result<Library, String> {
589        self.probe(name).map_err(|e| e.to_string())
590    }
591
592    /// Run `pkg-config` to find the library `name`.
593    ///
594    /// This will use all configuration previously set to specify how
595    /// `pkg-config` is run.
596    pub fn probe(&self, name: &str) -> Result<Library, Error> {
597        let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name));
598        if self.env_var_os(&abort_var_name).is_some() {
599            return Err(Error::EnvNoPkgConfig(abort_var_name));
600        } else if !self.target_supported() {
601            return Err(Error::CrossCompilation);
602        }
603
604        let mut library = Library::new();
605
606        let mut args = vec!["--libs"];
607        if self.probe_cflags {
608            args.push("--cflags");
609        }
610
611        let output = self.run(name, &args).map_err(|e| match e {
612            Error::Failure { command, output } => Error::ProbeFailure {
613                name: name.to_owned(),
614                command,
615                output,
616            },
617            other => other,
618        })?;
619        library.parse_libs_cflags(name, &output, self);
620
621        let output = self.run(name, &["--modversion"])?;
622        library.parse_modversion(str::from_utf8(&output).unwrap());
623
624        Ok(library)
625    }
626
627    /// True if pkg-config is used for the host system, or configured for cross-compilation
628    pub fn target_supported(&self) -> bool {
629        let target = env::var_os("TARGET").unwrap_or_default();
630        let host = env::var_os("HOST").unwrap_or_default();
631
632        // Only use pkg-config in host == target situations by default (allowing an
633        // override).
634        if host == target {
635            return true;
636        }
637
638        // pkg-config may not be aware of cross-compilation, and require
639        // a wrapper script that sets up platform-specific prefixes.
640        match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
641            // don't use pkg-config if explicitly disabled
642            Some(ref val) if val == "0" => false,
643            Some(_) => true,
644            None => {
645                // if not disabled, and pkg-config is customized,
646                // then assume it's prepared for cross-compilation
647                self.targeted_env_var("PKG_CONFIG").is_some()
648                    || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
649            }
650        }
651    }
652
653    /// Deprecated in favor of the top level `get_variable` function
654    #[doc(hidden)]
655    pub fn get_variable(package: &str, variable: &str) -> Result<String, String> {
656        get_variable(package, variable).map_err(|e| e.to_string())
657    }
658
659    fn targeted_env_var(&self, var_base: &str) -> Option<OsString> {
660        match (env::var("TARGET"), env::var("HOST")) {
661            (Ok(target), Ok(host)) => {
662                let kind = if host == target { "HOST" } else { "TARGET" };
663                let target_u = target.replace('-', "_");
664
665                self.env_var_os(&format!("{}_{}", var_base, target))
666                    .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u)))
667                    .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base)))
668                    .or_else(|| self.env_var_os(var_base))
669            }
670            (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => {
671                self.env_var_os(var_base)
672            }
673            (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => {
674                panic!(
675                    "HOST or TARGET environment variable is not valid unicode: {:?}",
676                    s
677                )
678            }
679        }
680    }
681
682    fn env_var_os(&self, name: &str) -> Option<OsString> {
683        if self.env_metadata {
684            println!("cargo:rerun-if-env-changed={}", name);
685        }
686        env::var_os(name)
687    }
688
689    fn is_static(&self, name: &str) -> bool {
690        self.statik.unwrap_or_else(|| self.infer_static(name))
691    }
692
693    fn run(&self, name: &str, args: &[&str]) -> Result<Vec<u8>, Error> {
694        let pkg_config_exe = self.targeted_env_var("PKG_CONFIG");
695        let fallback_exe = if pkg_config_exe.is_none() {
696            Some(OsString::from("pkgconf"))
697        } else {
698            None
699        };
700        let exe = pkg_config_exe.unwrap_or_else(|| OsString::from("pkg-config"));
701
702        let mut cmd = self.command(exe, name, args);
703
704        match cmd.output().or_else(|e| {
705            if let Some(exe) = fallback_exe {
706                self.command(exe, name, args).output()
707            } else {
708                Err(e)
709            }
710        }) {
711            Ok(output) => {
712                if output.status.success() {
713                    Ok(output.stdout)
714                } else {
715                    Err(Error::Failure {
716                        command: format!("{}", cmd),
717                        output,
718                    })
719                }
720            }
721            Err(cause) => Err(Error::Command {
722                command: format!("{}", cmd),
723                cause,
724            }),
725        }
726    }
727
728    fn command(&self, exe: OsString, name: &str, args: &[&str]) -> WrappedCommand {
729        let mut cmd = WrappedCommand::new(exe);
730        if self.is_static(name) {
731            cmd.arg("--static");
732        }
733        cmd.args(args).args(&self.extra_args);
734
735        if let Some(value) = self.targeted_env_var("PKG_CONFIG_PATH") {
736            cmd.env("PKG_CONFIG_PATH", value);
737        }
738        if let Some(value) = self.targeted_env_var("PKG_CONFIG_LIBDIR") {
739            cmd.env("PKG_CONFIG_LIBDIR", value);
740        }
741        if let Some(value) = self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR") {
742            cmd.env("PKG_CONFIG_SYSROOT_DIR", value);
743        }
744        if self.print_system_libs {
745            cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1");
746        }
747        if self.print_system_cflags {
748            cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1");
749        }
750        cmd.arg(name);
751        match self.min_version {
752            Bound::Included(ref version) => {
753                cmd.arg(format!("{} >= {}", name, version));
754            }
755            Bound::Excluded(ref version) => {
756                cmd.arg(format!("{} > {}", name, version));
757            }
758            _ => (),
759        }
760        match self.max_version {
761            Bound::Included(ref version) => {
762                cmd.arg(format!("{} <= {}", name, version));
763            }
764            Bound::Excluded(ref version) => {
765                cmd.arg(format!("{} < {}", name, version));
766            }
767            _ => (),
768        }
769        cmd
770    }
771
772    fn print_metadata(&self, s: &str) {
773        if self.cargo_metadata {
774            println!("cargo:{}", s);
775        }
776    }
777
778    fn infer_static(&self, name: &str) -> bool {
779        let name = envify(name);
780        if self.env_var_os(&format!("{}_STATIC", name)).is_some() {
781            true
782        } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() {
783            false
784        } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() {
785            true
786        } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() {
787            false
788        } else {
789            false
790        }
791    }
792}
793
794// Implement Default manually since Bound does not implement Default.
795impl Default for Config {
796    fn default() -> Config {
797        Config {
798            statik: None,
799            min_version: Bound::Unbounded,
800            max_version: Bound::Unbounded,
801            extra_args: vec![],
802            print_system_cflags: false,
803            print_system_libs: false,
804            cargo_metadata: false,
805            env_metadata: false,
806            probe_cflags: false,
807        }
808    }
809}
810
811impl Library {
812    fn new() -> Library {
813        Library {
814            libs: Vec::new(),
815            link_paths: Vec::new(),
816            link_files: Vec::new(),
817            include_paths: Vec::new(),
818            ld_args: Vec::new(),
819            frameworks: Vec::new(),
820            framework_paths: Vec::new(),
821            defines: HashMap::new(),
822            version: String::new(),
823            _priv: (),
824        }
825    }
826
827    /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories)
828    /// using target-specific logic.
829    pub fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> {
830        fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> {
831            for suffix in suffixes {
832                if let Some(lib) = filename.strip_suffix(suffix) {
833                    return Some(lib);
834                }
835            }
836            None
837        }
838
839        let prefix = "lib";
840        if target.contains("windows") {
841            if target.contains("gnu") && filename.starts_with(prefix) {
842                // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc,
843                // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it
844                // receives via the -l command line argument before passing it to the linker:
845                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446
846                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457
847                // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs.
848                // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove
849                // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix.
850                // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll
851                let filename = &filename[prefix.len()..];
852                test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"])
853            } else {
854                // According to link.exe documentation:
855                // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170
856                //
857                //   LINK doesn't use file extensions to make assumptions about the contents of a file.
858                //   Instead, LINK examines each input file to determine what kind of file it is.
859                //
860                // However, rustc appends `.lib` to the string it receives from the -l command line argument,
861                // which it receives from Cargo via cargo:rustc-link-lib:
862                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828
863                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843
864                // So the only file extension that works for MSVC targets is `.lib`
865                // However, for externally created libraries, there's no
866                // guarantee that the extension is ".lib" so we need to
867                // consider all options.
868                // See:
869                // https://github.com/mesonbuild/meson/issues/8153
870                // https://github.com/rust-lang/rust/issues/114013
871                test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"])
872            }
873        } else if target.contains("apple") {
874            if let Some(filename) = filename.strip_prefix(prefix) {
875                return test_suffixes(filename, &[".a", ".so", ".dylib"]);
876            }
877            None
878        } else {
879            if let Some(filename) = filename.strip_prefix(prefix) {
880                return test_suffixes(filename, &[".a", ".so"]);
881            }
882            None
883        }
884    }
885
886    fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) {
887        let target = env::var("TARGET");
888        let is_msvc = target
889            .as_ref()
890            .map(|target| target.contains("msvc"))
891            .unwrap_or(false);
892
893        let system_roots = if cfg!(target_os = "macos") {
894            vec![PathBuf::from("/Library"), PathBuf::from("/System")]
895        } else {
896            let sysroot = config
897                .env_var_os("PKG_CONFIG_SYSROOT_DIR")
898                .or_else(|| config.env_var_os("SYSROOT"))
899                .map(PathBuf::from);
900
901            if cfg!(target_os = "windows") {
902                if let Some(sysroot) = sysroot {
903                    vec![sysroot]
904                } else {
905                    vec![]
906                }
907            } else {
908                vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))]
909            }
910        };
911
912        let mut dirs = Vec::new();
913        let statik = config.is_static(name);
914
915        let words = split_flags(output);
916
917        // Handle single-character arguments like `-I/usr/include`
918        let parts = words
919            .iter()
920            .filter(|l| l.len() > 2)
921            .map(|arg| (&arg[0..2], &arg[2..]));
922        for (flag, val) in parts {
923            match flag {
924                "-L" => {
925                    let meta = format!("rustc-link-search=native={}", val);
926                    config.print_metadata(&meta);
927                    dirs.push(PathBuf::from(val));
928                    self.link_paths.push(PathBuf::from(val));
929                }
930                "-F" => {
931                    let meta = format!("rustc-link-search=framework={}", val);
932                    config.print_metadata(&meta);
933                    self.framework_paths.push(PathBuf::from(val));
934                }
935                "-I" => {
936                    self.include_paths.push(PathBuf::from(val));
937                }
938                "-l" => {
939                    // These are provided by the CRT with MSVC
940                    if is_msvc && ["m", "c", "pthread"].contains(&val) {
941                        continue;
942                    }
943
944                    if val.starts_with(':') {
945                        // Pass this flag to linker directly.
946                        let meta = format!("rustc-link-arg={}{}", flag, val);
947                        config.print_metadata(&meta);
948                    } else if statik && is_static_available(val, &system_roots, &dirs) {
949                        let meta = format!("rustc-link-lib=static={}", val);
950                        config.print_metadata(&meta);
951                    } else {
952                        let meta = format!("rustc-link-lib={}", val);
953                        config.print_metadata(&meta);
954                    }
955
956                    self.libs.push(val.to_string());
957                }
958                "-D" => {
959                    let mut iter = val.split('=');
960                    self.defines.insert(
961                        iter.next().unwrap().to_owned(),
962                        iter.next().map(|s| s.to_owned()),
963                    );
964                }
965                "-u" => {
966                    let meta = format!("rustc-link-arg=-Wl,-u,{}", val);
967                    config.print_metadata(&meta);
968                }
969                _ => {}
970            }
971        }
972
973        // Handle multi-character arguments with space-separated value like `-framework foo`
974        let mut iter = words.iter().flat_map(|arg| {
975            if let Some(arg) = arg.strip_prefix("-Wl,") {
976                arg.split(',').collect()
977            } else {
978                vec![arg.as_ref()]
979            }
980        });
981        while let Some(part) = iter.next() {
982            match part {
983                "-framework" => {
984                    if let Some(lib) = iter.next() {
985                        let meta = format!("rustc-link-lib=framework={}", lib);
986                        config.print_metadata(&meta);
987                        self.frameworks.push(lib.to_string());
988                    }
989                }
990                "-isystem" | "-iquote" | "-idirafter" => {
991                    if let Some(inc) = iter.next() {
992                        self.include_paths.push(PathBuf::from(inc));
993                    }
994                }
995                "-undefined" | "--undefined" => {
996                    if let Some(symbol) = iter.next() {
997                        let meta = format!("rustc-link-arg=-Wl,{},{}", part, symbol);
998                        config.print_metadata(&meta);
999                    }
1000                }
1001                _ => {
1002                    let path = std::path::Path::new(part);
1003                    if path.is_file() {
1004                        // Cargo doesn't have a means to directly specify a file path to link,
1005                        // so split up the path into the parent directory and library name.
1006                        // TODO: pass file path directly when link-arg library type is stabilized
1007                        // https://github.com/rust-lang/rust/issues/99427
1008                        if let (Some(dir), Some(file_name), Ok(target)) =
1009                            (path.parent(), path.file_name(), &target)
1010                        {
1011                            match Self::extract_lib_from_filename(
1012                                target,
1013                                &file_name.to_string_lossy(),
1014                            ) {
1015                                Some(lib_basename) => {
1016                                    let link_search =
1017                                        format!("rustc-link-search={}", dir.display());
1018                                    config.print_metadata(&link_search);
1019
1020                                    let link_lib = format!("rustc-link-lib={}", lib_basename);
1021                                    config.print_metadata(&link_lib);
1022                                    self.link_files.push(PathBuf::from(path));
1023                                }
1024                                None => {
1025                                    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);
1026                                }
1027                            }
1028                        }
1029                    }
1030                }
1031            }
1032        }
1033
1034        let linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,"));
1035        for option in linker_options {
1036            let mut pop = false;
1037            let mut ld_option = vec![];
1038            for subopt in option[4..].split(',') {
1039                if pop {
1040                    pop = false;
1041                    continue;
1042                }
1043
1044                if subopt == "-framework" {
1045                    pop = true;
1046                    continue;
1047                }
1048
1049                ld_option.push(subopt);
1050            }
1051
1052            let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(","));
1053            config.print_metadata(&meta);
1054
1055            self.ld_args
1056                .push(ld_option.into_iter().map(String::from).collect());
1057        }
1058    }
1059
1060    fn parse_modversion(&mut self, output: &str) {
1061        self.version.push_str(output.lines().next().unwrap().trim());
1062    }
1063}
1064
1065fn envify(name: &str) -> String {
1066    name.chars()
1067        .map(|c| c.to_ascii_uppercase())
1068        .map(|c| if c == '-' { '_' } else { c })
1069        .collect()
1070}
1071
1072/// System libraries should only be linked dynamically
1073fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool {
1074    let libnames = {
1075        let mut names = vec![format!("lib{}.a", name)];
1076
1077        if cfg!(target_os = "windows") {
1078            names.push(format!("{}.lib", name));
1079        }
1080
1081        names
1082    };
1083
1084    dirs.iter().any(|dir| {
1085        let library_exists = libnames.iter().any(|libname| dir.join(libname).exists());
1086        library_exists && !system_roots.iter().any(|sys| dir.starts_with(sys))
1087    })
1088}
1089
1090/// Split output produced by pkg-config --cflags and / or --libs into separate flags.
1091///
1092/// Backslash in output is used to preserve literal meaning of following byte.  Different words are
1093/// separated by unescaped space. Other whitespace characters generally should not occur unescaped
1094/// at all, apart from the newline at the end of output. For compatibility with what others
1095/// consumers of pkg-config output would do in this scenario, they are used here for splitting as
1096/// well.
1097fn split_flags(output: &[u8]) -> Vec<String> {
1098    let mut word = Vec::new();
1099    let mut words = Vec::new();
1100    let mut escaped = false;
1101
1102    for &b in output {
1103        match b {
1104            _ if escaped => {
1105                escaped = false;
1106                word.push(b);
1107            }
1108            b'\\' => escaped = true,
1109            b'\t' | b'\n' | b'\r' | b' ' => {
1110                if !word.is_empty() {
1111                    words.push(String::from_utf8(word).unwrap());
1112                    word = Vec::new();
1113                }
1114            }
1115            _ => word.push(b),
1116        }
1117    }
1118
1119    if !word.is_empty() {
1120        words.push(String::from_utf8(word).unwrap());
1121    }
1122
1123    words
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128    use super::*;
1129
1130    #[test]
1131    #[cfg(target_os = "macos")]
1132    fn system_library_mac_test() {
1133        use std::path::Path;
1134
1135        let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")];
1136
1137        assert!(!is_static_available(
1138            "PluginManager",
1139            &system_roots,
1140            &[PathBuf::from("/Library/Frameworks")]
1141        ));
1142        assert!(!is_static_available(
1143            "python2.7",
1144            &system_roots,
1145            &[PathBuf::from(
1146                "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config"
1147            )]
1148        ));
1149        assert!(!is_static_available(
1150            "ffi_convenience",
1151            &system_roots,
1152            &[PathBuf::from(
1153                "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs"
1154            )]
1155        ));
1156
1157        // Homebrew is in /usr/local, and it's not a part of the OS
1158        if Path::new("/usr/local/lib/libpng16.a").exists() {
1159            assert!(is_static_available(
1160                "png16",
1161                &system_roots,
1162                &[PathBuf::from("/usr/local/lib")]
1163            ));
1164
1165            let libpng = Config::new()
1166                .range_version("1".."99")
1167                .probe("libpng16")
1168                .unwrap();
1169            assert!(libpng.version.find('\n').is_none());
1170        }
1171    }
1172
1173    #[test]
1174    #[cfg(target_os = "linux")]
1175    fn system_library_linux_test() {
1176        assert!(!is_static_available(
1177            "util",
1178            &[PathBuf::from("/usr")],
1179            &[PathBuf::from("/usr/lib/x86_64-linux-gnu")]
1180        ));
1181        assert!(!is_static_available(
1182            "dialog",
1183            &[PathBuf::from("/usr")],
1184            &[PathBuf::from("/usr/lib")]
1185        ));
1186    }
1187
1188    fn test_library_filename(target: &str, filename: &str) {
1189        assert_eq!(
1190            Library::extract_lib_from_filename(target, filename),
1191            Some("foo")
1192        );
1193    }
1194
1195    #[test]
1196    fn link_filename_linux() {
1197        let target = "x86_64-unknown-linux-gnu";
1198        test_library_filename(target, "libfoo.a");
1199        test_library_filename(target, "libfoo.so");
1200    }
1201
1202    #[test]
1203    fn link_filename_apple() {
1204        let target = "x86_64-apple-darwin";
1205        test_library_filename(target, "libfoo.a");
1206        test_library_filename(target, "libfoo.so");
1207        test_library_filename(target, "libfoo.dylib");
1208    }
1209
1210    #[test]
1211    fn link_filename_msvc() {
1212        let target = "x86_64-pc-windows-msvc";
1213        // static and dynamic libraries have the same .lib suffix
1214        test_library_filename(target, "foo.lib");
1215    }
1216
1217    #[test]
1218    fn link_filename_mingw() {
1219        let target = "x86_64-pc-windows-gnu";
1220        test_library_filename(target, "foo.lib");
1221        test_library_filename(target, "libfoo.a");
1222        test_library_filename(target, "foo.dll");
1223        test_library_filename(target, "foo.dll.a");
1224    }
1225}