forked from parallaxsecond/parsec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.rs
280 lines (254 loc) · 8.83 KB
/
build.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright (c) 2019, Arm Limited, All Rights Reserved
// SPDX-License-Identifier: Apache-2.0
//
// 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.
#![deny(
nonstandard_style,
const_err,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results,
missing_copy_implementations
)]
// This one is hard to avoid.
#![allow(clippy::multiple_crate_versions)]
use cargo_toml::{Manifest, Value};
use serde::Deserialize;
use std::env;
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
const CONFIG_TABLE_NAME: &str = "config";
const MBED_CRYPTO_VERSION_KEY: &str = "mbed-crypto-version";
const SETUP_MBED_SCRIPT_PATH: &str = "./setup_mbed_crypto.sh";
const BUILD_CONFIG_FILE_PATH: &str = "./build-conf.toml";
const DEFAULT_NATIVE_MBED_COMPILER: &str = "clang";
const DEFAULT_NATIVE_MBED_ARCHIVER: &str = "ar";
const DEFAULT_ARM64_MBED_COMPILER: &str = "aarch64-linux-gnu-gcc";
const DEFAULT_ARM64_MBED_ARCHIVER: &str = "aarch64-linux-gnu-ar";
#[derive(Debug, Deserialize)]
struct Configuration {
mbed_config: Option<MbedConfig>,
}
#[derive(Debug, Deserialize)]
struct MbedConfig {
mbed_path: Option<String>,
native: Option<Toolchain>,
aarch64_unknown_linux_gnu: Option<Toolchain>,
}
#[derive(Debug, Deserialize)]
struct Toolchain {
mbed_compiler: Option<String>,
mbed_archiver: Option<String>,
}
fn get_configuration_string(parsec_config: &Value, key: &str) -> Result<String> {
let config_value = get_value_from_table(parsec_config, key)?;
match config_value {
Value::String(string) => Ok(string.clone()),
_ => Err(Error::new(
ErrorKind::InvalidInput,
"Configuration key missing",
)),
}
}
fn get_value_from_table<'a>(table: &'a Value, key: &str) -> Result<&'a Value> {
match table {
Value::Table(table) => table.get(key).ok_or_else(|| {
println!("Config table does not contain configuration key: {}", key);
Error::new(ErrorKind::InvalidInput, "Configuration key missing.")
}),
_ => Err(Error::new(
ErrorKind::InvalidInput,
"Value provided is not a TOML table",
)),
}
}
// Get the Mbed Crypto version to branch on from Cargo.toml file. Use that and MbedConfig to pass
// parameters to the setup_mbed_crypto.sh script which clones and builds Mbed Crypto and create
// a static library.
fn setup_mbed_crypto(mbed_config: &MbedConfig, mbed_version: &str) -> Result<()> {
let (mbed_compiler, mbed_archiver) =
if std::env::var("TARGET").unwrap() == "aarch64-unknown-linux-gnu" {
let toolchain;
toolchain = mbed_config
.aarch64_unknown_linux_gnu
.as_ref()
.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"The aarch64_unknown_linux_gnu subtable of mbed_config should exist",
)
})?;
(
toolchain
.mbed_compiler
.clone()
.unwrap_or_else(|| DEFAULT_ARM64_MBED_COMPILER.to_string()),
toolchain
.mbed_archiver
.clone()
.unwrap_or_else(|| DEFAULT_ARM64_MBED_ARCHIVER.to_string()),
)
} else {
let toolchain;
toolchain = mbed_config.native.as_ref().ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"The native subtable of mbed_config should exist",
)
})?;
(
toolchain
.mbed_compiler
.clone()
.unwrap_or_else(|| DEFAULT_NATIVE_MBED_COMPILER.to_string()),
toolchain
.mbed_archiver
.clone()
.unwrap_or_else(|| DEFAULT_NATIVE_MBED_ARCHIVER.to_string()),
)
};
let script_fail = |_| {
Err(Error::new(
ErrorKind::Other,
"setup_mbed_crypto.sh script failed",
))
};
if !::std::process::Command::new(SETUP_MBED_SCRIPT_PATH)
.arg(mbed_version)
.arg(
mbed_config
.mbed_path
.clone()
.unwrap_or_else(|| env::var("OUT_DIR").unwrap()),
)
.arg(format!("CC={}", mbed_compiler))
.arg(format!("AR={}", mbed_archiver))
.status()
.or_else(script_fail)?
.success()
{
Err(Error::new(
ErrorKind::Other,
"setup_mbed_crypto.sh returned an error status.",
))
} else {
Ok(())
}
}
fn generate_mbed_bindings(mbed_config: &MbedConfig, mbed_version: &str) -> Result<()> {
let mbed_include_dir = mbed_config
.mbed_path
.clone()
.unwrap_or_else(|| env::var("OUT_DIR").unwrap())
+ "/mbed-crypto-"
+ mbed_version
+ "/include";
let header = mbed_include_dir.clone() + "/psa/crypto.h";
println!("cargo:rerun-if-changed={}", header);
let bindings = bindgen::Builder::default()
.clang_arg(format!("-I{}", mbed_include_dir))
.rustfmt_bindings(true)
.header(header)
.generate_comments(false)
.generate()
.or_else(|_| {
Err(Error::new(
ErrorKind::Other,
"Unable to generate bindings to mbed crypto",
))
})?;
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings.write_to_file(out_path.join("psa_crypto_bindings.rs"))
}
// Get the compiler, the archiver and the location where to clone the Mbed Crypto repository.
fn parse_config_file() -> Result<Configuration> {
let config_str = ::std::fs::read_to_string(Path::new(BUILD_CONFIG_FILE_PATH))?;
Ok(toml::from_str(&config_str).or_else(|e| {
println!("Error parsing build configuration file ({}).", e);
Err(Error::new(
ErrorKind::InvalidInput,
"Could not parse build configuration file.",
))
})?)
}
fn main() -> Result<()> {
// Parsing build-conf.toml
let config = parse_config_file()?;
// Parsing Cargo.toml
let toml_path = std::path::Path::new("./Cargo.toml");
if !toml_path.exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
"Could not find Cargo.toml.",
));
}
let manifest = Manifest::from_path(&toml_path).or_else(|e| {
println!("Error parsing Cargo.toml ({}).", e);
Err(Error::new(
ErrorKind::InvalidInput,
"Could not parse Cargo.toml.",
))
})?;
let package = manifest.package.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"Cargo.toml does not contain package information.",
)
})?;
let metadata = package.metadata.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"Cargo.toml does not contain package metadata.",
)
})?;
let parsec_config = get_value_from_table(&metadata, CONFIG_TABLE_NAME)?;
if cfg!(feature = "mbed-crypto-provider") {
let mbed_config = config.mbed_config.ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"Could not find mbed_config table in the config file.",
)
})?;
let mbed_version = get_configuration_string(&parsec_config, MBED_CRYPTO_VERSION_KEY)?;
setup_mbed_crypto(&mbed_config, &mbed_version)?;
generate_mbed_bindings(&mbed_config, &mbed_version)?;
// Request rustc to link the Mbed Crypto static library
println!(
"cargo:rustc-link-search=native={}/mbed-crypto-{}/library/",
mbed_config
.mbed_path
.unwrap_or_else(|| env::var("OUT_DIR").unwrap()),
mbed_version,
);
println!("cargo:rustc-link-lib=static=mbedcrypto");
}
Ok(())
}