Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use pkg config #139

Merged
merged 2 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions psa-crypto-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ cc = "1.0.59"
cmake = "0.1.44"
regex = "1.9.1"
walkdir = "2.3.1"
pkg-config = "0.3.29"

[features]
default = ["operations"]
Expand Down
285 changes: 167 additions & 118 deletions psa-crypto-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,41 +64,73 @@ mod common {

use std::env;
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
use std::path::PathBuf;

pub fn configure_mbed_crypto() -> Result<()> {
let mbedtls_dir = String::from("./vendor");
let mbedtls_config = mbedtls_dir + "/scripts/config.py";
#[cfg(any(feature = "prefix", feature = "operations"))]
pub fn get_external_mbedtls() -> Option<Result<(String, String)>> {
if env::var("MBEDTLS_LIB_DIR").is_err() ^ env::var("MBEDTLS_INCLUDE_DIR").is_err() {
tgonzalezorlandoarm marked this conversation as resolved.
Show resolved Hide resolved
return Some(Err(Error::new(
ErrorKind::Other,
"both environment variables MBEDTLS_LIB_DIR and MBEDTLS_INCLUDE_DIR need to be set for operations feature",
)));
}

println!("cargo:rerun-if-changed=src/c/shim.c");
println!("cargo:rerun-if-changed=src/c/shim.h");
if let (Ok(lib_dir), Ok(include_dir)) =
(env::var("MBEDTLS_LIB_DIR"), env::var("MBEDTLS_INCLUDE_DIR"))
{
println!("Found environment variables, using external MbedTLS");
return Some(Ok((include_dir, lib_dir)));
}

let out_dir = env::var("OUT_DIR").unwrap();
if let Ok(mbedtls_result) = pkg_config::Config::new()
.range_version("3.5".."4.0")
.probe("mbedtls")
{
let include_dirs: Vec<String> = mbedtls_result
.include_paths
.into_iter()
.map(|x: PathBuf| -> String { x.into_os_string().into_string().unwrap() })
.collect();
let include_dir = include_dirs.join(" ");
// The current build framework doesn't support multiple lib paths for -L unfortuantely, so
// we just take the first element, which is enough for now :-(
let lib_dir = <PathBuf as Clone>::clone(&mbedtls_result.link_paths[0])
.into_os_string()
.into_string()
.unwrap();
println!("Found pkg-config mbedtls, using external MbedTLS");
return Some(Ok((include_dir, lib_dir)));
}

// Check for Mbed TLS sources
if !Path::new(&mbedtls_config).exists() {
return Err(Error::new(
ErrorKind::Other,
"MbedTLS config.py is missing. Have you run 'git submodule update --init'?",
));
// No env vars set and no discovered package through pkg-config
None
}

#[cfg(all(feature = "interface", not(feature = "operations")))]
pub fn get_external_mbedtls_include_only() -> Result<String> {
if let Ok(include_dir) = env::var("MBEDTLS_INCLUDE_DIR") {
println!("Found environment variable, using external MbedTLS");
return Ok(include_dir);
}

// Configure the MbedTLS build for making Mbed Crypto
if !::std::process::Command::new(mbedtls_config)
.arg("--write")
.arg(&(out_dir + "/" + CONFIG_FILE))
.arg("crypto")
.status()
.map_err(|_| Error::new(ErrorKind::Other, "configuring mbedtls failed"))?
.success()
if let Ok(mbedtls_result) = pkg_config::Config::new()
.range_version("3.5".."4.0")
.probe("mbedtls")
{
return Err(Error::new(
ErrorKind::Other,
"config.py returned an error status",
));
let include_dirs: Vec<String> = mbedtls_result
.include_paths
.into_iter()
.map(|x: PathBuf| -> String { x.into_os_string().into_string().unwrap() })
.collect();
let include_dir = include_dirs.join(" ");

return Ok(include_dir);
}

Ok(())
Err(Error::new(
ErrorKind::Other,
"interface feature necessitates MBEDTLS_INCLUDE_DIR environment variable",
gowthamsk-arm marked this conversation as resolved.
Show resolved Hide resolved
))
}

#[cfg(feature = "prefix")]
Expand Down Expand Up @@ -209,22 +241,15 @@ mod common {
#[cfg(all(feature = "interface", not(feature = "operations")))]
mod interface {
use super::common;
use std::env;
use std::io::{Error, ErrorKind, Result};
use std::io::Result;

// Build script when the interface feature is on and not the operations one
pub fn script_interface() -> Result<()> {
if let Ok(include_dir) = env::var("MBEDTLS_INCLUDE_DIR") {
common::configure_mbed_crypto()?;
common::generate_mbed_crypto_bindings(include_dir.clone(), false)?;
let _ = common::compile_shim_library(include_dir, true, false)?;
Ok(())
} else {
Err(Error::new(
ErrorKind::Other,
"interface feature necessitates MBEDTLS_INCLUDE_DIR environment variable",
))
}
let include_dir = common::get_external_mbedtls_include_only()?;

common::generate_mbed_crypto_bindings(include_dir.clone(), true)?;
let _ = common::compile_shim_library(include_dir, true, true)?;
Ok(())
}
}

Expand All @@ -238,9 +263,44 @@ mod operations {
#[cfg(feature = "prefix")]
use std::io::Write;
use std::io::{Error, ErrorKind, Result};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

pub fn configure_mbed_crypto() -> Result<()> {
let mbedtls_dir = String::from("./vendor");
let mbedtls_config = mbedtls_dir + "/scripts/config.py";

println!("cargo:rerun-if-changed=src/c/shim.c");
println!("cargo:rerun-if-changed=src/c/shim.h");

let out_dir = env::var("OUT_DIR").unwrap();

// Check for Mbed TLS sources
if !Path::new(&mbedtls_config).exists() {
return Err(Error::new(
ErrorKind::Other,
"MbedTLS config.py is missing. Have you run 'git submodule update --init'?",
));
}

// Configure the MbedTLS build for making Mbed Crypto
if !::std::process::Command::new(mbedtls_config)
.arg("--write")
.arg(&(out_dir + "/" + common::CONFIG_FILE))
.arg("crypto")
.status()
.map_err(|_| Error::new(ErrorKind::Other, "configuring mbedtls failed"))?
.success()
{
return Err(Error::new(
ErrorKind::Other,
"config.py returned an error status",
));
}

Ok(())
}

fn compile_mbed_crypto() -> Result<PathBuf> {
let mbedtls_dir = String::from("./vendor");
let out_dir = env::var("OUT_DIR").unwrap();
Expand Down Expand Up @@ -288,36 +348,31 @@ mod operations {
let include;
let external_mbedtls;

if env::var("MBEDTLS_LIB_DIR").is_err() ^ env::var("MBEDTLS_INCLUDE_DIR").is_err() {
return Err(Error::new(
ErrorKind::Other,
"both environment variables MBEDTLS_LIB_DIR and MBEDTLS_INCLUDE_DIR need to be set for operations feature",
));
}
if let (Ok(lib_dir), Ok(include_dir)) =
(env::var("MBEDTLS_LIB_DIR"), env::var("MBEDTLS_INCLUDE_DIR"))
{
println!("Found environment varibales, using external MbedTLS");
lib = lib_dir;
include = include_dir;
statically = cfg!(feature = "static") || env::var("MBEDCRYPTO_STATIC").is_ok();
external_mbedtls = true;
} else {
println!("Did not find environment variables, building MbedTLS!");
common::configure_mbed_crypto()?;
let mut mbed_lib_dir = compile_mbed_crypto()?;
let mut mbed_include_dir = mbed_lib_dir.clone();
mbed_lib_dir.push("lib");
if !mbed_lib_dir.as_path().exists() {
_ = mbed_lib_dir.pop();
mbed_lib_dir.push("lib64");
match common::get_external_mbedtls() {
Some(result) => {
let (include_dir, lib_dir) = result.unwrap();
lib = lib_dir;
include = include_dir;
statically = cfg!(feature = "static") || env::var("MBEDCRYPTO_STATIC").is_ok();
external_mbedtls = true;
}
mbed_include_dir.push("include");
None => {
println!("Did not find external MBEDTLS, building MbedTLS!");
configure_mbed_crypto()?;
let mut mbed_lib_dir = compile_mbed_crypto()?;
let mut mbed_include_dir = mbed_lib_dir.clone();
mbed_lib_dir.push("lib");
if !mbed_lib_dir.as_path().exists() {
_ = mbed_lib_dir.pop();
mbed_lib_dir.push("lib64");
}
mbed_include_dir.push("include");

lib = mbed_lib_dir.to_str().unwrap().to_owned();
include = mbed_include_dir.to_str().unwrap().to_owned();
statically = true;
external_mbedtls = false;
lib = mbed_lib_dir.to_str().unwrap().to_owned();
include = mbed_include_dir.to_str().unwrap().to_owned();
statically = true;
external_mbedtls = false;
}
}

// Linking to PSA Crypto library is only needed for the operations.
Expand All @@ -332,58 +387,52 @@ mod operations {
#[cfg(feature = "prefix")]
// Build script when the operations feature is on
pub fn script_operations() -> Result<()> {
if env::var("MBEDTLS_LIB_DIR").is_err() ^ env::var("MBEDTLS_INCLUDE_DIR").is_err() {
return Err(Error::new(
ErrorKind::Other,
"both environment variables MBEDTLS_LIB_DIR and MBEDTLS_INCLUDE_DIR need to be set for operations feature",
));
}

if let (Ok(lib_dir), Ok(include_dir)) =
(env::var("MBEDTLS_LIB_DIR"), env::var("MBEDTLS_INCLUDE_DIR"))
{
println!("Building with external MBEDTLS");

// Request rustc to link the Mbed Crypto library
let link_type = if cfg!(feature = "static") || env::var("MBEDCRYPTO_STATIC").is_ok() {
"static"
} else {
"dylib"
};
println!("cargo:rustc-link-search=native={}", lib_dir);
println!("cargo:rustc-link-lib={}=mbedcrypto", link_type);

common::generate_mbed_crypto_bindings(include_dir.clone(), true)?;
let _ = common::compile_shim_library(include_dir, true, true)?;
} else {
println!("Did not find environment variables, building MbedTLS!");
common::configure_mbed_crypto()?;
let mut mbed_lib_dir = compile_mbed_crypto()?;
let mut mbed_include_dir = mbed_lib_dir.clone();
mbed_lib_dir.push("lib");
if !mbed_lib_dir.as_path().exists() {
_ = mbed_lib_dir.pop();
mbed_lib_dir.push("lib64");
match common::get_external_mbedtls() {
Some(result) => {
let (include_dir, lib_dir) = result.unwrap();
// Request rustc to link the Mbed Crypto library
let link_type = if cfg!(feature = "static") || env::var("MBEDCRYPTO_STATIC").is_ok()
{
"static"
} else {
"dylib"
};
println!("cargo:rustc-link-search=native={}", lib_dir);
println!("cargo:rustc-link-lib={}=mbedcrypto", link_type);

common::generate_mbed_crypto_bindings(include_dir.clone(), true)?;
let _ = common::compile_shim_library(include_dir, true, true)?;
}
None => {
println!("Did not find environment variables, building MbedTLS!");
configure_mbed_crypto()?;
let mut mbed_lib_dir = compile_mbed_crypto()?;
let mut mbed_include_dir = mbed_lib_dir.clone();
mbed_lib_dir.push("lib");
if !mbed_lib_dir.as_path().exists() {
_ = mbed_lib_dir.pop();
mbed_lib_dir.push("lib64");
}

mbed_include_dir.push("include");
let main_lib = mbed_lib_dir.join("libmbedcrypto.a");

let include = mbed_include_dir.to_str().unwrap().to_owned();
common::generate_mbed_crypto_bindings(include.clone(), false)?;
let shim_lib = common::compile_shim_library(include, false, false)?;

// Modify and copy the libraries into a new directory.
let llib_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("llib");
let main_lib_name = prefix() + "mbedcrypto";
let shim_lib_name = prefix() + "shim";
objcopy(vec![
(main_lib, llib_path.join(format!("lib{}.a", main_lib_name))),
(shim_lib, llib_path.join(format!("lib{}.a", shim_lib_name))),
])?;
println!("cargo:rustc-link-search=native={}", llib_path.display());
println!("cargo:rustc-link-lib=static={}", main_lib_name);
println!("cargo:rustc-link-lib=static={}", shim_lib_name);
mbed_include_dir.push("include");
let main_lib = mbed_lib_dir.join("libmbedcrypto.a");

let include = mbed_include_dir.to_str().unwrap().to_owned();
common::generate_mbed_crypto_bindings(include.clone(), false)?;
let shim_lib = common::compile_shim_library(include, false, false)?;

// Modify and copy the libraries into a new directory.
let llib_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("llib");
let main_lib_name = prefix() + "mbedcrypto";
let shim_lib_name = prefix() + "shim";
objcopy(vec![
(main_lib, llib_path.join(format!("lib{}.a", main_lib_name))),
(shim_lib, llib_path.join(format!("lib{}.a", shim_lib_name))),
])?;
println!("cargo:rustc-link-search=native={}", llib_path.display());
println!("cargo:rustc-link-lib=static={}", main_lib_name);
println!("cargo:rustc-link-lib=static={}", shim_lib_name);
}
}

Ok(())
Expand Down
Loading