Debian Codegraph @

src/auditwheel/audit.rs

raw
1 use super::musllinux::{find_musl_libc, get_musl_version};
2 use super::policy::{Policy, MANYLINUX_POLICIES, MUSLLINUX_POLICIES};
3 use crate::auditwheel::{find_external_libs, PlatformTag};
4 use crate::compile::BuildArtifact;
5 use crate::target::Target;
6 use anyhow::{bail, Context, Result};
7 use fs_err::File;
8 use goblin::elf::{sym::STT_FUNC, Elf};
9 use lddtree::Library;
10 use once_cell::sync::Lazy;
11 use regex::Regex;
12 use serde::{Deserialize, Serialize};
13 use std::collections::{HashMap, HashSet};
14 use std::io::Read;
15 use std::path::{Path, PathBuf};
16 use std::{fmt, io};
17 use thiserror::Error;
18
19 static IS_LIBPYTHON: Lazy<Regex> =
20 Lazy::new(|| Regex::new(r"^libpython3\.\d+m?u?t?\.so\.\d+\.\d+$").unwrap());
21
22 /// Error raised during auditing an elf file for manylinux/musllinux compatibility
23 #[derive(Error, Debug)]
24 #[error("Ensuring manylinux/musllinux compliance failed")]
25 pub enum AuditWheelError {
26 /// The wheel couldn't be read
27 #[error("Failed to read the wheel")]
28 IoError(#[source] io::Error),
29 /// Reexports goblin parsing errors
30 #[error("Goblin failed to parse the elf file")]
31 GoblinError(#[source] goblin::error::Error),
32 /// The elf file isn't manylinux/musllinux compatible. Contains the list of offending
33 /// libraries.
34 #[error(
35 "Your library links libpython ({0}), which libraries must not do. Have you forgotten to activate the extension-module feature?",
36 )]
37 LinksLibPythonError(String),
38 /// The elf file isn't manylinux/musllinux compatible. Contains the list of offending
39 /// libraries.
40 #[error(
41 "Your library is not {0} compliant because it links the following forbidden libraries: {1:?}",
42 )]
43 LinksForbiddenLibrariesError(Policy, Vec<String>),
44 /// The elf file isn't manylinux/musllinux compatible. Contains the list of offending
45 /// libraries.
46 #[error(
47 "Your library is not {0} compliant because of the presence of too-recent versioned symbols: {1:?}. Consider building in a manylinux docker container",
48 )]
49 VersionedSymbolTooNewError(Policy, Vec<String>),
50 /// The elf file isn't manylinux/musllinux compatible. Contains the list of offending
51 /// libraries with blacked-list symbols.
52 #[error("Your library is not {0} compliant because it depends on black-listed symbols: {1:?}")]
53 BlackListedSymbolsError(Policy, Vec<String>),
54 /// The elf file isn't manylinux/musllinux compatible. Contains unsupported architecture
55 #[error("Your library is not {0} compliant because it has unsupported architecture: {1}")]
56 UnsupportedArchitecture(Policy, String),
57 /// This platform tag isn't defined by auditwheel yet
58 #[error("{0} compatibility policy is not defined by auditwheel yet, pass `--auditwheel=skip` to proceed anyway")]
59 UndefinedPolicy(PlatformTag),
60 /// Failed to analyze external shared library dependencies of the wheel
61 #[error("Failed to analyze external shared library dependencies of the wheel")]
62 DependencyAnalysisError(#[source] lddtree::Error),
63 }
64
65 /// Auditwheel mode
66 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
67 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
68 #[serde(rename_all = "lowercase")]
69 pub enum AuditWheelMode {
70 /// Audit and repair wheel for manylinux compliance
71 #[default]
72 Repair,
73 /// Check wheel for manylinux compliance, but do not repair
74 Check,
75 /// Don't check for manylinux compliance
76 Skip,
77 }
78
79 impl fmt::Display for AuditWheelMode {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 match self {
82 AuditWheelMode::Repair => write!(f, "repair"),
83 AuditWheelMode::Check => write!(f, "check"),
84 AuditWheelMode::Skip => write!(f, "skip"),
85 }
86 }
87 }
88
89 #[derive(Clone, Debug)]
90 pub struct VersionedLibrary {
91 /// library name
92 pub name: String,
93 /// versions needed
94 versions: HashSet<String>,
95 }
96
97 /// Find required dynamic linked libraries with version information
98 pub fn find_versioned_libraries(elf: &Elf) -> Vec<VersionedLibrary> {
99 let mut symbols = Vec::new();
100 if let Some(verneed) = &elf.verneed {
101 for need_file in verneed.iter() {
102 if let Some(name) = elf.dynstrtab.get_at(need_file.vn_file) {
103 // Skip dynamic linker/loader
104 if name.starts_with("ld-linux") || name == "ld64.so.2" || name == "ld64.so.1" {
105 continue;
106 }
107 let mut versions = HashSet::new();
108 for need_ver in need_file.iter() {
109 if let Some(aux_name) = elf.dynstrtab.get_at(need_ver.vna_name) {
110 versions.insert(aux_name.to_string());
111 }
112 }
113 symbols.push(VersionedLibrary {
114 name: name.to_string(),
115 versions,
116 });
117 }
118 }
119 }
120 symbols
121 }
122
123 /// Find incompliant symbols from symbol versions
124 #[allow(clippy::result_large_err)]
125 fn find_incompliant_symbols(
126 elf: &Elf,
127 symbol_versions: &[String],
128 ) -> Result<Vec<String>, AuditWheelError> {
129 let mut symbols = Vec::new();
130 let strtab = &elf.strtab;
131 for sym in &elf.syms {
132 if sym.st_type() == STT_FUNC {
133 let name = strtab.get_at(sym.st_name).unwrap_or("BAD NAME");
134 for symbol_version in symbol_versions {
135 if name.ends_with(&format!("@{symbol_version}")) {
136 symbols.push(name.to_string());
137 }
138 }
139 }
140 }
141 Ok(symbols)
142 }
143
144 #[allow(clippy::result_large_err)]
145 fn policy_is_satisfied(
146 policy: &Policy,
147 elf: &Elf,
148 arch: &str,
149 deps: &[String],
150 versioned_libraries: &[VersionedLibrary],
151 allow_linking_libpython: bool,
152 ) -> Result<(), AuditWheelError> {
153 let arch_versions = &policy.symbol_versions.get(arch).ok_or_else(|| {
154 AuditWheelError::UnsupportedArchitecture(policy.clone(), arch.to_string())
155 })?;
156 let mut offending_libs = HashSet::new();
157 let mut offending_versioned_syms = HashSet::new();
158 let mut offending_blacklist_syms = HashMap::new();
159 let undef_symbols: HashSet<String> = elf
160 .dynsyms
161 .iter()
162 .filter_map(|sym| {
163 if sym.st_shndx == goblin::elf::section_header::SHN_UNDEF as usize {
164 elf.dynstrtab.get_at(sym.st_name).map(ToString::to_string)
165 } else {
166 None
167 }
168 })
169 .collect();
170
171 for dep in deps {
172 // Skip dynamic linker/loader
173 if dep.starts_with("ld-linux") || dep == "ld64.so.2" || dep == "ld64.so.1" {
174 continue;
175 }
176 if !policy.lib_whitelist.contains(dep) {
177 if allow_linking_libpython && IS_LIBPYTHON.is_match(dep) {
178 continue;
179 }
180 offending_libs.insert(dep.clone());
181 }
182 if let Some(sym_list) = policy.blacklist.get(dep) {
183 let mut intersection: Vec<_> = sym_list.intersection(&undef_symbols).cloned().collect();
184 if !intersection.is_empty() {
185 intersection.sort();
186 offending_blacklist_syms.insert(dep, intersection);
187 }
188 }
189 }
190 for library in versioned_libraries {
191 if !policy.lib_whitelist.contains(&library.name) {
192 offending_libs.insert(library.name.clone());
193 continue;
194 }
195 let mut versions: HashMap<String, HashSet<String>> = HashMap::new();
196 for v in &library.versions {
197 let (name, version) = v.split_once('_').unwrap();
198 versions
199 .entry(name.to_string())
200 .or_default()
201 .insert(version.to_string());
202 }
203 for (name, versions_needed) in versions.iter() {
204 let versions_allowed = &arch_versions[name];
205 if !versions_needed.is_subset(versions_allowed) {
206 let offending_versions: Vec<&str> = versions_needed
207 .difference(versions_allowed)
208 .map(|v| v.as_ref())
209 .collect();
210 let offending_symbol_versions: Vec<String> = offending_versions
211 .iter()
212 .map(|v| format!("{name}_{v}"))
213 .collect();
214 let offending_symbols = find_incompliant_symbols(elf, &offending_symbol_versions)?;
215 let offender = if offending_symbols.is_empty() {
216 format!(
217 "{} offending versions: {}",
218 library.name,
219 offending_symbol_versions.join(", ")
220 )
221 } else {
222 format!(
223 "{} offending symbols: {}",
224 library.name,
225 offending_symbols.join(", ")
226 )
227 };
228 offending_versioned_syms.insert(offender);
229 }
230 }
231 }
232 // Check for black-listed symbols
233 if !offending_blacklist_syms.is_empty() {
234 let offenders = offending_blacklist_syms
235 .into_iter()
236 .map(|(lib, syms)| format!("{}: {}", lib, syms.join(", ")))
237 .collect();
238 return Err(AuditWheelError::BlackListedSymbolsError(
239 policy.clone(),
240 offenders,
241 ));
242 }
243 // Check for too-recent versioned symbols
244 if !offending_versioned_syms.is_empty() {
245 return Err(AuditWheelError::VersionedSymbolTooNewError(
246 policy.clone(),
247 offending_versioned_syms.into_iter().collect(),
248 ));
249 }
250 // Check for libpython and forbidden libraries
251 let offenders: Vec<String> = offending_libs.into_iter().collect();
252 match offenders.as_slice() {
253 [] => Ok(()),
254 [lib] if IS_LIBPYTHON.is_match(lib) => {
255 Err(AuditWheelError::LinksLibPythonError(lib.clone()))
256 }
257 offenders => Err(AuditWheelError::LinksForbiddenLibrariesError(
258 policy.clone(),
259 offenders.to_vec(),
260 )),
261 }
262 }
263
264 fn get_default_platform_policies() -> Vec<Policy> {
265 if let Ok(Some(musl_libc)) = find_musl_libc() {
266 if let Ok(Some((major, minor))) = get_musl_version(musl_libc) {
267 return MUSLLINUX_POLICIES
268 .iter()
269 .filter(|policy| {
270 policy.name == "linux" || policy.name == format!("musllinux_{major}_{minor}")
271 })
272 .cloned()
273 .collect();
274 }
275 }
276 MANYLINUX_POLICIES.clone()
277 }
278
279 /// An reimplementation of auditwheel, which checks elf files for
280 /// manylinux/musllinux compliance.
281 ///
282 /// If `platform_tag`, is None, it returns the the highest matching manylinux/musllinux policy
283 /// and whether we need to repair with patchelf,, or `linux` if nothing else matches.
284 /// It will error for bogus cases, e.g. if libpython is linked.
285 ///
286 /// If a specific manylinux/musllinux version is given, compliance is checked and a warning printed if
287 /// a higher version would be possible.
288 ///
289 /// Does nothing for `platform_tag` set to `Off`/`Linux` or non-linux platforms.
290 #[allow(clippy::result_large_err)]
291 pub fn auditwheel_rs(
292 artifact: &BuildArtifact,
293 target: &Target,
294 platform_tag: Option<PlatformTag>,
295 allow_linking_libpython: bool,
296 ) -> Result<(Policy, bool), AuditWheelError> {
297 if !target.is_linux() || platform_tag == Some(PlatformTag::Linux) {
298 return Ok((Policy::default(), false));
299 }
300 let path = &artifact.path;
301 let arch = target.target_arch().to_string();
302 let mut file = File::open(path).map_err(AuditWheelError::IoError)?;
303 let mut buffer = Vec::new();
304 file.read_to_end(&mut buffer)
305 .map_err(AuditWheelError::IoError)?;
306 let elf = Elf::parse(&buffer).map_err(AuditWheelError::GoblinError)?;
307 // This returns essentially the same as ldd
308 let deps: Vec<String> = elf.libraries.iter().map(ToString::to_string).collect();
309 let versioned_libraries = find_versioned_libraries(&elf);
310
311 // Find the highest possible policy, if any
312 let platform_policies = match platform_tag {
313 Some(PlatformTag::Manylinux { .. }) => MANYLINUX_POLICIES.clone(),
314 Some(PlatformTag::Musllinux { major, minor }) => MUSLLINUX_POLICIES
315 .clone()
316 .into_iter()
317 .filter(|policy| {
318 policy.name == "linux" || policy.name == format!("musllinux_{major}_{minor}")
319 })
320 .map(|mut policy| {
321 policy.fixup_musl_libc_so_name(target.target_arch());
322 policy
323 })
324 .collect(),
325 None | Some(PlatformTag::Pypi) => {
326 // Using the default for the `pypi` tag means we're correctly using manylinux where
327 // possible.
328 let mut policies = get_default_platform_policies();
329 for policy in &mut policies {
330 policy.fixup_musl_libc_so_name(target.target_arch());
331 }
332 policies
333 }
334 Some(PlatformTag::Linux) => unreachable!(),
335 };
336 let mut highest_policy = None;
337 let mut should_repair = false;
338 for policy in platform_policies.iter() {
339 let result = policy_is_satisfied(
340 policy,
341 &elf,
342 &arch,
343 &deps,
344 &versioned_libraries,
345 allow_linking_libpython,
346 );
347 match result {
348 Ok(_) => {
349 highest_policy = Some(policy.clone());
350 should_repair = false;
351 break;
352 }
353 Err(AuditWheelError::LinksForbiddenLibrariesError(..)) => {
354 highest_policy = Some(policy.clone());
355 should_repair = true;
356 break;
357 }
358 Err(AuditWheelError::VersionedSymbolTooNewError(..))
359 | Err(AuditWheelError::BlackListedSymbolsError(..))
360 // UnsupportedArchitecture happens when trying 2010 with aarch64
361 | Err(AuditWheelError::UnsupportedArchitecture(..)) => continue,
362 // If there was an error parsing the symbols or libpython was linked,
363 // we error no matter what the requested policy was
364 Err(err) => return Err(err),
365 }
366 }
367
368 let policy = if let Some(platform_tag) = platform_tag {
369 let mut policy = Policy::from_tag(&platform_tag)
370 .ok_or(AuditWheelError::UndefinedPolicy(platform_tag))?;
371 policy.fixup_musl_libc_so_name(target.target_arch());
372
373 if let Some(highest_policy) = highest_policy {
374 // Don't recommend manylinux1 because rust doesn't support it anymore
375 if policy.priority < highest_policy.priority && highest_policy.name != "manylinux_2_5" {
376 eprintln!(
377 "📦 Wheel is eligible for a higher priority tag. \
378 You requested {policy} but this wheel is eligible for {highest_policy}",
379 );
380 }
381 }
382
383 match policy_is_satisfied(
384 &policy,
385 &elf,
386 &arch,
387 &deps,
388 &versioned_libraries,
389 allow_linking_libpython,
390 ) {
391 Ok(_) => {
392 should_repair = false;
393 Ok(policy)
394 }
395 Err(AuditWheelError::LinksForbiddenLibrariesError(..)) => {
396 should_repair = true;
397 Ok(policy)
398 }
399 Err(err) => Err(err),
400 }
401 } else if let Some(policy) = highest_policy {
402 Ok(policy)
403 } else {
404 eprintln!(
405 "⚠️ Warning: No compatible platform tag found, using the linux tag instead. \
406 You won't be able to upload those wheels to PyPI."
407 );
408
409 // Fallback to linux
410 Ok(Policy::default())
411 }?;
412 Ok((policy, should_repair))
413 }
414
415 /// Get sysroot path from target C compiler
416 ///
417 /// Currently only gcc is supported, clang doesn't have a `--print-sysroot` option
418 pub fn get_sysroot_path(target: &Target) -> Result<PathBuf> {
419 use std::process::{Command, Stdio};
420
421 if let Some(sysroot) = std::env::var_os("TARGET_SYSROOT") {
422 return Ok(PathBuf::from(sysroot));
423 }
424
425 let host_triple = target.host_triple();
426 let target_triple = target.target_triple();
427 if host_triple != target_triple {
428 let mut build = cc::Build::new();
429 build
430 // Suppress cargo metadata for example env vars printing
431 .cargo_metadata(false)
432 // opt_level, host and target are required
433 .opt_level(0)
434 .host(host_triple)
435 .target(target_triple);
436 let compiler = build
437 .try_get_compiler()
438 .with_context(|| format!("Failed to get compiler for {target_triple}"))?;
439 // Only GNU like compilers support `--print-sysroot`
440 if !compiler.is_like_gnu() {
441 return Ok(PathBuf::from("/"));
442 }
443 let path = compiler.path();
444 let out = Command::new(path)
445 .arg("--print-sysroot")
446 .stdout(Stdio::piped())
447 .stderr(Stdio::null())
448 .output()
449 .with_context(|| format!("Failed to run `{} --print-sysroot`", path.display()))?;
450 if out.status.success() {
451 let sysroot = String::from_utf8(out.stdout)
452 .context("Failed to read the sysroot path")?
453 .trim()
454 .to_owned();
455 if sysroot.is_empty() {
456 return Ok(PathBuf::from("/"));
457 } else {
458 return Ok(PathBuf::from(sysroot));
459 }
460 } else {
461 bail!(
462 "Failed to get the sysroot path: {}",
463 String::from_utf8(out.stderr)?
464 );
465 }
466 }
467 Ok(PathBuf::from("/"))
468 }
469
470 /// For the given compilation result, return the manylinux platform and the external libs
471 /// we need to add to repair it
472 pub fn get_policy_and_libs(
473 artifact: &BuildArtifact,
474 platform_tag: Option<PlatformTag>,
475 target: &Target,
476 manifest_path: &Path,
477 allow_linking_libpython: bool,
478 ) -> Result<(Policy, Vec<Library>)> {
479 let (policy, should_repair) =
480 auditwheel_rs(artifact, target, platform_tag, allow_linking_libpython).with_context(
481 || {
482 if let Some(platform_tag) = platform_tag {
483 format!("Error ensuring {platform_tag} compliance")
484 } else {
485 "Error checking for manylinux/musllinux compliance".to_string()
486 }
487 },
488 )?;
489 let external_libs = if should_repair {
490 let sysroot = get_sysroot_path(target).unwrap_or_else(|_| PathBuf::from("/"));
491 let mut ld_paths: Vec<PathBuf> = artifact.linked_paths.iter().map(PathBuf::from).collect();
492
493 // Add library search paths from RUSTFLAGS
494 if let Some(rustflags_paths) = extract_rustflags_library_paths(manifest_path, target) {
495 ld_paths.extend(rustflags_paths);
496 }
497
498 let external_libs = find_external_libs(&artifact.path, &policy, sysroot, ld_paths)
499 .with_context(|| {
500 if let Some(platform_tag) = platform_tag {
501 format!("Error repairing wheel for {platform_tag} compliance")
502 } else {
503 "Error repairing wheel for manylinux/musllinux compliance".to_string()
504 }
505 })?;
506 if allow_linking_libpython {
507 external_libs
508 .into_iter()
509 .filter(|lib| !IS_LIBPYTHON.is_match(&lib.name))
510 .collect()
511 } else {
512 external_libs
513 }
514 } else {
515 Vec::new()
516 };
517 Ok((policy, external_libs))
518 }
519
520 /// Extract library search paths from RUSTFLAGS configuration
521 #[cfg_attr(test, allow(dead_code))]
522 fn extract_rustflags_library_paths(manifest_path: &Path, target: &Target) -> Option<Vec<PathBuf>> {
523 let manifest_dir = manifest_path.parent()?;
524 let config = cargo_config2::Config::load_with_cwd(manifest_dir).ok()?;
525 let rustflags = config.rustflags(target.target_triple()).ok()??;
526
527 // Encode the rustflags for parsing with the rustflags crate
528 let encoded = rustflags.encode().ok()?;
529
530 let mut library_paths = Vec::new();
531 for flag in rustflags::from_encoded(encoded.as_ref()) {
532 if let rustflags::Flag::LibrarySearchPath { kind: _, path } = flag {
533 library_paths.push(path);
534 }
535 }
536
537 if library_paths.is_empty() {
538 None
539 } else {
540 Some(library_paths)
541 }
542 }
543
544 pub fn relpath(to: &Path, from: &Path) -> PathBuf {
545 let mut suffix_pos = 0;
546 for (f, t) in from.components().zip(to.components()) {
547 if f == t {
548 suffix_pos += 1;
549 } else {
550 break;
551 }
552 }
553 let mut result = PathBuf::new();
554 from.components()
555 .skip(suffix_pos)
556 .map(|_| result.push(".."))
557 .last();
558 to.components()
559 .skip(suffix_pos)
560 .map(|x| result.push(x.as_os_str()))
561 .last();
562 result
563 }
564
565 #[cfg(test)]
566 mod test {
567 use crate::auditwheel::audit::relpath;
568 use crate::Target;
569 use pretty_assertions::assert_eq;
570 use std::path::Path;
571
572 #[test]
573 fn test_relpath() {
574 let cases = [
575 ("", "", ""),
576 ("/", "/usr", ".."),
577 ("/", "/usr/lib", "../.."),
578 ];
579 for (from, to, expected) in cases {
580 let from = Path::new(from);
581 let to = Path::new(to);
582 let result = relpath(from, to);
583 assert_eq!(result, Path::new(expected));
584 }
585 }
586
587 #[test]
588 fn test_extract_rustflags_library_paths() {
589 // Create a temporary directory with a Cargo.toml and .cargo/config.toml
590 let temp_dir = tempfile::tempdir().unwrap();
591 let manifest_path = temp_dir.path().join("Cargo.toml");
592 let cargo_dir = temp_dir.path().join(".cargo");
593 let config_path = cargo_dir.join("config.toml");
594
595 // Create the directories
596 fs_err::create_dir_all(&cargo_dir).unwrap();
597
598 // Create a minimal Cargo.toml
599 fs_err::write(
600 &manifest_path,
601 r#"
602 [package]
603 name = "test-package"
604 version = "0.1.0"
605 edition = "2021"
606 "#,
607 )
608 .unwrap();
609
610 // Create a config.toml with rustflags containing -L options
611 fs_err::write(
612 &config_path,
613 r#"
614 [build]
615 rustflags = ["-L", "dependency=/usr/local/lib", "-L", "/some/other/path", "-C", "opt-level=3"]
616 "#,
617 )
618 .unwrap();
619
620 // Test the function
621 let target = Target::from_target_triple(None).unwrap();
622 let paths = super::extract_rustflags_library_paths(&manifest_path, &target);
623
624 if let Some(paths) = paths {
625 assert_eq!(paths.len(), 2);
626 assert!(paths
627 .iter()
628 .any(|p| p.to_string_lossy() == "/usr/local/lib"));
629 assert!(paths
630 .iter()
631 .any(|p| p.to_string_lossy() == "/some/other/path"));
632 } else {
633 // It's possible that rustflags parsing fails in some environments,
634 // so we just verify the function doesn't panic
635 println!("No rustflags library paths found, which is acceptable");
636 }
637 }
638
639 #[test]
640 fn test_extract_rustflags_library_paths_no_config() {
641 // Test with a directory that has no cargo config
642 let temp_dir = tempfile::tempdir().unwrap();
643 let manifest_path = temp_dir.path().join("Cargo.toml");
644
645 // Create a minimal Cargo.toml
646 fs_err::write(
647 &manifest_path,
648 r#"
649 [package]
650 name = "test-package"
651 version = "0.1.0"
652 edition = "2021"
653 "#,
654 )
655 .unwrap();
656
657 let target = Target::from_target_triple(None).unwrap();
658 let paths = super::extract_rustflags_library_paths(&manifest_path, &target);
659
660 // Should return None when there's no cargo config with rustflags
661 assert!(paths.is_none());
662 }
663 }