Debian Codegraph @

debian/rust-vendor/selinux-sys/build.rs

raw
1 use std::borrow::Cow;
2 use std::ffi::{OsStr, OsString};
3 use std::path::{Path, PathBuf};
4 use std::{env, io, process, str};
5
6 use walkdir::WalkDir;
7
8 fn main() {
9 let target =
10 env::var("TARGET").expect("selinux-sys: Environment variable 'TARGET' was not defined");
11
12 let target_is_linux = target.contains("-linux-") || target.ends_with("-linux");
13 if !target_is_linux || target.ends_with("-kernel") {
14 return; // Nothing to build for this architecture.
15 }
16
17 let out_dir = env::var_os("OUT_DIR")
18 .map(PathBuf::from)
19 .expect("selinux-sys: Environment variable 'OUT_DIR' was not defined");
20
21 println!("cargo:root={}", path_to_str(&out_dir));
22
23 let sysroot = target_env_var_os("SYSROOT", &target).map(PathBuf::from);
24
25 let explicit_static = get_static_linking(&target);
26 let compiler_search_paths = get_compiler_search_paths(&target, sysroot.as_deref());
27
28 let include_path = find_and_output_include_dir(&compiler_search_paths.include_paths);
29 find_and_output_lib_dir(&compiler_search_paths.link_paths, &target, explicit_static);
30
31 generate_bindings(&target, sysroot.as_deref(), &out_dir, &include_path);
32 }
33
34 fn path_to_str(path: &Path) -> &str {
35 path.to_str().expect("selinux-sys: Path is not valid UTF-8")
36 }
37
38 #[cfg(feature = "static")]
39 fn get_static_linking(target: &str) -> Option<bool> {
40 target_env_var_os("SELINUX_STATIC", target)
41 .map(|v| v == "1" || v == "true")
42 .or_else(|| Some(true))
43 }
44
45 #[cfg(not(feature = "static"))]
46 fn get_static_linking(target: &str) -> Option<bool> {
47 target_env_var_os("SELINUX_STATIC", target).map(|v| v == "1" || v == "true")
48 }
49
50 fn get_compiler_search_paths(target: &str, sysroot: Option<&Path>) -> CompilerSearchPaths {
51 let explicit_path = target_env_var_os("SELINUX_PATH", target).map(PathBuf::from);
52
53 let mut include_dir = target_env_var_os("SELINUX_INCLUDE_DIR", target).map(PathBuf::from);
54 let mut link_dir = target_env_var_os("SELINUX_LIB_DIR", target).map(PathBuf::from);
55
56 for &name in &["CC", "CFLAGS"] {
57 target_env_var_os(name, target);
58 }
59
60 if let Some(explicit_path) = explicit_path {
61 if include_dir.is_none() {
62 include_dir = Some(explicit_path.join("include"));
63 }
64
65 if link_dir.is_none() {
66 link_dir = Some(explicit_path.join("lib"));
67 }
68 }
69
70 CompilerSearchPaths::new(sysroot, include_dir, link_dir)
71 }
72
73 #[derive(Debug)]
74 struct CompilerSearchPaths {
75 include_paths: Vec<PathBuf>,
76 link_paths: Vec<PathBuf>,
77 }
78
79 impl CompilerSearchPaths {
80 fn new(
81 sysroot: Option<&Path>,
82 include_dir: Option<PathBuf>,
83 link_dir: Option<PathBuf>,
84 ) -> Self {
85 unsafe { env::set_var("LANG", "C") };
86
87 let include_paths = Self::get_compiler_include_paths(sysroot, include_dir)
88 .expect("selinux-sys: Failed to discover default compiler search paths");
89
90 let link_paths = Self::get_compiler_link_paths(sysroot, link_dir)
91 .expect("selinux-sys: Failed to discover default linker search paths");
92
93 CompilerSearchPaths {
94 include_paths,
95 link_paths,
96 }
97 }
98
99 fn get_compiler_include_paths(
100 sysroot: Option<&Path>,
101 include_dir: Option<PathBuf>,
102 ) -> io::Result<Vec<PathBuf>> {
103 let mut compiler_builder = cc::Build::new();
104
105 if let Some(sysroot) = sysroot.map(Path::as_os_str).map(OsStr::to_str) {
106 let sysroot = sysroot.expect("SYSROOT is not encoded in UTF-8");
107 compiler_builder.flag(format!("--sysroot={sysroot}"));
108 }
109
110 if let Some(include_dir) = include_dir.as_deref() {
111 compiler_builder.include(include_dir);
112 }
113
114 let child = compiler_builder
115 .flag("-E")
116 .flag("-v")
117 .flag("-x")
118 .flag("c")
119 .get_compiler()
120 .to_command()
121 .arg("-") // stdin
122 .stdin(process::Stdio::null())
123 .stdout(process::Stdio::null())
124 .stderr(process::Stdio::piped())
125 .env("LANG", "C")
126 .spawn()?;
127
128 let output = child.wait_with_output()?;
129
130 if !output.status.success() {
131 return Err(io::Error::other(
132 "Compiler failed to print search directories",
133 ));
134 }
135
136 let mut paths = Vec::with_capacity(8);
137
138 if let Some(include_dir) = include_dir {
139 paths.push(include_dir);
140 }
141
142 paths.extend(
143 output
144 .stderr
145 .split(|&b| b == b'\n')
146 .skip_while(|&line| line != b"#include <...> search starts here:")
147 .take_while(|&line| line != b"End of search list.")
148 .filter_map(|bytes| str::from_utf8(bytes).ok())
149 .map(str::trim)
150 .filter_map(|s| dunce::canonicalize(s).ok()),
151 );
152
153 paths.dedup();
154 Ok(paths)
155 }
156
157 fn get_compiler_link_paths(
158 sysroot: Option<&Path>,
159 link_dir: Option<PathBuf>,
160 ) -> io::Result<Vec<PathBuf>> {
161 let mut compiler_builder = cc::Build::new();
162
163 if let Some(sysroot) = sysroot.map(Path::as_os_str).map(OsStr::to_str) {
164 let sysroot = sysroot.expect("SYSROOT is not encoded in UTF-8");
165 compiler_builder.flag(format!("--sysroot={sysroot}"));
166 }
167
168 if let Some(link_dir) = link_dir.as_deref() {
169 compiler_builder.flag("-L").flag(path_to_str(link_dir));
170 }
171
172 let child = compiler_builder
173 .flag("-v")
174 .flag("-print-search-dirs")
175 .get_compiler()
176 .to_command()
177 .stdout(process::Stdio::piped())
178 .stderr(process::Stdio::null())
179 .env("LANG", "C")
180 .spawn()?;
181
182 let output = child.wait_with_output()?;
183
184 if !output.status.success() {
185 return Err(io::Error::other(
186 "Compiler failed to print search directories",
187 ));
188 }
189
190 let line = output
191 .stdout
192 .split(|&b| b == b'\n')
193 .find_map(|line| line.strip_prefix(b"libraries:"))
194 .and_then(|bytes| str::from_utf8(bytes).ok())
195 .map(str::trim)
196 .map(|line| line.trim_start_matches('='))
197 .ok_or_else(|| {
198 io::Error::other("Compiler search directories format is unrecognized")
199 })?;
200
201 let mut paths = Vec::with_capacity(8);
202
203 if let Some(link_dir) = link_dir {
204 paths.push(link_dir);
205 }
206
207 if let Some(lib_paths) = env::var_os("LIBRARY_PATH") {
208 paths.extend(env::split_paths(&lib_paths).filter_map(|s| dunce::canonicalize(s).ok()));
209 }
210
211 paths.extend(env::split_paths(line).filter_map(|s| dunce::canonicalize(s).ok()));
212
213 paths.dedup();
214 Ok(paths)
215 }
216 }
217
218 fn target_env_var_os(name: &str, target: &str) -> Option<OsString> {
219 rerun_if_env_changed(name, target);
220
221 let target_underscores = target.replace('-', "_");
222
223 env::var_os(format!("{name}_{target}"))
224 .or_else(|| env::var_os(format!("{name}_{target_underscores}")))
225 .or_else(|| env::var_os(format!("TARGET_{name}")))
226 .or_else(|| env::var_os(name))
227 }
228
229 fn rerun_if_env_changed(name: &str, target: &str) {
230 let target_underscores = target.replace('-', "_");
231
232 println!("cargo:rerun-if-env-changed={name}_{target}");
233 println!("cargo:rerun-if-env-changed={name}_{target_underscores}");
234 println!("cargo:rerun-if-env-changed=TARGET_{name}");
235 println!("cargo:rerun-if-env-changed={name}");
236 }
237
238 fn rerun_if_dir_changed(dir: &Path) {
239 for file in WalkDir::new(dir).follow_links(false).same_file_system(true) {
240 if let Ok(file) = file {
241 println!("cargo:rerun-if-changed={}", file.path().display());
242 } else {
243 panic!(
244 "selinux-sys: Failed to list directory contents: {}",
245 dir.display()
246 );
247 }
248 }
249 }
250
251 fn find_and_output_include_dir(include_paths: &[PathBuf]) -> PathBuf {
252 let include_path = find_file_in_dirs("selinux/selinux.h", include_paths)
253 .expect("selinux-sys: Failed to find 'selinux/selinux.h'. Please make sure the C header files of libselinux are installed and accessible");
254
255 rerun_if_dir_changed(&include_path.join("selinux"));
256
257 println!("cargo:include={}", path_to_str(&include_path));
258
259 include_path
260 }
261
262 fn output_lib_dir(dir: &Path, file: &Path, static_lib: bool) {
263 println!("cargo:rerun-if-changed={}", file.display());
264
265 println!("cargo:lib={}", path_to_str(dir));
266
267 println!("cargo:rustc-link-search=native={}", path_to_str(dir));
268
269 println!(
270 "cargo:rustc-link-lib={}=selinux",
271 if static_lib { "static" } else { "dylib" }
272 );
273 }
274
275 fn find_and_output_lib_dir(link_paths: &[PathBuf], target: &str, explicit_static: Option<bool>) {
276 let lib_configs = match explicit_static {
277 Some(false) => vec![false],
278
279 Some(true) => vec![true],
280
281 None => {
282 if target.contains("-musl") {
283 vec![true, false]
284 } else {
285 vec![false, true]
286 }
287 }
288 };
289
290 for static_lib in lib_configs {
291 let file_name = format!("libselinux{}", if static_lib { ".a" } else { ".so" });
292
293 if let Ok(lib_path) = find_file_in_dirs(&file_name, link_paths) {
294 output_lib_dir(&lib_path, &lib_path.join(&file_name), static_lib);
295 return;
296 }
297
298 if let Some(link_path) = link_paths.first() {
299 let triplet = target.replace("-unknown-", "-").replace("-none-", "-");
300
301 for &lib_dir in &[link_path, &link_path.join(target), &link_path.join(triplet)] {
302 let lib_path = lib_dir.join(&file_name);
303 if let Ok(md) = lib_path.metadata()
304 && md.is_file()
305 {
306 output_lib_dir(lib_dir, &lib_path, static_lib);
307 return;
308 }
309 }
310 }
311 }
312 }
313
314 // See: https://github.com/rust-lang/rust-bindgen/issues/2136
315 fn translate_rustc_target_to_clang(rustc_target: &str) -> Cow<'_, str> {
316 if let Some(suffix) = rustc_target.strip_prefix("riscv32") {
317 let suffix = suffix.trim_start_matches(|c| c != '-');
318 Cow::Owned(format!("riscv32{suffix}"))
319 } else if let Some(suffix) = rustc_target.strip_prefix("riscv64") {
320 let suffix = suffix.trim_start_matches(|c| c != '-');
321 Cow::Owned(format!("riscv64{suffix}"))
322 } else if let Some(suffix) = rustc_target.strip_prefix("aarch64-apple-") {
323 Cow::Owned(format!("arm64-apple-{suffix}"))
324 } else if let Some(prefix) = rustc_target.strip_suffix("-espidf") {
325 Cow::Owned(format!("{prefix}-elf"))
326 } else {
327 Cow::Borrowed(rustc_target)
328 }
329 }
330
331 fn generate_bindings(target: &str, sysroot: Option<&Path>, out_dir: &Path, include_path: &Path) {
332 let clang_target = translate_rustc_target_to_clang(target);
333
334 let mut builder = bindgen::Builder::default()
335 .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
336 .default_enum_style(bindgen::EnumVariation::ModuleConsts)
337 .default_macro_constant_type(bindgen::MacroTypeVariation::Signed)
338 .size_t_is_usize(true)
339 .derive_debug(true)
340 .derive_copy(true)
341 .derive_eq(true)
342 .derive_ord(true)
343 .impl_debug(true)
344 .no_partialeq("^avc_([_a-zA-Z0-9]+)_callback$")
345 .clang_arg(format!("--target={clang_target}"))
346 .clang_args(&["-I", path_to_str(include_path)]);
347
348 if let Some(sysroot) = sysroot.map(Path::as_os_str).map(OsStr::to_str) {
349 let sysroot = sysroot.expect("SYSROOT is not encoded in UTF-8");
350 builder = builder.clang_arg(format!("--sysroot={sysroot}"));
351 }
352
353 // Do not expose deprecated functions.
354 for &blacklisted_function in &[
355 "(avc_init|security_load_booleans|checkPasswdAccess|rpm_execcon)",
356 "selinux_(booleans_path|users_path|check_passwd_access)",
357 "security_compute_user(_raw)?",
358 "sid(get|put)",
359 "matchpathcon(_init|_init_prefix|_fini|_index)?",
360 ] {
361 builder = builder.blocklist_function(blacklisted_function);
362 }
363
364 // Do not expose deprecated types.
365 for &type_re in &["security_context_t", "^__u?int[0-9]+_t$"] {
366 builder = builder.blocklist_type(type_re);
367 }
368
369 // Expose documented functions.
370 for &function in &[
371 "(f|l)?(g|s)et(file|exec|fscreate|keycreate|sockcreate|peer|pid|prev)?con(_raw)?",
372 "freecon(ary)?",
373 "(set_)?match(path|media)con(_.+)?",
374 "(is_)?(security|selabel|selinux|avc|context)_.+",
375 "(init|fini|set)_selinuxmnt",
376 "get_(default|ordered)_(context|type).*",
377 "(string|mode)_to_(security_class|av_perm)",
378 "getseuser(byname)?",
379 "manual_user_enter_context",
380 "print_access_vector",
381 "query_user_context",
382 ] {
383 builder = builder.allowlist_function(function);
384 }
385
386 // Expose documented types and constants.
387 builder = builder
388 .allowlist_type("(security|selinux|access|av|avc|SEL)_.+")
389 .allowlist_var("(SELINUX|SELABEL|MATCHPATHCON|SECSID|AVC)_.+");
390
391 // Include all SELinux headers.
392 builder = builder.header("src/selinux-sys.h");
393
394 // Define macros to include headers that actually exist.
395 for &optional_header in &["restorecon.h", "get_context_list.h", "get_default_type.h"] {
396 let path = include_path.join("selinux").join(optional_header);
397 if let Ok(md) = path.metadata()
398 && md.file_type().is_file()
399 {
400 let mut def = format!("SELINUX_SYS_{}", optional_header.replace('.', "_"));
401 def.make_ascii_uppercase();
402 builder = builder.clang_args(&["-D", &def]);
403 }
404 }
405
406 let bindings = builder.generate().expect(
407 "selinux-sys: Failed to generate Rust bindings for 'selinux/selinux.h' and other headers",
408 );
409
410 bindings
411 .write_to_file(out_dir.join("selinux-sys.rs"))
412 .expect("selinux-sys: Failed to write 'selinux-sys.rs'");
413 }
414
415 fn find_file_in_dirs(path_suffix: &str, dirs: &[PathBuf]) -> io::Result<PathBuf> {
416 for dir in dirs {
417 if let Ok(md) = dir.join(path_suffix).metadata()
418 && md.file_type().is_file()
419 {
420 return Ok(dir.clone());
421 }
422 }
423
424 Err(io::ErrorKind::NotFound.into())
425 }