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}
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                // Show pkg-config's own error output, this often contains the
355                // actual reason for the failure (e.g. a missing transitive
356                // dependency) which is more specific than our generic message.
357                let stderr = String::from_utf8_lossy(&output.stderr);
358                if !stderr.is_empty() {
359                    writeln!(f, "pkg-config output:")?;
360                    for line in stderr.lines() {
361                        writeln!(f, "  {}", line)?;
362                    }
363                    writeln!(f)?;
364                }
365
366                // Explain how it was caused
367                writeln!(
368                    f,
369                    "The system library `{}` required by crate `{}` was not found.",
370                    name, crate_name
371                )?;
372                writeln!(
373                    f,
374                    "The file `{}.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.",
375                    name
376                )?;
377
378                // There will be no status code if terminated by signal
379                if let Some(_code) = output.status.code() {
380                    // Nix uses a wrapper script for pkg-config that sets the custom
381                    // environment variable PKG_CONFIG_PATH_FOR_TARGET
382                    let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"];
383
384                    // Find a search path to use
385                    let mut search_data = None;
386                    for location in search_locations.iter() {
387                        if let Ok(search_path) = env::var(location) {
388                            search_data = Some((location, search_path));
389                            break;
390                        }
391                    }
392
393                    // Guess the most reasonable course of action
394                    let hint = if let Some((search_location, search_path)) = search_data {
395                        writeln!(
396                            f,
397                            "{} contains the following:\n{}",
398                            search_location,
399                            search_path
400                                .split(':')
401                                .map(|path| format!("    - {}", path))
402                                .collect::<Vec<String>>()
403                                .join("\n"),
404                        )?;
405
406                        format!("you may need to install a package such as {name}, {name}-dev or {name}-devel.", name=name)
407                    } else {
408                        // Even on Nix, setting PKG_CONFIG_PATH seems to be a viable option
409                        writeln!(f, "The PKG_CONFIG_PATH environment variable is not set.")?;
410
411                        format!(
412                            "if you have installed the library, try setting PKG_CONFIG_PATH to the directory containing `{}.pc`.",
413                            name
414                        )
415                    };
416
417                    // Try and nudge the user in the right direction so they don't get stuck
418                    writeln!(f, "\nHINT: {}", hint)?;
419                }
420
421                Ok(())
422            }
423            Error::Failure {
424                ref command,
425                ref output,
426            } => {
427                write!(
428                    f,
429                    "`{}` did not exit successfully: {}",
430                    command, output.status
431                )?;
432                format_output(output, f)
433            }
434            Error::__Nonexhaustive => panic!(),
435        }
436    }
437}
438
439fn format_output(output: &Output, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440    let stdout = String::from_utf8_lossy(&output.stdout);
441    if !stdout.is_empty() {
442        write!(f, "\n--- stdout\n{}", stdout)?;
443    }
444    let stderr = String::from_utf8_lossy(&output.stderr);
445    if !stderr.is_empty() {
446        write!(f, "\n--- stderr\n{}", stderr)?;
447    }
448    Ok(())
449}
450
451/// Deprecated in favor of the probe_library function
452#[doc(hidden)]
453pub fn find_library(name: &str) -> Result<Library, String> {
454    probe_library(name).map_err(|e| e.to_string())
455}
456
457/// Simple shortcut for using all default options for finding a library.
458pub fn probe_library(name: &str) -> Result<Library, Error> {
459    Config::new().probe(name)
460}
461
462#[doc(hidden)]
463#[deprecated(note = "use config.target_supported() instance method instead")]
464pub fn target_supported() -> bool {
465    Config::new().target_supported()
466}
467
468/// Run `pkg-config` to get the value of a variable from a package using
469/// `--variable`.
470///
471/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are
472/// returned by `pkg-config --variable`, which makes them unsuitable to use
473/// during cross-compilation unless specifically designed to be used
474/// at that time.
475pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> {
476    let arg = format!("--variable={}", variable);
477    let cfg = Config::new();
478    let out = cfg.run(package, &[&arg])?;
479    Ok(str::from_utf8(&out).unwrap().trim_end().to_owned())
480}
481
482impl Config {
483    /// Creates a new set of configuration options which are all initially set
484    /// to "blank".
485    pub fn new() -> Config {
486        Config {
487            statik: None,
488            min_version: Bound::Unbounded,
489            max_version: Bound::Unbounded,
490            extra_args: vec![],
491            print_system_cflags: true,
492            print_system_libs: true,
493            cargo_metadata: true,
494            env_metadata: true,
495        }
496    }
497
498    /// Indicate whether the `--static` flag should be passed.
499    ///
500    /// This will override the inference from environment variables described in
501    /// the crate documentation.
502    pub fn statik(&mut self, statik: bool) -> &mut Config {
503        self.statik = Some(statik);
504        self
505    }
506
507    /// Indicate that the library must be at least version `vers`.
508    pub fn atleast_version(&mut self, vers: &str) -> &mut Config {
509        self.min_version = Bound::Included(vers.to_string());
510        self.max_version = Bound::Unbounded;
511        self
512    }
513
514    /// Indicate that the library must be equal to version `vers`.
515    pub fn exactly_version(&mut self, vers: &str) -> &mut Config {
516        self.min_version = Bound::Included(vers.to_string());
517        self.max_version = Bound::Included(vers.to_string());
518        self
519    }
520
521    /// Indicate that the library's version must be in `range`.
522    pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config
523    where
524        R: RangeBounds<&'a str>,
525    {
526        self.min_version = match range.start_bound() {
527            Bound::Included(vers) => Bound::Included(vers.to_string()),
528            Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
529            Bound::Unbounded => Bound::Unbounded,
530        };
531        self.max_version = match range.end_bound() {
532            Bound::Included(vers) => Bound::Included(vers.to_string()),
533            Bound::Excluded(vers) => Bound::Excluded(vers.to_string()),
534            Bound::Unbounded => Bound::Unbounded,
535        };
536        self
537    }
538
539    /// Add an argument to pass to pkg-config.
540    ///
541    /// It's placed after all of the arguments generated by this library.
542    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config {
543        self.extra_args.push(arg.as_ref().to_os_string());
544        self
545    }
546
547    /// Define whether metadata should be emitted for cargo allowing it to
548    /// automatically link the binary. Defaults to `true`.
549    pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config {
550        self.cargo_metadata = cargo_metadata;
551        self
552    }
553
554    /// Define whether metadata should be emitted for cargo allowing to
555    /// automatically rebuild when environment variables change. Defaults to
556    /// `true`.
557    pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config {
558        self.env_metadata = env_metadata;
559        self
560    }
561
562    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment
563    /// variable.
564    ///
565    /// This env var is enabled by default.
566    pub fn print_system_libs(&mut self, print: bool) -> &mut Config {
567        self.print_system_libs = print;
568        self
569    }
570
571    /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment
572    /// variable.
573    ///
574    /// This env var is enabled by default.
575    pub fn print_system_cflags(&mut self, print: bool) -> &mut Config {
576        self.print_system_cflags = print;
577        self
578    }
579
580    /// Deprecated in favor of the `probe` function
581    #[doc(hidden)]
582    pub fn find(&self, name: &str) -> Result<Library, String> {
583        self.probe(name).map_err(|e| e.to_string())
584    }
585
586    /// Run `pkg-config` to find the library `name`.
587    ///
588    /// This will use all configuration previously set to specify how
589    /// `pkg-config` is run.
590    pub fn probe(&self, name: &str) -> Result<Library, Error> {
591        let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name));
592        if self.env_var_os(&abort_var_name).is_some() {
593            return Err(Error::EnvNoPkgConfig(abort_var_name));
594        } else if !self.target_supported() {
595            return Err(Error::CrossCompilation);
596        }
597
598        let mut library = Library::new();
599
600        let output = self
601            .run(name, &["--libs", "--cflags"])
602            .map_err(|e| match e {
603                Error::Failure { command, output } => Error::ProbeFailure {
604                    name: name.to_owned(),
605                    command,
606                    output,
607                },
608                other => other,
609            })?;
610        library.parse_libs_cflags(name, &output, self);
611
612        let output = self.run(name, &["--modversion"])?;
613        library.parse_modversion(str::from_utf8(&output).unwrap());
614
615        Ok(library)
616    }
617
618    /// True if pkg-config is used for the host system, or configured for cross-compilation
619    pub fn target_supported(&self) -> bool {
620        let target = env::var_os("TARGET").unwrap_or_default();
621        let host = env::var_os("HOST").unwrap_or_default();
622
623        // Only use pkg-config in host == target situations by default (allowing an
624        // override).
625        if host == target {
626            return true;
627        }
628
629        // pkg-config may not be aware of cross-compilation, and require
630        // a wrapper script that sets up platform-specific prefixes.
631        match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") {
632            // don't use pkg-config if explicitly disabled
633            Some(ref val) if val == "0" => false,
634            Some(_) => true,
635            None => {
636                // if not disabled, and pkg-config is customized,
637                // then assume it's prepared for cross-compilation
638                self.targeted_env_var("PKG_CONFIG").is_some()
639                    || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some()
640            }
641        }
642    }
643
644    /// Deprecated in favor of the top level `get_variable` function
645    #[doc(hidden)]
646    pub fn get_variable(package: &str, variable: &str) -> Result<String, String> {
647        get_variable(package, variable).map_err(|e| e.to_string())
648    }
649
650    fn targeted_env_var(&self, var_base: &str) -> Option<OsString> {
651        match (env::var("TARGET"), env::var("HOST")) {
652            (Ok(target), Ok(host)) => {
653                let kind = if host == target { "HOST" } else { "TARGET" };
654                let target_u = target.replace('-', "_");
655
656                self.env_var_os(&format!("{}_{}", var_base, target))
657                    .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u)))
658                    .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base)))
659                    .or_else(|| self.env_var_os(var_base))
660            }
661            (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => {
662                self.env_var_os(var_base)
663            }
664            (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => {
665                panic!(
666                    "HOST or TARGET environment variable is not valid unicode: {:?}",
667                    s
668                )
669            }
670        }
671    }
672
673    fn env_var_os(&self, name: &str) -> Option<OsString> {
674        if self.env_metadata {
675            println!("cargo:rerun-if-env-changed={}", name);
676        }
677        env::var_os(name)
678    }
679
680    fn is_static(&self, name: &str) -> bool {
681        self.statik.unwrap_or_else(|| self.infer_static(name))
682    }
683
684    fn run(&self, name: &str, args: &[&str]) -> Result<Vec<u8>, Error> {
685        let pkg_config_exe = self.targeted_env_var("PKG_CONFIG");
686        let fallback_exe = if pkg_config_exe.is_none() {
687            Some(OsString::from("pkgconf"))
688        } else {
689            None
690        };
691        let exe = pkg_config_exe.unwrap_or_else(|| OsString::from("pkg-config"));
692
693        let mut cmd = self.command(exe, name, args);
694
695        match cmd.output().or_else(|e| {
696            if let Some(exe) = fallback_exe {
697                self.command(exe, name, args).output()
698            } else {
699                Err(e)
700            }
701        }) {
702            Ok(output) => {
703                if output.status.success() {
704                    Ok(output.stdout)
705                } else {
706                    Err(Error::Failure {
707                        command: format!("{}", cmd),
708                        output,
709                    })
710                }
711            }
712            Err(cause) => Err(Error::Command {
713                command: format!("{}", cmd),
714                cause,
715            }),
716        }
717    }
718
719    fn command(&self, exe: OsString, name: &str, args: &[&str]) -> WrappedCommand {
720        let mut cmd = WrappedCommand::new(exe);
721        if self.is_static(name) {
722            cmd.arg("--static");
723        }
724        cmd.args(args).args(&self.extra_args);
725
726        if let Some(value) = self.targeted_env_var("PKG_CONFIG_PATH") {
727            cmd.env("PKG_CONFIG_PATH", value);
728        }
729        if let Some(value) = self.targeted_env_var("PKG_CONFIG_LIBDIR") {
730            cmd.env("PKG_CONFIG_LIBDIR", value);
731        }
732        if let Some(value) = self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR") {
733            cmd.env("PKG_CONFIG_SYSROOT_DIR", value);
734        }
735        if self.print_system_libs {
736            cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1");
737        }
738        if self.print_system_cflags {
739            cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1");
740        }
741        cmd.arg(name);
742        match self.min_version {
743            Bound::Included(ref version) => {
744                cmd.arg(&format!("{} >= {}", name, version));
745            }
746            Bound::Excluded(ref version) => {
747                cmd.arg(&format!("{} > {}", name, version));
748            }
749            _ => (),
750        }
751        match self.max_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        cmd
761    }
762
763    fn print_metadata(&self, s: &str) {
764        if self.cargo_metadata {
765            println!("cargo:{}", s);
766        }
767    }
768
769    fn infer_static(&self, name: &str) -> bool {
770        let name = envify(name);
771        if self.env_var_os(&format!("{}_STATIC", name)).is_some() {
772            true
773        } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() {
774            false
775        } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() {
776            true
777        } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() {
778            false
779        } else {
780            false
781        }
782    }
783}
784
785// Implement Default manually since Bound does not implement Default.
786impl Default for Config {
787    fn default() -> Config {
788        Config {
789            statik: None,
790            min_version: Bound::Unbounded,
791            max_version: Bound::Unbounded,
792            extra_args: vec![],
793            print_system_cflags: false,
794            print_system_libs: false,
795            cargo_metadata: false,
796            env_metadata: false,
797        }
798    }
799}
800
801impl Library {
802    fn new() -> Library {
803        Library {
804            libs: Vec::new(),
805            link_paths: Vec::new(),
806            link_files: Vec::new(),
807            include_paths: Vec::new(),
808            ld_args: Vec::new(),
809            frameworks: Vec::new(),
810            framework_paths: Vec::new(),
811            defines: HashMap::new(),
812            version: String::new(),
813            _priv: (),
814        }
815    }
816
817    /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories)
818    /// using target-specific logic.
819    fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> {
820        fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> {
821            for suffix in suffixes {
822                if filename.ends_with(suffix) {
823                    return Some(&filename[..filename.len() - suffix.len()]);
824                }
825            }
826            None
827        }
828
829        let prefix = "lib";
830        if target.contains("windows") {
831            if target.contains("gnu") && filename.starts_with(prefix) {
832                // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc,
833                // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it
834                // receives via the -l command line argument before passing it to the linker:
835                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446
836                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457
837                // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs.
838                // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove
839                // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix.
840                // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll
841                let filename = &filename[prefix.len()..];
842                return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
843            } else {
844                // According to link.exe documentation:
845                // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170
846                //
847                //   LINK doesn't use file extensions to make assumptions about the contents of a file.
848                //   Instead, LINK examines each input file to determine what kind of file it is.
849                //
850                // However, rustc appends `.lib` to the string it receives from the -l command line argument,
851                // which it receives from Cargo via cargo:rustc-link-lib:
852                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828
853                // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843
854                // So the only file extension that works for MSVC targets is `.lib`
855                // However, for externally created libraries, there's no
856                // guarantee that the extension is ".lib" so we need to
857                // consider all options.
858                // See:
859                // https://github.com/mesonbuild/meson/issues/8153
860                // https://github.com/rust-lang/rust/issues/114013
861                return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]);
862            }
863        } else if target.contains("apple") {
864            if filename.starts_with(prefix) {
865                let filename = &filename[prefix.len()..];
866                return test_suffixes(filename, &[".a", ".so", ".dylib"]);
867            }
868            return None;
869        } else {
870            if filename.starts_with(prefix) {
871                let filename = &filename[prefix.len()..];
872                return test_suffixes(filename, &[".a", ".so"]);
873            }
874            return None;
875        }
876    }
877
878    fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) {
879        let target = env::var("TARGET");
880        let is_msvc = target
881            .as_ref()
882            .map(|target| target.contains("msvc"))
883            .unwrap_or(false);
884
885        let system_roots = if cfg!(target_os = "macos") {
886            vec![PathBuf::from("/Library"), PathBuf::from("/System")]
887        } else {
888            let sysroot = config
889                .env_var_os("PKG_CONFIG_SYSROOT_DIR")
890                .or_else(|| config.env_var_os("SYSROOT"))
891                .map(PathBuf::from);
892
893            if cfg!(target_os = "windows") {
894                if let Some(sysroot) = sysroot {
895                    vec![sysroot]
896                } else {
897                    vec![]
898                }
899            } else {
900                vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))]
901            }
902        };
903
904        let mut dirs = Vec::new();
905        let statik = config.is_static(name);
906
907        let words = split_flags(output);
908
909        // Handle single-character arguments like `-I/usr/include`
910        let parts = words
911            .iter()
912            .filter(|l| l.len() > 2)
913            .map(|arg| (&arg[0..2], &arg[2..]));
914        for (flag, val) in parts {
915            match flag {
916                "-L" => {
917                    let meta = format!("rustc-link-search=native={}", val);
918                    config.print_metadata(&meta);
919                    dirs.push(PathBuf::from(val));
920                    self.link_paths.push(PathBuf::from(val));
921                }
922                "-F" => {
923                    let meta = format!("rustc-link-search=framework={}", val);
924                    config.print_metadata(&meta);
925                    self.framework_paths.push(PathBuf::from(val));
926                }
927                "-I" => {
928                    self.include_paths.push(PathBuf::from(val));
929                }
930                "-l" => {
931                    // These are provided by the CRT with MSVC
932                    if is_msvc && ["m", "c", "pthread"].contains(&val) {
933                        continue;
934                    }
935
936                    if val.starts_with(':') {
937                        // Pass this flag to linker directly.
938                        let meta = format!("rustc-link-arg={}{}", flag, val);
939                        config.print_metadata(&meta);
940                    } else if statik && is_static_available(val, &system_roots, &dirs) {
941                        let meta = format!("rustc-link-lib=static={}", val);
942                        config.print_metadata(&meta);
943                    } else {
944                        let meta = format!("rustc-link-lib={}", val);
945                        config.print_metadata(&meta);
946                    }
947
948                    self.libs.push(val.to_string());
949                }
950                "-D" => {
951                    let mut iter = val.split('=');
952                    self.defines.insert(
953                        iter.next().unwrap().to_owned(),
954                        iter.next().map(|s| s.to_owned()),
955                    );
956                }
957                "-u" => {
958                    let meta = format!("rustc-link-arg=-Wl,-u,{}", val);
959                    config.print_metadata(&meta);
960                }
961                _ => {}
962            }
963        }
964
965        // Handle multi-character arguments with space-separated value like `-framework foo`
966        let mut iter = words.iter().flat_map(|arg| {
967            if arg.starts_with("-Wl,") {
968                arg[4..].split(',').collect()
969            } else {
970                vec![arg.as_ref()]
971            }
972        });
973        while let Some(part) = iter.next() {
974            match part {
975                "-framework" => {
976                    if let Some(lib) = iter.next() {
977                        let meta = format!("rustc-link-lib=framework={}", lib);
978                        config.print_metadata(&meta);
979                        self.frameworks.push(lib.to_string());
980                    }
981                }
982                "-isystem" | "-iquote" | "-idirafter" => {
983                    if let Some(inc) = iter.next() {
984                        self.include_paths.push(PathBuf::from(inc));
985                    }
986                }
987                "-undefined" | "--undefined" => {
988                    if let Some(symbol) = iter.next() {
989                        let meta = format!("rustc-link-arg=-Wl,{},{}", part, symbol);
990                        config.print_metadata(&meta);
991                    }
992                }
993                _ => {
994                    let path = std::path::Path::new(part);
995                    if path.is_file() {
996                        // Cargo doesn't have a means to directly specify a file path to link,
997                        // so split up the path into the parent directory and library name.
998                        // TODO: pass file path directly when link-arg library type is stabilized
999                        // https://github.com/rust-lang/rust/issues/99427
1000                        if let (Some(dir), Some(file_name), Ok(target)) =
1001                            (path.parent(), path.file_name(), &target)
1002                        {
1003                            match Self::extract_lib_from_filename(
1004                                target,
1005                                &file_name.to_string_lossy(),
1006                            ) {
1007                                Some(lib_basename) => {
1008                                    let link_search =
1009                                        format!("rustc-link-search={}", dir.display());
1010                                    config.print_metadata(&link_search);
1011
1012                                    let link_lib = format!("rustc-link-lib={}", lib_basename);
1013                                    config.print_metadata(&link_lib);
1014                                    self.link_files.push(PathBuf::from(path));
1015                                }
1016                                None => {
1017                                    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);
1018                                }
1019                            }
1020                        }
1021                    }
1022                }
1023            }
1024        }
1025
1026        let linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,"));
1027        for option in linker_options {
1028            let mut pop = false;
1029            let mut ld_option = vec![];
1030            for subopt in option[4..].split(',') {
1031                if pop {
1032                    pop = false;
1033                    continue;
1034                }
1035
1036                if subopt == "-framework" {
1037                    pop = true;
1038                    continue;
1039                }
1040
1041                ld_option.push(subopt);
1042            }
1043
1044            let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(","));
1045            config.print_metadata(&meta);
1046
1047            self.ld_args
1048                .push(ld_option.into_iter().map(String::from).collect());
1049        }
1050    }
1051
1052    fn parse_modversion(&mut self, output: &str) {
1053        self.version.push_str(output.lines().next().unwrap().trim());
1054    }
1055}
1056
1057fn envify(name: &str) -> String {
1058    name.chars()
1059        .map(|c| c.to_ascii_uppercase())
1060        .map(|c| if c == '-' { '_' } else { c })
1061        .collect()
1062}
1063
1064/// System libraries should only be linked dynamically
1065fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool {
1066    let libnames = {
1067        let mut names = vec![format!("lib{}.a", name)];
1068
1069        if cfg!(target_os = "windows") {
1070            names.push(format!("{}.lib", name));
1071        }
1072
1073        names
1074    };
1075
1076    dirs.iter().any(|dir| {
1077        let library_exists = libnames.iter().any(|libname| dir.join(&libname).exists());
1078        library_exists && !system_roots.iter().any(|sys| dir.starts_with(sys))
1079    })
1080}
1081
1082/// Split output produced by pkg-config --cflags and / or --libs into separate flags.
1083///
1084/// Backslash in output is used to preserve literal meaning of following byte.  Different words are
1085/// separated by unescaped space. Other whitespace characters generally should not occur unescaped
1086/// at all, apart from the newline at the end of output. For compatibility with what others
1087/// consumers of pkg-config output would do in this scenario, they are used here for splitting as
1088/// well.
1089fn split_flags(output: &[u8]) -> Vec<String> {
1090    let mut word = Vec::new();
1091    let mut words = Vec::new();
1092    let mut escaped = false;
1093
1094    for &b in output {
1095        match b {
1096            _ if escaped => {
1097                escaped = false;
1098                word.push(b);
1099            }
1100            b'\\' => escaped = true,
1101            b'\t' | b'\n' | b'\r' | b' ' => {
1102                if !word.is_empty() {
1103                    words.push(String::from_utf8(word).unwrap());
1104                    word = Vec::new();
1105                }
1106            }
1107            _ => word.push(b),
1108        }
1109    }
1110
1111    if !word.is_empty() {
1112        words.push(String::from_utf8(word).unwrap());
1113    }
1114
1115    words
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120    use super::*;
1121
1122    #[test]
1123    #[cfg(target_os = "macos")]
1124    fn system_library_mac_test() {
1125        use std::path::Path;
1126
1127        let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")];
1128
1129        assert!(!is_static_available(
1130            "PluginManager",
1131            &system_roots,
1132            &[PathBuf::from("/Library/Frameworks")]
1133        ));
1134        assert!(!is_static_available(
1135            "python2.7",
1136            &system_roots,
1137            &[PathBuf::from(
1138                "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config"
1139            )]
1140        ));
1141        assert!(!is_static_available(
1142            "ffi_convenience",
1143            &system_roots,
1144            &[PathBuf::from(
1145                "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs"
1146            )]
1147        ));
1148
1149        // Homebrew is in /usr/local, and it's not a part of the OS
1150        if Path::new("/usr/local/lib/libpng16.a").exists() {
1151            assert!(is_static_available(
1152                "png16",
1153                &system_roots,
1154                &[PathBuf::from("/usr/local/lib")]
1155            ));
1156
1157            let libpng = Config::new()
1158                .range_version("1".."99")
1159                .probe("libpng16")
1160                .unwrap();
1161            assert!(libpng.version.find('\n').is_none());
1162        }
1163    }
1164
1165    #[test]
1166    #[cfg(target_os = "linux")]
1167    fn system_library_linux_test() {
1168        assert!(!is_static_available(
1169            "util",
1170            &[PathBuf::from("/usr")],
1171            &[PathBuf::from("/usr/lib/x86_64-linux-gnu")]
1172        ));
1173        assert!(!is_static_available(
1174            "dialog",
1175            &[PathBuf::from("/usr")],
1176            &[PathBuf::from("/usr/lib")]
1177        ));
1178    }
1179
1180    fn test_library_filename(target: &str, filename: &str) {
1181        assert_eq!(
1182            Library::extract_lib_from_filename(target, filename),
1183            Some("foo")
1184        );
1185    }
1186
1187    #[test]
1188    fn link_filename_linux() {
1189        let target = "x86_64-unknown-linux-gnu";
1190        test_library_filename(target, "libfoo.a");
1191        test_library_filename(target, "libfoo.so");
1192    }
1193
1194    #[test]
1195    fn link_filename_apple() {
1196        let target = "x86_64-apple-darwin";
1197        test_library_filename(target, "libfoo.a");
1198        test_library_filename(target, "libfoo.so");
1199        test_library_filename(target, "libfoo.dylib");
1200    }
1201
1202    #[test]
1203    fn link_filename_msvc() {
1204        let target = "x86_64-pc-windows-msvc";
1205        // static and dynamic libraries have the same .lib suffix
1206        test_library_filename(target, "foo.lib");
1207    }
1208
1209    #[test]
1210    fn link_filename_mingw() {
1211        let target = "x86_64-pc-windows-gnu";
1212        test_library_filename(target, "foo.lib");
1213        test_library_filename(target, "libfoo.a");
1214        test_library_filename(target, "foo.dll");
1215        test_library_filename(target, "foo.dll.a");
1216    }
1217}