diff options
Diffstat (limited to 'third_party/rust/pkg-config')
-rw-r--r-- | third_party/rust/pkg-config/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/pkg-config/CHANGELOG.md | 163 | ||||
-rw-r--r-- | third_party/rust/pkg-config/Cargo.toml | 27 | ||||
-rw-r--r-- | third_party/rust/pkg-config/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/pkg-config/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/pkg-config/README.md | 79 | ||||
-rw-r--r-- | third_party/rust/pkg-config/src/lib.rs | 972 | ||||
-rw-r--r-- | third_party/rust/pkg-config/tests/escape.pc | 5 | ||||
-rw-r--r-- | third_party/rust/pkg-config/tests/foo.pc | 16 | ||||
-rw-r--r-- | third_party/rust/pkg-config/tests/framework.pc | 16 | ||||
-rw-r--r-- | third_party/rust/pkg-config/tests/rpath.pc | 7 | ||||
-rw-r--r-- | third_party/rust/pkg-config/tests/test.rs | 323 |
12 files changed, 1835 insertions, 0 deletions
diff --git a/third_party/rust/pkg-config/.cargo-checksum.json b/third_party/rust/pkg-config/.cargo-checksum.json new file mode 100644 index 0000000000..c5e73aa5cb --- /dev/null +++ b/third_party/rust/pkg-config/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"bc1a9e53c60e64a9f30e81109eeae1273ee1f574291ff712c2cfa0ec78155c82","Cargo.toml":"e2faa7f58ba9688a2f1ab2708632b4f13d0c87e769c5909b7a30facad4d648de","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"37f11a56c969237dcfd15368e96bf686ec92b0254e38fb84636e178d632c0492","src/lib.rs":"04de2653405cdbe3c662fb8e31ea3dcab7431b32dbfbd3243075de6cb5f84588","tests/escape.pc":"00caa4136799dbe5bd504239ba90d1156c12def365c8d761da319fe8a83b398e","tests/foo.pc":"4a1c442c5d1c10761ea1644f8fd58f93cc5a706391bc67b04c243bbd35d70d79","tests/framework.pc":"304fdb6cea92973650e410ab1f70ce1ebeb7718af3f139e806efbf182acd565c","tests/rpath.pc":"424a844e844edfef02692492def9864833391f581338962946646989a69c1180","tests/test.rs":"dc0c27302c599524c06be5b807e8e371f60c8296e9da280677c79db1a3fe146a"},"package":"6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"}
\ No newline at end of file diff --git a/third_party/rust/pkg-config/CHANGELOG.md b/third_party/rust/pkg-config/CHANGELOG.md new file mode 100644 index 0000000000..3ea463d030 --- /dev/null +++ b/third_party/rust/pkg-config/CHANGELOG.md @@ -0,0 +1,163 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.3.26] - 2022-10-26 + +### Added + +- Support for handling full paths to libraries in addition to normal `-l` + linker flags (#134). + +## [0.3.25] - 2022-03-31 + +### Added + +- Support for parsing `-Wl` linker arguments from the `Libs` lines and + passing them to the linker as well as making them available via + `Library::ld_args` (#131). + +### Changed + +- Use SPDX license format and remove obsolete badge info (#129). + +## [0.3.24] - 2021-12-11 + +### Fixed + +- Re-add `target_supported()`, which was accidentally removed in 0.3.15 (#128). + +## [0.3.23] - 2021-12-06 + +### Changed + +- Improve error messages when a `pkg-config` package can't be found (#127). + +## [0.3.22] - 2021-10-24 + +### Fixed + +- `pkg-config` compiles again with Rust 1.30 or newer. 0.3.21 accidentally + made use of API only available since 1.40 (#124, #125). + +### Changed + +- Switched from Travis to GitHub Actions for the CI. Travis is dysfunctional + since quite some time (#126). + +## [0.3.21] - 2021-10-22 + +### Fixed + +- Tests succeed again on macOS (#122). + +### Changed + +- Improve error message in case of missing pkg-config and provide instructions + how it can be installed (#121). + +## [0.3.20] - 2021-09-25 + +### Fixed + +- Use target-specific pkg-config consistently everywhere (#121, #118). + +## [0.3.19] - 2020-10-13 + +### Added + +- Add `README.md` to be displayed on crates.io (#111). + +- Support for `-isystem`, `-iquote` and `-idirafter` include flags (#115). + +### Changed + +- Improve documentation for cross-compilation (#113). + +- Allow overriding system root via the `PKG_CONFIG_SYSROOT_DIR` or `SYSROOT` + environment variable (#82). + +## [0.3.18] - 2020-07-11 + +### Fixed + +- Use `env::var_os()` almost everywhere to handle non-UTF8 paths in + environment variables, and also improve error handling around environment + variable handling (#106). + +### Changed + +- Default the `env_metadata` build parameter to `true` instead of `false`. + Whenever a pkg-config related environment variable changes it would make + sense to rebuild crates that use pkg-config, or otherwise changes might not + be picked up. As such the previous default didn't make much sense (#105). + +## [0.3.17] - 2019-11-02 + +### Fixed + +- Fix support for multiple version number constraints (#95) + +## [0.3.16] - 2019-09-09 + +### Changed +- Stop using deprecated functions and require Rust 1.30 (#84) + +### Fixed +- Fix repository URL in README.md +- Fix various clippy warnings + +### Added +- Run `cargo fmt` as part of the CI (#89) +- Derive `Clone` for `Library` and `Debug` for `Config (#91) +- Add support for `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` and enable by default (#93) + +## [0.3.15] - 2019-07-25 + +### Changed +- Changes minimum documented rust version to 1.28 (#76) + +### Fixed +- Fix Travis CI badge url (#78) +- Fix project name in README.md (#81) + +### Added +- Support specifying range of versions (#75) +- Allow cross-compilation if pkg-config is customized (#44, #86) + +## [0.3.14] - 2018-08-28 + +### Fixed +- Don't append .lib suffix on MSVC builds (#72) + +## [0.3.13] - 2018-08-06 + +### Fixed +- Fix MSVC support to actually work and consider library paths too (#71) + +## [0.3.12] - 2018-06-18 + +### Added +- Support for MSVC (#70) +- Document and test Rust 1.13 as minimally supported version (#66) + +## [0.3.11] - 2018-04-24 + +### Fixed +- Re-added AsciiExt import (#65) + +## [0.3.10] - 2018-04-23 + +### Added +- Allow static linking of /usr/ on macOS (#42) +- Add support for parsing `-Wl,` style framework flags (#48) +- Parse defines in `pkg-config` output (#49) +- Rerun on `PKG_CONFIG_PATH` changes (#50) +- Introduce target-scoped variables (#58) +- Respect pkg-config escaping rules used with --cflags and --libs (#61) + +### Changed +- Use `?` instead of `try!()` in the codebase (#63) diff --git a/third_party/rust/pkg-config/Cargo.toml b/third_party/rust/pkg-config/Cargo.toml new file mode 100644 index 0000000000..abd63e3d7a --- /dev/null +++ b/third_party/rust/pkg-config/Cargo.toml @@ -0,0 +1,27 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "pkg-config" +version = "0.3.26" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = """ +A library to run the pkg-config system tool at build time in order to be used in +Cargo build scripts. +""" +documentation = "https://docs.rs/pkg-config" +readme = "README.md" +keywords = ["build-dependencies"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/pkg-config-rs" + +[dev-dependencies.lazy_static] +version = "1" diff --git a/third_party/rust/pkg-config/LICENSE-APACHE b/third_party/rust/pkg-config/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/pkg-config/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third_party/rust/pkg-config/LICENSE-MIT b/third_party/rust/pkg-config/LICENSE-MIT new file mode 100644 index 0000000000..39e0ed6602 --- /dev/null +++ b/third_party/rust/pkg-config/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/pkg-config/README.md b/third_party/rust/pkg-config/README.md new file mode 100644 index 0000000000..61f1244c8d --- /dev/null +++ b/third_party/rust/pkg-config/README.md @@ -0,0 +1,79 @@ +# pkg-config-rs + +[![Build Status](https://github.com/rust-lang/pkg-config-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/rust-lang/pkg-config-rs/actions) +[![Rust](https://img.shields.io/badge/rust-1.30%2B-blue.svg?maxAge=3600)](https://github.com/rust-lang/pkg-config-rs/) + +[Documentation](https://docs.rs/pkg-config) + +A simple library meant to be used as a build dependency with Cargo packages in +order to use the system `pkg-config` tool (if available) to determine where a +library is located. + +You can use this crate directly to probe for specific libraries, or use +[system-deps](https://github.com/gdesmott/system-deps) to declare all your +`pkg-config` dependencies in `Cargo.toml`. + +This library requires Rust 1.30+. + +# Example + +Find the system library named `foo`, with minimum version 1.2.3: + +```rust +extern crate pkg_config; + +fn main() { + pkg_config::Config::new().atleast_version("1.2.3").probe("foo").unwrap(); +} +``` + +Find the system library named `foo`, with no version requirement (not +recommended): + +```rust +extern crate pkg_config; + +fn main() { + pkg_config::probe_library("foo").unwrap(); +} +``` + +# External configuration via target-scoped environment variables + +In cross-compilation context, it is useful to manage separately `PKG_CONFIG_PATH` +and a few other variables for the `host` and the `target` platform. + +The supported variables are: `PKG_CONFIG_PATH`, `PKG_CONFIG_LIBDIR`, and +`PKG_CONFIG_SYSROOT_DIR`. + +Each of these variables can also be supplied with certain prefixes and suffixes, in the following prioritized order: + +1. `<var>_<target>` - for example, `PKG_CONFIG_PATH_x86_64-unknown-linux-gnu` +2. `<var>_<target_with_underscores>` - for example, `PKG_CONFIG_PATH_x86_64_unknown_linux_gnu` +3. `<build-kind>_<var>` - for example, `HOST_PKG_CONFIG_PATH` or `TARGET_PKG_CONFIG_PATH` +4. `<var>` - a plain `PKG_CONFIG_PATH` + +This crate will allow `pkg-config` to be used in cross-compilation +if `PKG_CONFIG_SYSROOT_DIR` or `PKG_CONFIG` is set. You can set `PKG_CONFIG_ALLOW_CROSS=1` +to bypass the compatibility check, but please note that enabling use of `pkg-config` in +cross-compilation without appropriate sysroot and search paths set is likely to break builds. + +Some Rust sys crates support building vendored libraries from source, which may be a work +around for lack of cross-compilation support in `pkg-config`. + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + https://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in pkg-config-rs by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/third_party/rust/pkg-config/src/lib.rs b/third_party/rust/pkg-config/src/lib.rs new file mode 100644 index 0000000000..e9395be465 --- /dev/null +++ b/third_party/rust/pkg-config/src/lib.rs @@ -0,0 +1,972 @@ +//! A build dependency for Cargo libraries to find system artifacts through the +//! `pkg-config` utility. +//! +//! This library will shell out to `pkg-config` as part of build scripts and +//! probe the system to determine how to link to a specified library. The +//! `Config` structure serves as a method of configuring how `pkg-config` is +//! invoked in a builder style. +//! +//! A number of environment variables are available to globally configure how +//! this crate will invoke `pkg-config`: +//! +//! * `FOO_NO_PKG_CONFIG` - if set, this will disable running `pkg-config` when +//! probing for the library named `foo`. +//! +//! * `PKG_CONFIG_ALLOW_CROSS` - The `pkg-config` command usually doesn't +//! support cross-compilation, and this crate prevents it from selecting +//! incompatible versions of libraries. +//! Setting `PKG_CONFIG_ALLOW_CROSS=1` disables this protection, which is +//! likely to cause linking errors, unless `pkg-config` has been configured +//! to use appropriate sysroot and search paths for the target platform. +//! +//! There are also a number of environment variables which can configure how a +//! library is linked to (dynamically vs statically). These variables control +//! whether the `--static` flag is passed. Note that this behavior can be +//! overridden by configuring explicitly on `Config`. The variables are checked +//! in the following order: +//! +//! * `FOO_STATIC` - pass `--static` for the library `foo` +//! * `FOO_DYNAMIC` - do not pass `--static` for the library `foo` +//! * `PKG_CONFIG_ALL_STATIC` - pass `--static` for all libraries +//! * `PKG_CONFIG_ALL_DYNAMIC` - do not pass `--static` for all libraries +//! +//! After running `pkg-config` all appropriate Cargo metadata will be printed on +//! stdout if the search was successful. +//! +//! # Example +//! +//! Find the system library named `foo`, with minimum version 1.2.3: +//! +//! ```no_run +//! fn main() { +//! pkg_config::Config::new().atleast_version("1.2.3").probe("foo").unwrap(); +//! } +//! ``` +//! +//! Find the system library named `foo`, with no version requirement (not +//! recommended): +//! +//! ```no_run +//! fn main() { +//! pkg_config::probe_library("foo").unwrap(); +//! } +//! ``` +//! +//! Configure how library `foo` is linked to. +//! +//! ```no_run +//! fn main() { +//! pkg_config::Config::new().atleast_version("1.2.3").statik(true).probe("foo").unwrap(); +//! } +//! ``` + +#![doc(html_root_url = "https://docs.rs/pkg-config/0.3")] + +use std::collections::HashMap; +use std::env; +use std::error; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io; +use std::ops::{Bound, RangeBounds}; +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::str; + +#[derive(Clone, Debug)] +pub struct Config { + statik: Option<bool>, + min_version: Bound<String>, + max_version: Bound<String>, + extra_args: Vec<OsString>, + cargo_metadata: bool, + env_metadata: bool, + print_system_libs: bool, + print_system_cflags: bool, +} + +#[derive(Clone, Debug)] +pub struct Library { + /// Libraries specified by -l + pub libs: Vec<String>, + /// Library search paths specified by -L + pub link_paths: Vec<PathBuf>, + /// Library file paths specified without -l + pub link_files: Vec<PathBuf>, + /// Darwin frameworks specified by -framework + pub frameworks: Vec<String>, + /// Darwin framework search paths specified by -F + pub framework_paths: Vec<PathBuf>, + /// C/C++ header include paths specified by -I + pub include_paths: Vec<PathBuf>, + /// Linker options specified by -Wl + pub ld_args: Vec<Vec<String>>, + /// C/C++ definitions specified by -D + pub defines: HashMap<String, Option<String>>, + /// Version specified by .pc file's Version field + pub version: String, + /// Ensure that this struct can only be created via its private `[Library::new]` constructor. + /// Users of this crate can only access the struct via `[Config::probe]`. + _priv: (), +} + +/// Represents all reasons `pkg-config` might not succeed or be run at all. +pub enum Error { + /// Aborted because of `*_NO_PKG_CONFIG` environment variable. + /// + /// Contains the name of the responsible environment variable. + EnvNoPkgConfig(String), + + /// Detected cross compilation without a custom sysroot. + /// + /// Ignore the error with `PKG_CONFIG_ALLOW_CROSS=1`, + /// which may let `pkg-config` select libraries + /// for the host's architecture instead of the target's. + CrossCompilation, + + /// Failed to run `pkg-config`. + /// + /// Contains the command and the cause. + Command { command: String, cause: io::Error }, + + /// `pkg-config` did not exit sucessfully after probing a library. + /// + /// Contains the command and output. + Failure { command: String, output: Output }, + + /// `pkg-config` did not exit sucessfully on the first attempt to probe a library. + /// + /// Contains the command and output. + ProbeFailure { + name: String, + command: String, + output: Output, + }, + + #[doc(hidden)] + // please don't match on this, we're likely to add more variants over time + __Nonexhaustive, +} + +impl error::Error for Error {} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + // Failed `unwrap()` prints Debug representation, but the default debug format lacks helpful instructions for the end users + <Error as fmt::Display>::fmt(self, f) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + Error::EnvNoPkgConfig(ref name) => write!(f, "Aborted because {} is set", name), + Error::CrossCompilation => f.write_str( + "pkg-config has not been configured to support cross-compilation.\n\ + \n\ + Install a sysroot for the target platform and configure it via\n\ + PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\n\ + cross-compiling wrapper for pkg-config and set it via\n\ + PKG_CONFIG environment variable.", + ), + Error::Command { + ref command, + ref cause, + } => { + match cause.kind() { + io::ErrorKind::NotFound => { + let crate_name = + std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "sys".to_owned()); + let instructions = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { + "Try `brew install pkg-config` if you have Homebrew.\n" + } else if cfg!(unix) { + "Try `apt install pkg-config`, or `yum install pkg-config`,\n\ + or `pkg install pkg-config`, or `apk add pkgconfig` \ + depending on your distribution.\n" + } else { + "" // There's no easy fix for Windows users + }; + write!(f, "Could not run `{command}`\n\ + The pkg-config command could not be found.\n\ + \n\ + Most likely, you need to install a pkg-config package for your OS.\n\ + {instructions}\ + \n\ + If you've already installed it, ensure the pkg-config command is one of the\n\ + directories in the PATH environment variable.\n\ + \n\ + If you did not expect this build to link to a pre-installed system library,\n\ + then check documentation of the {crate_name} crate for an option to\n\ + build the library from source, or disable features or dependencies\n\ + that require pkg-config.", command = command, instructions = instructions, crate_name = crate_name) + } + _ => write!(f, "Failed to run command `{}`, because: {}", command, cause), + } + } + Error::ProbeFailure { + ref name, + ref command, + ref output, + } => { + write!( + f, + "`{}` did not exit successfully: {}\nerror: could not find system library '{}' required by the '{}' crate\n", + command, output.status, name, env::var("CARGO_PKG_NAME").unwrap_or_default(), + )?; + format_output(output, f) + } + Error::Failure { + ref command, + ref output, + } => { + write!( + f, + "`{}` did not exit successfully: {}", + command, output.status + )?; + format_output(output, f) + } + Error::__Nonexhaustive => panic!(), + } + } +} + +fn format_output(output: &Output, f: &mut fmt::Formatter) -> fmt::Result { + let stdout = String::from_utf8_lossy(&output.stdout); + if !stdout.is_empty() { + write!(f, "\n--- stdout\n{}", stdout)?; + } + let stderr = String::from_utf8_lossy(&output.stderr); + if !stderr.is_empty() { + write!(f, "\n--- stderr\n{}", stderr)?; + } + Ok(()) +} + +/// Deprecated in favor of the probe_library function +#[doc(hidden)] +pub fn find_library(name: &str) -> Result<Library, String> { + probe_library(name).map_err(|e| e.to_string()) +} + +/// Simple shortcut for using all default options for finding a library. +pub fn probe_library(name: &str) -> Result<Library, Error> { + Config::new().probe(name) +} + +#[doc(hidden)] +#[deprecated(note = "use config.target_supported() instance method instead")] +pub fn target_supported() -> bool { + Config::new().target_supported() +} + +/// Run `pkg-config` to get the value of a variable from a package using +/// `--variable`. +/// +/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are +/// returned by `pkg-config --variable`, which makes them unsuitable to use +/// during cross-compilation unless specifically designed to be used +/// at that time. +pub fn get_variable(package: &str, variable: &str) -> Result<String, Error> { + let arg = format!("--variable={}", variable); + let cfg = Config::new(); + let out = run(cfg.command(package, &[&arg]))?; + Ok(str::from_utf8(&out).unwrap().trim_end().to_owned()) +} + +impl Config { + /// Creates a new set of configuration options which are all initially set + /// to "blank". + pub fn new() -> Config { + Config { + statik: None, + min_version: Bound::Unbounded, + max_version: Bound::Unbounded, + extra_args: vec![], + print_system_cflags: true, + print_system_libs: true, + cargo_metadata: true, + env_metadata: true, + } + } + + /// Indicate whether the `--static` flag should be passed. + /// + /// This will override the inference from environment variables described in + /// the crate documentation. + pub fn statik(&mut self, statik: bool) -> &mut Config { + self.statik = Some(statik); + self + } + + /// Indicate that the library must be at least version `vers`. + pub fn atleast_version(&mut self, vers: &str) -> &mut Config { + self.min_version = Bound::Included(vers.to_string()); + self.max_version = Bound::Unbounded; + self + } + + /// Indicate that the library must be equal to version `vers`. + pub fn exactly_version(&mut self, vers: &str) -> &mut Config { + self.min_version = Bound::Included(vers.to_string()); + self.max_version = Bound::Included(vers.to_string()); + self + } + + /// Indicate that the library's version must be in `range`. + pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config + where + R: RangeBounds<&'a str>, + { + self.min_version = match range.start_bound() { + Bound::Included(vers) => Bound::Included(vers.to_string()), + Bound::Excluded(vers) => Bound::Excluded(vers.to_string()), + Bound::Unbounded => Bound::Unbounded, + }; + self.max_version = match range.end_bound() { + Bound::Included(vers) => Bound::Included(vers.to_string()), + Bound::Excluded(vers) => Bound::Excluded(vers.to_string()), + Bound::Unbounded => Bound::Unbounded, + }; + self + } + + /// Add an argument to pass to pkg-config. + /// + /// It's placed after all of the arguments generated by this library. + pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Config { + self.extra_args.push(arg.as_ref().to_os_string()); + self + } + + /// Define whether metadata should be emitted for cargo allowing it to + /// automatically link the binary. Defaults to `true`. + pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config { + self.cargo_metadata = cargo_metadata; + self + } + + /// Define whether metadata should be emitted for cargo allowing to + /// automatically rebuild when environment variables change. Defaults to + /// `true`. + pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config { + self.env_metadata = env_metadata; + self + } + + /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment + /// variable. + /// + /// This env var is enabled by default. + pub fn print_system_libs(&mut self, print: bool) -> &mut Config { + self.print_system_libs = print; + self + } + + /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment + /// variable. + /// + /// This env var is enabled by default. + pub fn print_system_cflags(&mut self, print: bool) -> &mut Config { + self.print_system_cflags = print; + self + } + + /// Deprecated in favor fo the `probe` function + #[doc(hidden)] + pub fn find(&self, name: &str) -> Result<Library, String> { + self.probe(name).map_err(|e| e.to_string()) + } + + /// Run `pkg-config` to find the library `name`. + /// + /// This will use all configuration previously set to specify how + /// `pkg-config` is run. + pub fn probe(&self, name: &str) -> Result<Library, Error> { + let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name)); + if self.env_var_os(&abort_var_name).is_some() { + return Err(Error::EnvNoPkgConfig(abort_var_name)); + } else if !self.target_supported() { + return Err(Error::CrossCompilation); + } + + let mut library = Library::new(); + + let output = run(self.command(name, &["--libs", "--cflags"])).map_err(|e| match e { + Error::Failure { command, output } => Error::ProbeFailure { + name: name.to_owned(), + command, + output, + }, + other => other, + })?; + library.parse_libs_cflags(name, &output, self); + + let output = run(self.command(name, &["--modversion"]))?; + library.parse_modversion(str::from_utf8(&output).unwrap()); + + Ok(library) + } + + /// True if pkg-config is used for the host system, or configured for cross-compilation + pub fn target_supported(&self) -> bool { + let target = env::var_os("TARGET").unwrap_or_default(); + let host = env::var_os("HOST").unwrap_or_default(); + + // Only use pkg-config in host == target situations by default (allowing an + // override). + if host == target { + return true; + } + + // pkg-config may not be aware of cross-compilation, and require + // a wrapper script that sets up platform-specific prefixes. + match self.targetted_env_var("PKG_CONFIG_ALLOW_CROSS") { + // don't use pkg-config if explicitly disabled + Some(ref val) if val == "0" => false, + Some(_) => true, + None => { + // if not disabled, and pkg-config is customized, + // then assume it's prepared for cross-compilation + self.targetted_env_var("PKG_CONFIG").is_some() + || self.targetted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some() + } + } + } + + /// Deprecated in favor of the top level `get_variable` function + #[doc(hidden)] + pub fn get_variable(package: &str, variable: &str) -> Result<String, String> { + get_variable(package, variable).map_err(|e| e.to_string()) + } + + fn targetted_env_var(&self, var_base: &str) -> Option<OsString> { + match (env::var("TARGET"), env::var("HOST")) { + (Ok(target), Ok(host)) => { + let kind = if host == target { "HOST" } else { "TARGET" }; + let target_u = target.replace("-", "_"); + + self.env_var_os(&format!("{}_{}", var_base, target)) + .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u))) + .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base))) + .or_else(|| self.env_var_os(var_base)) + } + (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => { + self.env_var_os(var_base) + } + (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => { + panic!( + "HOST or TARGET environment variable is not valid unicode: {:?}", + s + ) + } + } + } + + fn env_var_os(&self, name: &str) -> Option<OsString> { + if self.env_metadata { + println!("cargo:rerun-if-env-changed={}", name); + } + env::var_os(name) + } + + fn is_static(&self, name: &str) -> bool { + self.statik.unwrap_or_else(|| self.infer_static(name)) + } + + fn command(&self, name: &str, args: &[&str]) -> Command { + let exe = self + .targetted_env_var("PKG_CONFIG") + .unwrap_or_else(|| OsString::from("pkg-config")); + let mut cmd = Command::new(exe); + if self.is_static(name) { + cmd.arg("--static"); + } + cmd.args(args).args(&self.extra_args); + + if let Some(value) = self.targetted_env_var("PKG_CONFIG_PATH") { + cmd.env("PKG_CONFIG_PATH", value); + } + if let Some(value) = self.targetted_env_var("PKG_CONFIG_LIBDIR") { + cmd.env("PKG_CONFIG_LIBDIR", value); + } + if let Some(value) = self.targetted_env_var("PKG_CONFIG_SYSROOT_DIR") { + cmd.env("PKG_CONFIG_SYSROOT_DIR", value); + } + if self.print_system_libs { + cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1"); + } + if self.print_system_cflags { + cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1"); + } + cmd.arg(name); + match self.min_version { + Bound::Included(ref version) => { + cmd.arg(&format!("{} >= {}", name, version)); + } + Bound::Excluded(ref version) => { + cmd.arg(&format!("{} > {}", name, version)); + } + _ => (), + } + match self.max_version { + Bound::Included(ref version) => { + cmd.arg(&format!("{} <= {}", name, version)); + } + Bound::Excluded(ref version) => { + cmd.arg(&format!("{} < {}", name, version)); + } + _ => (), + } + cmd + } + + fn print_metadata(&self, s: &str) { + if self.cargo_metadata { + println!("cargo:{}", s); + } + } + + fn infer_static(&self, name: &str) -> bool { + let name = envify(name); + if self.env_var_os(&format!("{}_STATIC", name)).is_some() { + true + } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() { + false + } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() { + true + } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() { + false + } else { + false + } + } +} + +// Implement Default manualy since Bound does not implement Default. +impl Default for Config { + fn default() -> Config { + Config { + statik: None, + min_version: Bound::Unbounded, + max_version: Bound::Unbounded, + extra_args: vec![], + print_system_cflags: false, + print_system_libs: false, + cargo_metadata: false, + env_metadata: false, + } + } +} + +impl Library { + fn new() -> Library { + Library { + libs: Vec::new(), + link_paths: Vec::new(), + link_files: Vec::new(), + include_paths: Vec::new(), + ld_args: Vec::new(), + frameworks: Vec::new(), + framework_paths: Vec::new(), + defines: HashMap::new(), + version: String::new(), + _priv: (), + } + } + + /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories) + /// using target-specific logic. + fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> { + fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> { + for suffix in suffixes { + if filename.ends_with(suffix) { + return Some(&filename[..filename.len() - suffix.len()]); + } + } + None + } + + let prefix = "lib"; + if target.contains("msvc") { + // According to link.exe documentation: + // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170 + // + // LINK doesn't use file extensions to make assumptions about the contents of a file. + // Instead, LINK examines each input file to determine what kind of file it is. + // + // However, rustc appends `.lib` to the string it receives from the -l command line argument, + // which it receives from Cargo via cargo:rustc-link-lib: + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828 + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843 + // So the only file extension that works for MSVC targets is `.lib` + return test_suffixes(filename, &[".lib"]); + } else if target.contains("windows") && target.contains("gnu") { + // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc, + // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it + // receives via the -l command line argument before passing it to the linker: + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446 + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457 + // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs. + // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove + // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix. + // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll + if filename.starts_with(prefix) { + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]); + } else { + return test_suffixes(filename, &[".dll.a", ".dll", ".lib"]); + } + } else if target.contains("apple") { + if filename.starts_with(prefix) { + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".a", ".so", ".dylib"]); + } + return None; + } else { + if filename.starts_with(prefix) { + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".a", ".so"]); + } + return None; + } + } + + fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) { + let mut is_msvc = false; + let target = env::var("TARGET"); + if let Ok(target) = &target { + if target.contains("msvc") { + is_msvc = true; + } + } + + let system_roots = if cfg!(target_os = "macos") { + vec![PathBuf::from("/Library"), PathBuf::from("/System")] + } else { + let sysroot = config + .env_var_os("PKG_CONFIG_SYSROOT_DIR") + .or_else(|| config.env_var_os("SYSROOT")) + .map(PathBuf::from); + + if cfg!(target_os = "windows") { + if let Some(sysroot) = sysroot { + vec![sysroot] + } else { + vec![] + } + } else { + vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))] + } + }; + + let mut dirs = Vec::new(); + let statik = config.is_static(name); + + let words = split_flags(output); + + // Handle single-character arguments like `-I/usr/include` + let parts = words + .iter() + .filter(|l| l.len() > 2) + .map(|arg| (&arg[0..2], &arg[2..])); + for (flag, val) in parts { + match flag { + "-L" => { + let meta = format!("rustc-link-search=native={}", val); + config.print_metadata(&meta); + dirs.push(PathBuf::from(val)); + self.link_paths.push(PathBuf::from(val)); + } + "-F" => { + let meta = format!("rustc-link-search=framework={}", val); + config.print_metadata(&meta); + self.framework_paths.push(PathBuf::from(val)); + } + "-I" => { + self.include_paths.push(PathBuf::from(val)); + } + "-l" => { + // These are provided by the CRT with MSVC + if is_msvc && ["m", "c", "pthread"].contains(&val) { + continue; + } + + if statik && is_static_available(val, &system_roots, &dirs) { + let meta = format!("rustc-link-lib=static={}", val); + config.print_metadata(&meta); + } else { + let meta = format!("rustc-link-lib={}", val); + config.print_metadata(&meta); + } + + self.libs.push(val.to_string()); + } + "-D" => { + let mut iter = val.split('='); + self.defines.insert( + iter.next().unwrap().to_owned(), + iter.next().map(|s| s.to_owned()), + ); + } + _ => {} + } + } + + // Handle multi-character arguments with space-separated value like `-framework foo` + let mut iter = words.iter().flat_map(|arg| { + if arg.starts_with("-Wl,") { + arg[4..].split(',').collect() + } else { + vec![arg.as_ref()] + } + }); + while let Some(part) = iter.next() { + match part { + "-framework" => { + if let Some(lib) = iter.next() { + let meta = format!("rustc-link-lib=framework={}", lib); + config.print_metadata(&meta); + self.frameworks.push(lib.to_string()); + } + } + "-isystem" | "-iquote" | "-idirafter" => { + if let Some(inc) = iter.next() { + self.include_paths.push(PathBuf::from(inc)); + } + } + _ => { + let path = std::path::Path::new(part); + if path.is_file() { + // Cargo doesn't have a means to directly specify a file path to link, + // so split up the path into the parent directory and library name. + // TODO: pass file path directly when link-arg library type is stabilized + // https://github.com/rust-lang/rust/issues/99427 + if let (Some(dir), Some(file_name), Ok(target)) = + (path.parent(), path.file_name(), &target) + { + match Self::extract_lib_from_filename( + target, + &file_name.to_string_lossy(), + ) { + Some(lib_basename) => { + let link_search = + format!("rustc-link-search={}", dir.display()); + config.print_metadata(&link_search); + + let link_lib = format!("rustc-link-lib={}", lib_basename); + config.print_metadata(&link_lib); + self.link_files.push(PathBuf::from(path)); + } + None => { + 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); + } + } + } + } + } + } + } + + let mut linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,")); + while let Some(option) = linker_options.next() { + let mut pop = false; + let mut ld_option = vec![]; + for subopt in option[4..].split(',') { + if pop { + pop = false; + continue; + } + + if subopt == "-framework" { + pop = true; + continue; + } + + ld_option.push(subopt); + } + + let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(",")); + config.print_metadata(&meta); + + self.ld_args + .push(ld_option.into_iter().map(String::from).collect()); + } + } + + fn parse_modversion(&mut self, output: &str) { + self.version.push_str(output.lines().nth(0).unwrap().trim()); + } +} + +fn envify(name: &str) -> String { + name.chars() + .map(|c| c.to_ascii_uppercase()) + .map(|c| if c == '-' { '_' } else { c }) + .collect() +} + +/// System libraries should only be linked dynamically +fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool { + let libname = format!("lib{}.a", name); + + dirs.iter().any(|dir| { + !system_roots.iter().any(|sys| dir.starts_with(sys)) && dir.join(&libname).exists() + }) +} + +fn run(mut cmd: Command) -> Result<Vec<u8>, Error> { + match cmd.output() { + Ok(output) => { + if output.status.success() { + Ok(output.stdout) + } else { + Err(Error::Failure { + command: format!("{:?}", cmd), + output, + }) + } + } + Err(cause) => Err(Error::Command { + command: format!("{:?}", cmd), + cause, + }), + } +} + +/// Split output produced by pkg-config --cflags and / or --libs into separate flags. +/// +/// Backslash in output is used to preserve literal meaning of following byte. Different words are +/// separated by unescaped space. Other whitespace characters generally should not occur unescaped +/// at all, apart from the newline at the end of output. For compatibility with what others +/// consumers of pkg-config output would do in this scenario, they are used here for splitting as +/// well. +fn split_flags(output: &[u8]) -> Vec<String> { + let mut word = Vec::new(); + let mut words = Vec::new(); + let mut escaped = false; + + for &b in output { + match b { + _ if escaped => { + escaped = false; + word.push(b); + } + b'\\' => escaped = true, + b'\t' | b'\n' | b'\r' | b' ' => { + if !word.is_empty() { + words.push(String::from_utf8(word).unwrap()); + word = Vec::new(); + } + } + _ => word.push(b), + } + } + + if !word.is_empty() { + words.push(String::from_utf8(word).unwrap()); + } + + words +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(target_os = "macos")] + fn system_library_mac_test() { + use std::path::Path; + + let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")]; + + assert!(!is_static_available( + "PluginManager", + &system_roots, + &[PathBuf::from("/Library/Frameworks")] + )); + assert!(!is_static_available( + "python2.7", + &system_roots, + &[PathBuf::from( + "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config" + )] + )); + assert!(!is_static_available( + "ffi_convenience", + &system_roots, + &[PathBuf::from( + "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs" + )] + )); + + // Homebrew is in /usr/local, and it's not a part of the OS + if Path::new("/usr/local/lib/libpng16.a").exists() { + assert!(is_static_available( + "png16", + &system_roots, + &[PathBuf::from("/usr/local/lib")] + )); + + let libpng = Config::new() + .range_version("1".."99") + .probe("libpng16") + .unwrap(); + assert!(libpng.version.find('\n').is_none()); + } + } + + #[test] + #[cfg(target_os = "linux")] + fn system_library_linux_test() { + assert!(!is_static_available( + "util", + &[PathBuf::from("/usr")], + &[PathBuf::from("/usr/lib/x86_64-linux-gnu")] + )); + assert!(!is_static_available( + "dialog", + &[PathBuf::from("/usr")], + &[PathBuf::from("/usr/lib")] + )); + } + + fn test_library_filename(target: &str, filename: &str) { + assert_eq!( + Library::extract_lib_from_filename(target, filename), + Some("foo") + ); + } + + #[test] + fn link_filename_linux() { + let target = "x86_64-unknown-linux-gnu"; + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "libfoo.so"); + } + + #[test] + fn link_filename_apple() { + let target = "x86_64-apple-darwin"; + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "libfoo.so"); + test_library_filename(target, "libfoo.dylib"); + } + + #[test] + fn link_filename_msvc() { + let target = "x86_64-pc-windows-msvc"; + // static and dynamic libraries have the same .lib suffix + test_library_filename(target, "foo.lib"); + } + + #[test] + fn link_filename_mingw() { + let target = "x86_64-pc-windows-gnu"; + test_library_filename(target, "foo.lib"); + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "foo.dll"); + test_library_filename(target, "foo.dll.a"); + } +} diff --git a/third_party/rust/pkg-config/tests/escape.pc b/third_party/rust/pkg-config/tests/escape.pc new file mode 100644 index 0000000000..701c4bf73f --- /dev/null +++ b/third_party/rust/pkg-config/tests/escape.pc @@ -0,0 +1,5 @@ +Name: Escape +Version: 4.2.0 +Description: Escape utility library +Libs: -Llink\ path\ with\ spaces +Cflags: -Iinclude\ path\ with\ spaces -DA=\"escaped\ string\'\ literal\" -DB=ESCAPED\ IDENTIFIER -DFOX=🦊 diff --git a/third_party/rust/pkg-config/tests/foo.pc b/third_party/rust/pkg-config/tests/foo.pc new file mode 100644 index 0000000000..ce63ceb558 --- /dev/null +++ b/third_party/rust/pkg-config/tests/foo.pc @@ -0,0 +1,16 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/valgrind +arch=amd64 +os=linux +platform=amd64-linux +valt_load_address=0x38000000 + +Name: Valgrind +Description: A dynamic binary instrumentation framework +Version: 3.10.0.SVN +Requires: +Libs: -L${libdir}/valgrind -lcoregrind-amd64-linux -lvex-amd64-linux -lgcc +Cflags: -I${includedir} -isystem /usr/foo + diff --git a/third_party/rust/pkg-config/tests/framework.pc b/third_party/rust/pkg-config/tests/framework.pc new file mode 100644 index 0000000000..fec17f47a6 --- /dev/null +++ b/third_party/rust/pkg-config/tests/framework.pc @@ -0,0 +1,16 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/valgrind +arch=amd64 +os=linux +platform=amd64-linux +valt_load_address=0x38000000 + +Name: Valgrind +Description: A dynamic binary instrumentation framework +Version: 3.10.0.SVN +Requires: +Libs: -F${libdir} -framework foo -Wl,-framework,bar -Wl,-framework -Wl,baz -Wl,-framework,foobar,-framework,foobaz +Cflags: -I${includedir} + diff --git a/third_party/rust/pkg-config/tests/rpath.pc b/third_party/rust/pkg-config/tests/rpath.pc new file mode 100644 index 0000000000..7c36c5cb71 --- /dev/null +++ b/third_party/rust/pkg-config/tests/rpath.pc @@ -0,0 +1,7 @@ +prefix=/usr/local + +Name: rpath +Version: 4.2.0 +Description: RPath example library +Libs: -L${prefix}/lib -Wl,-rpath,${prefix}/lib -lrpath +Cflags: -I${prefix}/include diff --git a/third_party/rust/pkg-config/tests/test.rs b/third_party/rust/pkg-config/tests/test.rs new file mode 100644 index 0000000000..4e04ac0712 --- /dev/null +++ b/third_party/rust/pkg-config/tests/test.rs @@ -0,0 +1,323 @@ +extern crate pkg_config; +#[macro_use] +extern crate lazy_static; + +use pkg_config::Error; +use std::env; +use std::path::PathBuf; +use std::sync::Mutex; + +lazy_static! { + static ref LOCK: Mutex<()> = Mutex::new(()); +} + +fn reset() { + for (k, _) in env::vars() { + if k.contains("DYNAMIC") + || k.contains("STATIC") + || k.contains("PKG_CONFIG_ALLOW_CROSS") + || k.contains("PKG_CONFIG_SYSROOT_DIR") + || k.contains("FOO_NO_PKG_CONFIG") + { + env::remove_var(&k); + } + } + env::remove_var("TARGET"); + env::remove_var("HOST"); + env::set_var( + "PKG_CONFIG_PATH", + &env::current_dir().unwrap().join("tests"), + ); +} + +fn find(name: &str) -> Result<pkg_config::Library, Error> { + pkg_config::probe_library(name) +} + +#[test] +fn cross_disabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + match find("foo") { + Err(Error::CrossCompilation) => {} + x => panic!("Error::CrossCompilation expected, found `{:?}`", x), + } +} + +#[test] +fn cross_enabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_ALLOW_CROSS", "1"); + find("foo").unwrap(); +} + +#[test] +fn cross_enabled_if_customized() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_SYSROOT_DIR", "/tmp/cross-test"); + find("foo").unwrap(); +} + +#[test] +fn cross_disabled_if_customized() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_ALLOW_CROSS", "0"); + env::set_var("PKG_CONFIG_SYSROOT_DIR", "/tmp/cross-test"); + match find("foo") { + Err(Error::CrossCompilation) => {} + _ => panic!("expected CrossCompilation failure"), + } +} + +#[test] +fn package_disabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("FOO_NO_PKG_CONFIG", "1"); + match find("foo") { + Err(Error::EnvNoPkgConfig(name)) => assert_eq!(name, "FOO_NO_PKG_CONFIG"), + x => panic!("Error::EnvNoPkgConfig expected, found `{:?}`", x), + } +} + +#[test] +fn output_ok() { + let _g = LOCK.lock(); + reset(); + let lib = find("foo").unwrap(); + assert!(lib.libs.contains(&"gcc".to_string())); + assert!(lib.libs.contains(&"coregrind-amd64-linux".to_string())); + assert!(lib.link_paths.contains(&PathBuf::from("/usr/lib/valgrind"))); + assert!(lib + .include_paths + .contains(&PathBuf::from("/usr/include/valgrind"))); + assert!(lib.include_paths.contains(&PathBuf::from("/usr/foo"))); +} + +#[test] +fn escapes() { + let _g = LOCK.lock(); + reset(); + let lib = find("escape").unwrap(); + assert!(lib + .include_paths + .contains(&PathBuf::from("include path with spaces"))); + assert!(lib + .link_paths + .contains(&PathBuf::from("link path with spaces"))); + assert_eq!( + lib.defines.get("A"), + Some(&Some("\"escaped string' literal\"".to_owned())) + ); + assert_eq!( + lib.defines.get("B"), + Some(&Some("ESCAPED IDENTIFIER".to_owned())) + ); + assert_eq!(lib.defines.get("FOX"), Some(&Some("🦊".to_owned()))); +} + +#[test] +fn framework() { + let _g = LOCK.lock(); + reset(); + let lib = find("framework").unwrap(); + assert!(lib.frameworks.contains(&"foo".to_string())); + assert!(lib.frameworks.contains(&"bar".to_string())); + assert!(lib.frameworks.contains(&"baz".to_string())); + assert!(lib.frameworks.contains(&"foobar".to_string())); + assert!(lib.frameworks.contains(&"foobaz".to_string())); + assert!(lib.framework_paths.contains(&PathBuf::from("/usr/lib"))); +} + +#[test] +fn get_variable() { + let _g = LOCK.lock(); + reset(); + let prefix = pkg_config::get_variable("foo", "prefix").unwrap(); + assert_eq!(prefix, "/usr"); +} + +#[test] +fn version() { + let _g = LOCK.lock(); + reset(); + assert_eq!(&find("foo").unwrap().version[..], "3.10.0.SVN"); +} + +#[test] +fn atleast_version_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .atleast_version("3.10") + .probe("foo") + .unwrap(); +} + +#[test] +#[should_panic] +fn atleast_version_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .atleast_version("3.11") + .probe("foo") + .unwrap(); +} + +#[test] +fn exactly_version_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .exactly_version("3.10.0.SVN") + .probe("foo") + .unwrap(); +} + +#[test] +#[should_panic] +fn exactly_version_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .exactly_version("3.10.0") + .probe("foo") + .unwrap(); +} + +#[test] +fn range_version_range_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.2.0".."4.4.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0".."4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_inclusive_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0"..="4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_inclusive_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("3.8.0"..="4.0.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_from_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0"..) + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_from_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.4.0"..) + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_to_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(.."4.4.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_to_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(.."4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_to_inclusive_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..="4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_to_inclusive_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..="4.0.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_full() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..) + .probe("escape") + .unwrap(); +} + +#[test] +fn rpath() { + let _g = LOCK.lock(); + reset(); + let lib = find("rpath").unwrap(); + assert!(lib + .ld_args + .contains(&vec!["-rpath".to_string(), "/usr/local/lib".to_string(),])); +} |