Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls-sys/build.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use std::path::{Path, PathBuf};
5
6 const EXTERNAL_BUILD_CFG_NAME: &str = "s2n_tls_external_build";
7
8 fn main() {
9 println!("cargo:rustc-check-cfg=cfg({EXTERNAL_BUILD_CFG_NAME})");
10
11 let external = External::default();
12 if external.is_enabled() {
13 external.link();
14 } else {
15 build_vendored();
16 }
17 }
18
19 fn env<N: AsRef<str>>(name: N) -> String {
20 let name = name.as_ref();
21 option_env(name).unwrap_or_else(|| panic!("missing env var {name:?}"))
22 }
23
24 fn option_env<N: AsRef<str>>(name: N) -> Option<String> {
25 let name = name.as_ref();
26 println!("cargo:rerun-if-env-changed={name}");
27 std::env::var(name).ok()
28 }
29
30 struct FeatureDetector<'a> {
31 builder: cc::Build,
32 out_dir: &'a Path,
33 }
34
35 impl<'a> FeatureDetector<'a> {
36 pub fn new(out_dir: &'a Path, libcrypto: &Libcrypto) -> Self {
37 let builder = builder(libcrypto);
38 Self { builder, out_dir }
39 }
40
41 pub fn supports(&self, name: &str) -> bool {
42 let mut build = self.builder.get_compiler().to_command();
43
44 let global_flags = std::path::Path::new("lib/tests/features/GLOBAL.flags");
45 assert!(
46 global_flags.exists(),
47 "missing flags file: {:?}",
48 global_flags.display()
49 );
50
51 let global_flags = std::fs::read_to_string(global_flags).unwrap();
52 for flag in global_flags.trim().split(' ').filter(|f| !f.is_empty()) {
53 build.arg(flag);
54 }
55
56 let base = std::path::Path::new("lib/tests/features").join(name);
57
58 let file = base.with_extension("c");
59 assert!(file.exists(), "missing feature file: {:?}", file.display());
60
61 let probe_flags = base.with_extension("flags");
62 assert!(
63 probe_flags.exists(),
64 "missing flags file: {:?}",
65 probe_flags.display()
66 );
67
68 let probe_flags = std::fs::read_to_string(probe_flags).unwrap();
69 for flag in probe_flags.trim().split(' ').filter(|f| !f.is_empty()) {
70 build.arg(flag);
71 }
72
73 build
74 // just compile the file and don't link
75 .arg("-c")
76 .arg("-o")
77 .arg(self.out_dir.join(name).with_extension("o"))
78 .arg(&file);
79
80 eprintln!("=== Testing feature {name} ===");
81 build.status().unwrap().success()
82 }
83 }
84
85 fn build_vendored() {
86 let libcrypto = Libcrypto::default();
87
88 let mut build = builder(&libcrypto);
89
90 build.files(include!("./files.rs"));
91
92 // https://doc.rust-lang.org/cargo/reference/environment-variables.html
93 // * OPT_LEVEL, DEBUG — values of the corresponding variables for the profile currently being built.
94 // * PROFILE — release for release builds, debug for other builds. This is determined based on if
95 // the profile inherits from the dev or release profile. Using this environment variable is not
96 // recommended. Using other environment variables like OPT_LEVEL provide a more correct view of
97 // the actual settings being used.
98 if env("OPT_LEVEL") != "0" {
99 build.define("S2N_BUILD_RELEASE", "1");
100 build.define("NDEBUG", "1");
101
102 // build s2n-tls with LTO if supported
103 if build.get_compiler().is_like_gnu() {
104 build
105 .flag_if_supported("-flto")
106 .flag_if_supported("-ffat-lto-objects");
107 }
108 }
109
110 let out_dir = PathBuf::from(env("OUT_DIR"));
111
112 let features = FeatureDetector::new(&out_dir, &libcrypto);
113
114 let mut feature_names = std::fs::read_dir("lib/tests/features")
115 .expect("missing features directory")
116 .flatten()
117 .filter(|file| {
118 let file = file.path();
119 file.extension().is_some_and(|ext| ext == "c")
120 })
121 .map(|file| {
122 file.path()
123 .file_stem()
124 .unwrap()
125 .to_str()
126 .unwrap()
127 .to_string()
128 })
129 .collect::<Vec<_>>();
130
131 feature_names.sort();
132
133 for name in &feature_names {
134 let is_supported = features.supports(name);
135 eprintln!("{name}: {is_supported}");
136 if is_supported {
137 build.define(name, "1");
138
139 // stacktraces are only available if execinfo is
140 if name == "S2N_EXECINFO_AVAILABLE" && option_env("CARGO_FEATURE_STACKTRACE").is_some()
141 {
142 build.define("S2N_STACKTRACE", "1");
143 }
144 }
145 }
146
147 // don't spit out a bunch of warnings to the end user, since they won't really be able
148 // to do anything with it
149 build.warnings(false);
150
151 build.compile("s2n-tls");
152
153 // linking to the libcrypto is handled by the rust compiler through the
154 // `extern crate aws_lc_rs as _;` statement included in the generated source
155 // files. This is less brittle than manually linking the libcrypto artifact.
156
157 // let consumers know where to find our header files
158 let include_dir = out_dir.join("include");
159 std::fs::create_dir_all(&include_dir).unwrap();
160 std::fs::copy("lib/api/s2n.h", include_dir.join("s2n.h")).unwrap();
161 println!("cargo:include={}", include_dir.display());
162 }
163
164 fn builder(libcrypto: &Libcrypto) -> cc::Build {
165 let mut build = cc::Build::new();
166
167 let includes = [&libcrypto.include, "lib", "lib/api"];
168 if let Ok(cflags) = std::env::var("CFLAGS") {
169 // cc will read the CFLAGS env variable and prepend the compiler
170 // command with all flags and includes from it, which may conflict
171 // with the includes we specify. To ensure that our includes show
172 // up first in the compiler command, we prepend them to CFLAGS.
173 std::env::set_var("CFLAGS", format!("-I {} {}", includes.join(" -I "), cflags));
174 } else {
175 build.includes(includes);
176 };
177
178 build
179 .flag("-include")
180 .flag("lib/utils/s2n_prelude.h")
181 .flag("-std=c11")
182 .flag("-fgnu89-inline")
183 // make sure the stack is non-executable
184 .flag_if_supported("-z relro")
185 .flag_if_supported("-z now")
186 .flag_if_supported("-z noexecstack")
187 // we use some deprecated libcrypto features so don't warn here
188 .flag_if_supported("-Wno-deprecated-declarations")
189 .flag_if_supported("-Wa,-mbranches-within-32B-boundaries");
190
191 build
192 }
193
194 #[derive(PartialEq, Eq, PartialOrd, Ord)]
195 struct Libcrypto {
196 version: String,
197 link: String,
198 include: String,
199 root: String,
200 }
201
202 impl Default for Libcrypto {
203 fn default() -> Self {
204 for (name, value) in std::env::vars() {
205 if let Some(version) = name.strip_prefix("DEP_AWS_LC_") {
206 if let Some(version) = version.strip_suffix("_INCLUDE") {
207 let version = version.to_string();
208
209 println!("cargo:rerun-if-env-changed={name}");
210
211 let include = value;
212 let root = env(format!("DEP_AWS_LC_{version}_ROOT"));
213 let link = env(format!("DEP_AWS_LC_{version}_LIBCRYPTO"));
214
215 return Self {
216 version,
217 link,
218 include,
219 root,
220 };
221 }
222 }
223 }
224
225 panic!("missing DEP_AWS_LC paths");
226 }
227 }
228
229 struct External {
230 lib_dir: Option<PathBuf>,
231 include_dir: Option<PathBuf>,
232 }
233
234 impl Default for External {
235 fn default() -> Self {
236 let dir = option_env("S2N_TLS_DIR").map(PathBuf::from);
237
238 let lib_dir = option_env("S2N_TLS_LIB_DIR")
239 .map(PathBuf::from)
240 .or_else(|| dir.as_ref().map(|d| d.join("lib")));
241
242 let include_dir = option_env("S2N_TLS_INCLUDE_DIR")
243 .map(PathBuf::from)
244 .or_else(|| dir.as_ref().map(|d| d.join("include")));
245
246 Self {
247 lib_dir,
248 include_dir,
249 }
250 }
251 }
252
253 impl External {
254 fn is_enabled(&self) -> bool {
255 self.lib_dir.is_some()
256 }
257
258 fn link(&self) {
259 println!("cargo:rustc-cfg={EXTERNAL_BUILD_CFG_NAME}");
260
261 // Propagate an external build flag to dependents, of the form
262 // `DEP_S2N_TLS_EXTERNAL_BUILD=true`.
263 println!("cargo:external_build=true");
264
265 println!(
266 "cargo:rustc-link-search={}",
267 self.lib_dir.as_ref().unwrap().display()
268 );
269 println!("cargo:rustc-link-lib=s2n");
270
271 // tell rust we're linking with libcrypto
272 println!("cargo:rustc-link-lib=crypto");
273
274 if let Some(include_dir) = self.include_dir.as_ref() {
275 println!("cargo:include={}", include_dir.display());
276 }
277 }
278 }