Debian Codegraph @

src/build_context.rs

raw ◀ ▶
1 Debian patch touch this file
1 use crate::auditwheel::{get_policy_and_libs, patchelf, relpath, AuditWheelMode};
2 use crate::auditwheel::{PlatformTag, Policy};
3 use crate::bridge::Abi3Version;
4 use crate::build_options::CargoOptions;
5 use crate::compile::{warn_missing_py_init, CompileTarget};
6 use crate::compression::CompressionOptions;
7 use crate::module_writer::{
8 add_data, write_bin, write_bindings_module, write_cffi_module, write_python_part,
9 write_uniffi_module, write_wasm_launcher, WheelWriter,
10 };
11 use crate::project_layout::ProjectLayout;
12 use crate::source_distribution::source_distribution;
13 use crate::target::validate_wheel_filename_for_pypi;
14 use crate::target::{Arch, Os};
15 use crate::{
16 compile, pyproject_toml::Format, BridgeModel, BuildArtifact, Metadata24, ModuleWriter,
17 PyProjectToml, PythonInterpreter, Target,
18 };
19 use anyhow::{anyhow, bail, Context, Result};
20 use cargo_metadata::CrateType;
21 use cargo_metadata::Metadata;
22 use fs_err as fs;
23 use ignore::overrides::{Override, OverrideBuilder};
24 use indexmap::IndexMap;
25 use lddtree::Library;
26 use normpath::PathExt;
27 use pep508_rs::Requirement;
28 use platform_info::*;
29 use sha2::{Digest, Sha256};
30 use std::collections::{BTreeMap, HashSet};
31 use std::env;
32 use std::io;
33 use std::path::{Path, PathBuf};
34 use std::str::FromStr;
35 use tracing::instrument;
36
37 /// Insert wasm launcher scripts as entrypoints and the wasmtime dependency
38 fn bin_wasi_helper(
39 artifacts_and_files: &[(&BuildArtifact, String)],
40 mut metadata24: Metadata24,
41 ) -> Result<Metadata24> {
42 eprintln!("⚠️ Warning: wasi support is experimental");
43 // escaped can contain [\w\d.], but i don't know how we'd handle dots correctly here
44 if metadata24.get_distribution_escaped().contains('.') {
45 bail!(
46 "Can't build wasm wheel if there is a dot in the name ('{}')",
47 metadata24.get_distribution_escaped()
48 )
49 }
50 if !metadata24.entry_points.is_empty() {
51 bail!("You can't define entrypoints yourself for a binary project");
52 }
53
54 let mut console_scripts = IndexMap::new();
55 for (_, bin_name) in artifacts_and_files {
56 let base_name = bin_name
57 .strip_suffix(".wasm")
58 .context("No .wasm suffix in wasi binary")?;
59 console_scripts.insert(
60 base_name.to_string(),
61 format!(
62 "{}.{}:main",
63 metadata24.get_distribution_escaped(),
64 base_name.replace('-', "_")
65 ),
66 );
67 }
68
69 metadata24
70 .entry_points
71 .insert("console_scripts".to_string(), console_scripts);
72
73 // Add our wasmtime default version if the user didn't provide one
74 if !metadata24
75 .requires_dist
76 .iter()
77 .any(|requirement| requirement.name.as_ref() == "wasmtime")
78 {
79 // Having the wasmtime version hardcoded is not ideal, it's easy enough to overwrite
80 metadata24
81 .requires_dist
82 .push(Requirement::from_str("wasmtime>=11.0.0,<12.0.0").unwrap());
83 }
84
85 Ok(metadata24)
86 }
87
88 /// Contains all the metadata required to build the crate
89 #[derive(Clone)]
90 pub struct BuildContext {
91 /// The platform, i.e. os and pointer width
92 pub target: Target,
93 /// List of Cargo targets to compile
94 pub compile_targets: Vec<CompileTarget>,
95 /// Whether this project is pure rust or rust mixed with python
96 pub project_layout: ProjectLayout,
97 /// The path to pyproject.toml. Required for the source distribution
98 pub pyproject_toml_path: PathBuf,
99 /// Parsed pyproject.toml if any
100 pub pyproject_toml: Option<PyProjectToml>,
101 /// Python Package Metadata 2.3
102 pub metadata24: Metadata24,
103 /// The name of the crate
104 pub crate_name: String,
105 /// The name of the module can be distinct from the package name, mostly
106 /// because package names normally contain minuses while module names
107 /// have underscores. The package name is part of metadata24
108 pub module_name: String,
109 /// The path to the Cargo.toml. Required for the cargo invocations
110 pub manifest_path: PathBuf,
111 /// Directory for all generated artifacts
112 pub target_dir: PathBuf,
113 /// The directory to store the built wheels in. Defaults to a new "wheels"
114 /// directory in the project's target directory
115 pub out: PathBuf,
116 /// Build artifacts in release mode, with optimizations
117 pub release: bool,
118 /// Strip the library for minimum file size
119 pub strip: bool,
120 /// Checking the linked libraries for manylinux/musllinux compliance
121 pub auditwheel: AuditWheelMode,
122 /// When compiling for manylinux, use zig as linker to ensure glibc version compliance
123 #[cfg(feature = "zig")]
124 pub zig: bool,
125 /// Whether to use the manylinux/musllinux or use the native linux tag (off)
126 pub platform_tag: Vec<PlatformTag>,
127 /// The available python interpreter
128 pub interpreter: Vec<PythonInterpreter>,
129 /// Cargo.toml as resolved by [cargo_metadata]
130 pub cargo_metadata: Metadata,
131 /// Whether to use universal2 or use the native macOS tag (off)
132 pub universal2: bool,
133 /// Build editable wheels
134 pub editable: bool,
135 /// Cargo build options
136 pub cargo_options: CargoOptions,
137 /// Compression options
138 pub compression: CompressionOptions,
139 /// Whether to validate wheels against PyPI platform tag rules
140 pub pypi_validation: bool,
141 }
142
143 /// The wheel file location and its Python version tag (e.g. `py3`).
144 ///
145 /// For bindings the version tag contains the Python interpreter version
146 /// they bind against (e.g. `cp37`).
147 pub type BuiltWheelMetadata = (PathBuf, String);
148
149 impl BuildContext {
150 /// Checks which kind of bindings we have (pyo3/rust-cypthon or cffi or bin) and calls the
151 /// correct builder.
152 #[instrument(skip_all)]
153 pub fn build_wheels(&self) -> Result<Vec<BuiltWheelMetadata>> {
154 use itertools::Itertools;
155
156 fs::create_dir_all(&self.out)
157 .context("Failed to create the target directory for the wheels")?;
158
159 let wheels = match self.bridge() {
160 BridgeModel::Bin(None) => self.build_bin_wheel(None)?,
161 BridgeModel::Bin(Some(..)) => self.build_bin_wheels(&self.interpreter)?,
162 BridgeModel::PyO3(crate::PyO3 { abi3, .. }) => match abi3 {
163 Some(Abi3Version::Version(major, minor)) => {
164 let abi3_interps: Vec<_> = self
165 .interpreter
166 .iter()
167 .filter(|interp| interp.has_stable_api())
168 .cloned()
169 .collect();
170 let non_abi3_interps: Vec<_> = self
171 .interpreter
172 .iter()
173 .filter(|interp| !interp.has_stable_api())
174 .cloned()
175 .collect();
176 let mut built_wheels = Vec::new();
177 if !abi3_interps.is_empty() {
178 built_wheels.extend(self.build_pyo3_wheel_abi3(
179 &abi3_interps,
180 *major,
181 *minor,
182 )?);
183 }
184 if !non_abi3_interps.is_empty() {
185 let interp_names: HashSet<_> = non_abi3_interps
186 .iter()
187 .map(|interp| interp.to_string())
188 .collect();
189 eprintln!(
190 "⚠️ Warning: {} does not yet support abi3 so the build artifacts will be version-specific.",
191 interp_names.iter().join(", ")
192 );
193 built_wheels.extend(self.build_pyo3_wheels(&non_abi3_interps)?);
194 }
195 built_wheels
196 }
197 Some(Abi3Version::CurrentPython) => {
198 let abi3_interps: Vec<_> = self
199 .interpreter
200 .iter()
201 .filter(|interp| interp.has_stable_api())
202 .cloned()
203 .collect();
204 let non_abi3_interps: Vec<_> = self
205 .interpreter
206 .iter()
207 .filter(|interp| !interp.has_stable_api())
208 .cloned()
209 .collect();
210 let mut built_wheels = Vec::new();
211 if !abi3_interps.is_empty() {
212 let interp = abi3_interps.first().unwrap();
213 built_wheels.extend(self.build_pyo3_wheel_abi3(
214 &abi3_interps,
215 interp.major as u8,
216 interp.minor as u8,
217 )?);
218 }
219 if !non_abi3_interps.is_empty() {
220 let interp_names: HashSet<_> = non_abi3_interps
221 .iter()
222 .map(|interp| interp.to_string())
223 .collect();
224 eprintln!(
225 "⚠️ Warning: {} does not yet support abi3 so the build artifacts will be version-specific.",
226 interp_names.iter().join(", ")
227 );
228 built_wheels.extend(self.build_pyo3_wheels(&non_abi3_interps)?);
229 }
230 built_wheels
231 }
232 None => self.build_pyo3_wheels(&self.interpreter)?,
233 },
234 BridgeModel::Cffi => self.build_cffi_wheel()?,
235 BridgeModel::UniFfi => self.build_uniffi_wheel()?,
236 };
237
238 // Validate wheel filenames against PyPI platform tag rules if requested
239 if self.pypi_validation {
240 for wheel in &wheels {
241 let filename = wheel
242 .0
243 .file_name()
244 .and_then(|name| name.to_str())
245 .ok_or_else(|| anyhow!("Invalid wheel filename: {:?}", wheel.0))?;
246
247 if let Err(error) = validate_wheel_filename_for_pypi(filename) {
248 bail!("PyPI validation failed: {}", error);
249 }
250 }
251 }
252
253 Ok(wheels)
254 }
255
256 /// Bridge model
257 pub fn bridge(&self) -> &BridgeModel {
258 // FIXME: currently we only allow multiple bin targets so bridges are all the same
259 &self.compile_targets[0].bridge_model
260 }
261
262 /// Builds a source distribution and returns the same metadata as [BuildContext::build_wheels]
263 pub fn build_source_distribution(&self) -> Result<Option<BuiltWheelMetadata>> {
264 fs::create_dir_all(&self.out)
265 .context("Failed to create the target directory for the source distribution")?;
266
267 match self.pyproject_toml.as_ref() {
268 Some(pyproject) => {
269 let sdist_path =
270 source_distribution(self, pyproject, self.excludes(Format::Sdist)?)
271 .context("Failed to build source distribution")?;
272 Ok(Some((sdist_path, "source".to_string())))
273 }
274 None => Ok(None),
275 }
276 }
277
278 /// Return the tags of the wheel that this build context builds.
279 pub fn tags_from_bridge(&self) -> Result<Vec<String>> {
280 let tags = match self.bridge() {
281 BridgeModel::PyO3(bindings) | BridgeModel::Bin(Some(bindings)) => match bindings.abi3 {
282 Some(Abi3Version::Version(major, minor)) => {
283 let platform = self.get_platform_tag(&[PlatformTag::Linux])?;
284 vec![format!("cp{major}{minor}-abi3-{platform}")]
285 }
286 Some(Abi3Version::CurrentPython) => {
287 let interp = &self.interpreter[0];
288 let platform = self.get_platform_tag(&[PlatformTag::Linux])?;
289 vec![format!(
290 "cp{major}{minor}-abi3-{platform}",
291 major = interp.major,
292 minor = interp.minor
293 )]
294 }
295 None => {
296 vec![self.interpreter[0].get_tag(self, &[PlatformTag::Linux])?]
297 }
298 },
299 BridgeModel::Bin(None) | BridgeModel::Cffi | BridgeModel::UniFfi => {
300 self.get_universal_tags(&[PlatformTag::Linux])?.1
301 }
302 };
303 Ok(tags)
304 }
305
306 fn auditwheel(
307 &self,
308 artifact: &BuildArtifact,
309 platform_tag: &[PlatformTag],
310 python_interpreter: Option<&PythonInterpreter>,
311 ) -> Result<(Policy, Vec<Library>)> {
312 if matches!(self.auditwheel, AuditWheelMode::Skip) {
313 return Ok((Policy::default(), Vec::new()));
314 }
315
316 if let Some(python_interpreter) = python_interpreter {
317 if platform_tag.is_empty()
318 && self.target.is_linux()
319 && !python_interpreter.support_portable_wheels()
320 {
321 eprintln!(
322 "🐍 Skipping auditwheel because {python_interpreter} does not support manylinux/musllinux wheels"
323 );
324 return Ok((Policy::default(), Vec::new()));
325 }
326 }
327
328 let mut musllinux: Vec<_> = platform_tag
329 .iter()
330 .filter(|tag| tag.is_musllinux())
331 .copied()
332 .collect();
333 musllinux.sort();
334 let mut others: Vec<_> = platform_tag
335 .iter()
336 .filter(|tag| !tag.is_musllinux())
337 .copied()
338 .collect();
339 others.sort();
340
341 // only bin bindings allow linking to libpython, extension modules must not
342 let allow_linking_libpython = self.bridge().is_bin();
343 if self.bridge().is_bin() && !musllinux.is_empty() {
344 return get_policy_and_libs(
345 artifact,
346 Some(musllinux[0]),
347 &self.target,
348 &self.manifest_path,
349 allow_linking_libpython,
350 );
351 }
352
353 let tag = others.first().or_else(|| musllinux.first()).copied();
354 get_policy_and_libs(
355 artifact,
356 tag,
357 &self.target,
358 &self.manifest_path,
359 allow_linking_libpython,
360 )
361 }
362
363 /// Add library search paths in Cargo target directory rpath when building in editable mode
364 fn add_rpath(&self, artifacts: &[&BuildArtifact]) -> Result<()> {
365 if self.editable && self.target.is_linux() && !artifacts.is_empty() {
366 for artifact in artifacts {
367 if artifact.linked_paths.is_empty() {
368 continue;
369 }
370 let old_rpaths = patchelf::get_rpath(&artifact.path)?;
371 let mut new_rpaths = old_rpaths.clone();
372 for path in &artifact.linked_paths {
373 if !old_rpaths.contains(path) {
374 new_rpaths.push(path.to_string());
375 }
376 }
377 let new_rpath = new_rpaths.join(":");
378 if let Err(err) = patchelf::set_rpath(&artifact.path, &new_rpath) {
379 eprintln!(
380 "⚠️ Warning: Failed to set rpath for {}: {}",
381 artifact.path.display(),
382 err
383 );
384 }
385 }
386 }
387 Ok(())
388 }
389
390 fn add_external_libs(
391 &self,
392 writer: &mut WheelWriter,
393 artifacts: &[&BuildArtifact],
394 ext_libs: &[Vec<Library>],
395 ) -> Result<()> {
396 if self.editable {
397 return self.add_rpath(artifacts);
398 }
399 if ext_libs.iter().all(|libs| libs.is_empty()) {
400 return Ok(());
401 }
402
403 if matches!(self.auditwheel, AuditWheelMode::Check) {
404 eprintln!("🖨️ Your library is not manylinux/musllinux compliant because it requires copying the following libraries:");
405 for lib in ext_libs.iter().flatten() {
406 if let Some(path) = lib.realpath.as_ref() {
407 eprintln!(" {} => {}", lib.name, path.display())
408 } else {
409 eprintln!(" {} => not found", lib.name)
410 };
411 }
412 bail!("Can not repair the wheel because `--auditwheel=check` is specified, re-run with `--auditwheel=repair` to copy the libraries.");
413 }
414
415 patchelf::verify_patchelf()?;
416
417 // Put external libs to ${module_name}.libs directory
418 // See https://github.com/pypa/auditwheel/issues/89
419 let mut libs_dir = self
420 .project_layout
421 .python_module
422 .as_ref()
423 .and_then(|py| py.file_name().map(|s| s.to_os_string()))
424 .unwrap_or_else(|| self.module_name.clone().into());
425 libs_dir.push(".libs");
426 let libs_dir = PathBuf::from(libs_dir);
427 writer.add_directory(&libs_dir)?;
428
429 let temp_dir = tempfile::tempdir()?;
430 let mut soname_map = BTreeMap::new();
431 let mut libs_copied = HashSet::new();
432 for lib in ext_libs.iter().flatten() {
433 let lib_path = lib.realpath.clone().with_context(|| {
434 format!(
435 "Cannot repair wheel, because required library {} could not be located.",
436 lib.path.display()
437 )
438 })?;
439 // Generate a new soname with a short hash
440 let short_hash = &hash_file(&lib_path)?[..8];
441 let (file_stem, file_ext) = lib.name.split_once('.').unwrap();
442 let new_soname = if !file_stem.ends_with(&format!("-{short_hash}")) {
443 format!("{file_stem}-{short_hash}.{file_ext}")
444 } else {
445 format!("{file_stem}.{file_ext}")
446 };
447
448 // Copy the original lib to a tmpdir and modify some of its properties
449 // for example soname and rpath
450 let dest_path = temp_dir.path().join(&new_soname);
451 fs::copy(&lib_path, &dest_path)?;
452 libs_copied.insert(lib_path);
453
454 // fs::copy copies permissions as well, and the original
455 // file may have been read-only
456 let mut perms = fs::metadata(&dest_path)?.permissions();
457 #[allow(clippy::permissions_set_readonly_false)]
458 perms.set_readonly(false);
459 fs::set_permissions(&dest_path, perms)?;
460
461 patchelf::set_soname(&dest_path, &new_soname)?;
•462 if !lib.rpath.is_empty() {
463 patchelf::set_rpath(&dest_path, &libs_dir)?;
464 }
465 soname_map.insert(
466 lib.name.clone(),
467 (new_soname.clone(), dest_path.clone(), lib.needed.clone()),
468 );
469 }
470
471 for (artifact, artifact_ext_libs) in artifacts.iter().zip(ext_libs) {
472 let artifact_deps: HashSet<_> = artifact_ext_libs.iter().map(|lib| &lib.name).collect();
473 let replacements = soname_map
474 .iter()
475 .filter_map(|(k, v)| {
476 if artifact_deps.contains(k) {
477 Some((k, v.0.clone()))
478 } else {
479 None
480 }
481 })
482 .collect::<Vec<_>>();
483 if !replacements.is_empty() {
484 patchelf::replace_needed(&artifact.path, &replacements[..])?;
485 }
486 }
487
488 // we grafted in a bunch of libraries and modified their sonames, but
489 // they may have internal dependencies (DT_NEEDED) on one another, so
490 // we need to update those records so each now knows about the new
491 // name of the other.
492 for (new_soname, path, needed) in soname_map.values() {
493 let mut replacements = Vec::new();
494 for n in needed {
495 if soname_map.contains_key(n) {
496 replacements.push((n, soname_map[n].0.clone()));
497 }
498 }
499 if !replacements.is_empty() {
500 patchelf::replace_needed(path, &replacements[..])?;
501 }
502 writer.add_file_with_permissions(libs_dir.join(new_soname), path, 0o755)?;
503 }
504
505 eprintln!(
506 "🖨 Copied external shared libraries to package {} directory:",
507 libs_dir.display()
508 );
509 for lib_path in libs_copied {
510 eprintln!(" {}", lib_path.display());
511 }
512
513 let artifact_dir = match self.bridge() {
514 // cffi bindings that contains '.' in the module name will be split into directories
515 BridgeModel::Cffi => self.module_name.split(".").collect::<PathBuf>(),
516 // For namespace packages the modules the modules resides resides at ${module_name}.so
517 // where periods are replaced with slashes so for example my.namespace.module would reside
518 // at my/namespace/module.so
519 _ if self.module_name.contains(".") => {
520 let mut path = self.module_name.split(".").collect::<PathBuf>();
521 path.pop();
522 path
523 }
524 // For other bindings artifact .so file usually resides at ${module_name}/${module_name}.so
525 _ => PathBuf::from(&self.module_name),
526 };
527 for artifact in artifacts {
528 let mut new_rpaths = patchelf::get_rpath(&artifact.path)?;
529 // TODO: clean existing rpath entries if it's not pointed to a location within the wheel
530 // See https://github.com/pypa/auditwheel/blob/353c24250d66951d5ac7e60b97471a6da76c123f/src/auditwheel/repair.py#L160
531 let new_rpath = Path::new("$ORIGIN").join(relpath(&libs_dir, &artifact_dir));
532 new_rpaths.push(new_rpath.to_str().unwrap().to_string());
533 let new_rpath = new_rpaths.join(":");
534 patchelf::set_rpath(&artifact.path, &new_rpath)?;
535 }
536 Ok(())
537 }
538
539 fn add_pth(&self, writer: &mut WheelWriter) -> Result<()> {
540 if self.editable {
541 writer.add_pth(&self.project_layout, &self.metadata24)?;
542 }
543 Ok(())
544 }
545
546 fn excludes(&self, format: Format) -> Result<Override> {
547 let project_dir = match self.pyproject_toml_path.normalize() {
548 Ok(pyproject_toml_path) => pyproject_toml_path.into_path_buf(),
549 Err(_) => self.manifest_path.normalize()?.into_path_buf(),
550 };
551 let mut excludes = OverrideBuilder::new(project_dir.parent().unwrap());
552 if let Some(pyproject) = self.pyproject_toml.as_ref() {
553 if let Some(glob_patterns) = &pyproject.exclude() {
554 for glob in glob_patterns
555 .iter()
556 .filter_map(|glob_pattern| glob_pattern.targets(format))
557 {
558 excludes.add(glob)?;
559 }
560 }
561 }
562 // Ignore sdist output files so that we don't include them in the sdist
563 if matches!(format, Format::Sdist) {
564 let glob_pattern = format!(
565 "{}{}{}-*.tar.gz",
566 self.out.display(),
567 std::path::MAIN_SEPARATOR,
568 &self.metadata24.get_distribution_escaped(),
569 );
570 excludes.add(&glob_pattern)?;
571 }
572 Ok(excludes.build()?)
573 }
574
575 /// Returns the platform part of the tag for the wheel name
576 pub fn get_platform_tag(&self, platform_tags: &[PlatformTag]) -> Result<String> {
577 if let Ok(host_platform) = env::var("_PYTHON_HOST_PLATFORM") {
578 let override_platform = host_platform.replace(['.', '-'], "_");
579 eprintln!("🚉 Overriding platform tag from _PYTHON_HOST_PLATFORM environment variable as {override_platform}.");
580 return Ok(override_platform);
581 }
582
583 let target = &self.target;
584 let tag = match (&target.target_os(), &target.target_arch()) {
585 // Windows
586 (Os::Windows, Arch::X86) => "win32".to_string(),
587 (Os::Windows, Arch::X86_64) => "win_amd64".to_string(),
588 (Os::Windows, Arch::Aarch64) => "win_arm64".to_string(),
589 // Linux
590 (Os::Linux, _) => {
591 let arch = target.get_platform_arch()?;
592 let mut platform_tags = platform_tags.to_vec();
593 platform_tags.sort();
594 let mut tags = vec![];
595 for platform_tag in platform_tags {
596 tags.push(format!("{platform_tag}_{arch}"));
597 for alias in platform_tag.aliases() {
598 tags.push(format!("{alias}_{arch}"));
599 }
600 }
601 tags.join(".")
602 }
603 // macOS
604 (Os::Macos, Arch::X86_64) | (Os::Macos, Arch::Aarch64) => {
605 let ((x86_64_major, x86_64_minor), (arm64_major, arm64_minor)) = macosx_deployment_target(env::var("MACOSX_DEPLOYMENT_TARGET").ok().as_deref(), self.universal2)?;
606 let x86_64_tag = if let Some(deployment_target) = self.pyproject_toml.as_ref().and_then(|x| x.target_config("x86_64-apple-darwin")).and_then(|config| config.macos_deployment_target.as_ref()) {
607 deployment_target.replace('.', "_")
608 } else {
609 format!("{x86_64_major}_{x86_64_minor}")
610 };
611 let arm64_tag = if let Some(deployment_target) = self.pyproject_toml.as_ref().and_then(|x| x.target_config("aarch64-apple-darwin")).and_then(|config| config.macos_deployment_target.as_ref()) {
612 deployment_target.replace('.', "_")
613 } else {
614 format!("{arm64_major}_{arm64_minor}")
615 };
616 if self.universal2 {
617 format!(
618 "macosx_{x86_64_tag}_x86_64.macosx_{arm64_tag}_arm64.macosx_{x86_64_tag}_universal2"
619 )
620 } else if target.target_arch() == Arch::Aarch64 {
621 format!("macosx_{arm64_tag}_arm64")
622 } else {
623 format!("macosx_{x86_64_tag}_x86_64")
624 }
625 }
626 // FreeBSD
627 | (Os::FreeBsd, _) => {
628 format!(
629 "{}_{}_{}",
630 target.target_os().to_string().to_ascii_lowercase(),
631 target.get_platform_release()?.to_ascii_lowercase(),
632 target.target_arch().machine(),
633 )
634 }
635 // NetBSD
636 | (Os::NetBsd, _)
637 // OpenBSD
638 | (Os::OpenBsd, _) => {
639 let release = target.get_platform_release()?;
640 format!(
641 "{}_{}_{}",
642 target.target_os().to_string().to_ascii_lowercase(),
643 release,
644 target.target_arch().machine(),
645 )
646 }
647 // DragonFly
648 (Os::Dragonfly, Arch::X86_64)
649 // Haiku
650 | (Os::Haiku, Arch::X86_64) => {
651 let release = target.get_platform_release()?;
652 format!(
653 "{}_{}_{}",
654 target.target_os().to_string().to_ascii_lowercase(),
655 release.to_ascii_lowercase(),
656 "x86_64"
657 )
658 }
659 // Emscripten
660 (Os::Emscripten, Arch::Wasm32) => {
661 let release = emscripten_version()?.replace(['.', '-'], "_");
662 format!("emscripten_{release}_wasm32")
663 }
664 (Os::Wasi, Arch::Wasm32) => {
665 "any".to_string()
666 }
667 // osname_release_machine fallback for any POSIX system
668 (_, _) => {
669 let info = PlatformInfo::new()
670 .map_err(|e| anyhow!("Failed to fetch platform information: {e}"))?;
671 let mut release = info.release().to_string_lossy().replace(['.', '-'], "_");
672 let mut machine = info.machine().to_string_lossy().replace([' ', '/'], "_");
673
674 let mut os = target.target_os().to_string().to_ascii_lowercase();
675 // See https://github.com/python/cpython/blob/46c8d915715aa2bd4d697482aa051fe974d440e1/Lib/sysconfig.py#L722-L730
676 if target.target_os() == Os::Solaris || target.target_os() == Os::Illumos {
677 // Solaris / Illumos
678 if let Some((major, other)) = release.split_once('_') {
679 let major_ver: u64 = major.parse().context("illumos major version is not a number")?;
680 if major_ver >= 5 {
681 // SunOS 5 == Solaris 2
682 os = "solaris".to_string();
683 release = format!("{}_{}", major_ver - 3, other);
684 machine = format!("{machine}_64bit");
685 }
686 }
687 }
688 format!(
689 "{os}_{release}_{machine}"
690 )
691 }
692 };
693 Ok(tag)
694 }
695
696 /// Returns the tags for the WHEEL file for cffi wheels
697 pub fn get_py3_tags(&self, platform_tags: &[PlatformTag]) -> Result<Vec<String>> {
698 let tags = vec![format!(
699 "py3-none-{}",
700 self.get_platform_tag(platform_tags)?
701 )];
702 Ok(tags)
703 }
704
705 /// Returns the tags for the platform without python version
706 pub fn get_universal_tags(
707 &self,
708 platform_tags: &[PlatformTag],
709 ) -> Result<(String, Vec<String>)> {
710 let tag = format!(
711 "py3-none-{platform}",
712 platform = self.get_platform_tag(platform_tags)?
713 );
714 let tags = self.get_py3_tags(platform_tags)?;
715 Ok((tag, tags))
716 }
717
718 fn write_pyo3_wheel_abi3(
719 &self,
720 artifact: BuildArtifact,
721 platform_tags: &[PlatformTag],
722 ext_libs: Vec<Library>,
723 major: u8,
724 min_minor: u8,
725 ) -> Result<BuiltWheelMetadata> {
726 let platform = self.get_platform_tag(platform_tags)?;
727 let tag = format!("cp{major}{min_minor}-abi3-{platform}");
728
729 let mut writer = WheelWriter::new(
730 &tag,
731 &self.out,
732 &self.project_layout.project_root,
733 &self.metadata24,
734 std::slice::from_ref(&tag),
735 self.excludes(Format::Wheel)?,
736 self.compression,
737 )?;
738 self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
739
740 write_bindings_module(
741 &mut writer,
742 &self.project_layout,
743 &artifact.path,
744 self.interpreter.first(),
745 true,
746 &self.target,
747 self.editable,
748 self.pyproject_toml.as_ref(),
749 )
750 .context("Failed to add the files to the wheel")?;
751
752 self.add_pth(&mut writer)?;
753 add_data(
754 &mut writer,
755 &self.metadata24,
756 self.project_layout.data.as_deref(),
757 )?;
758 let wheel_path = writer.finish()?;
759 Ok((wheel_path, format!("cp{major}{min_minor}")))
760 }
761
762 /// For abi3 we only need to build a single wheel and we don't even need a python interpreter
763 /// for it
764 pub fn build_pyo3_wheel_abi3(
765 &self,
766 interpreters: &[PythonInterpreter],
767 major: u8,
768 min_minor: u8,
769 ) -> Result<Vec<BuiltWheelMetadata>> {
770 let mut wheels = Vec::new();
771 // On windows, we have picked an interpreter to set the location of python.lib,
772 // otherwise it's none
773 let python_interpreter = interpreters.first();
774 let artifact = self.compile_cdylib(
775 python_interpreter,
776 Some(&self.project_layout.extension_name),
777 )?;
778 let (policy, external_libs) =
779 self.auditwheel(&artifact, &self.platform_tag, python_interpreter)?;
780 let platform_tags = if self.platform_tag.is_empty() {
781 vec![policy.platform_tag()]
782 } else {
783 self.platform_tag.clone()
784 };
785 let (wheel_path, tag) =
786 self.write_pyo3_wheel_abi3(artifact, &platform_tags, external_libs, major, min_minor)?;
787
788 eprintln!(
789 "📦 Built wheel for abi3 Python ≥ {}.{} to {}",
790 major,
791 min_minor,
792 wheel_path.display()
793 );
794 wheels.push((wheel_path, tag));
795
796 Ok(wheels)
797 }
798
799 fn write_pyo3_wheel(
800 &self,
801 python_interpreter: &PythonInterpreter,
802 artifact: BuildArtifact,
803 platform_tags: &[PlatformTag],
804 ext_libs: Vec<Library>,
805 ) -> Result<BuiltWheelMetadata> {
806 let tag = python_interpreter.get_tag(self, platform_tags)?;
807
808 let mut writer = WheelWriter::new(
809 &tag,
810 &self.out,
811 &self.project_layout.project_root,
812 &self.metadata24,
813 std::slice::from_ref(&tag),
814 self.excludes(Format::Wheel)?,
815 self.compression,
816 )?;
817 self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
818
819 write_bindings_module(
820 &mut writer,
821 &self.project_layout,
822 &artifact.path,
823 Some(python_interpreter),
824 false,
825 &self.target,
826 self.editable,
827 self.pyproject_toml.as_ref(),
828 )
829 .context("Failed to add the files to the wheel")?;
830
831 self.add_pth(&mut writer)?;
832 add_data(
833 &mut writer,
834 &self.metadata24,
835 self.project_layout.data.as_deref(),
836 )?;
837 let wheel_path = writer.finish()?;
838 Ok((
839 wheel_path,
840 format!("cp{}{}", python_interpreter.major, python_interpreter.minor),
841 ))
842 }
843
844 /// Builds wheels for a pyo3 extension for all given python versions.
845 /// Return type is the same as [BuildContext::build_wheels()]
846 ///
847 /// Defaults to 3.{5, 6, 7, 8, 9} if no python versions are given
848 /// and silently ignores all non-existent python versions.
849 ///
850 /// Runs [auditwheel_rs()] if not deactivated
851 pub fn build_pyo3_wheels(
852 &self,
853 interpreters: &[PythonInterpreter],
854 ) -> Result<Vec<BuiltWheelMetadata>> {
855 let mut wheels = Vec::new();
856 for python_interpreter in interpreters {
857 let artifact = self.compile_cdylib(
858 Some(python_interpreter),
859 Some(&self.project_layout.extension_name),
860 )?;
861 let (policy, external_libs) =
862 self.auditwheel(&artifact, &self.platform_tag, Some(python_interpreter))?;
863 let platform_tags = if self.platform_tag.is_empty() {
864 vec![policy.platform_tag()]
865 } else {
866 self.platform_tag.clone()
867 };
868 let (wheel_path, tag) =
869 self.write_pyo3_wheel(python_interpreter, artifact, &platform_tags, external_libs)?;
870 eprintln!(
871 "📦 Built wheel for {} {}.{}{} to {}",
872 python_interpreter.interpreter_kind,
873 python_interpreter.major,
874 python_interpreter.minor,
875 python_interpreter.abiflags,
876 wheel_path.display()
877 );
878
879 wheels.push((wheel_path, tag));
880 }
881
882 Ok(wheels)
883 }
884
885 /// Runs cargo build, extracts the cdylib from the output and returns the path to it
886 ///
887 /// The module name is used to warn about missing a `PyInit_<module name>` function for
888 /// bindings modules.
889 pub fn compile_cdylib(
890 &self,
891 python_interpreter: Option<&PythonInterpreter>,
892 extension_name: Option<&str>,
893 ) -> Result<BuildArtifact> {
894 let artifacts = compile(self, python_interpreter, &self.compile_targets)
895 .context("Failed to build a native library through cargo")?;
896 let error_msg = "Cargo didn't build a cdylib. Did you miss crate-type = [\"cdylib\"] \
897 in the lib section of your Cargo.toml?";
898 let artifacts = artifacts.first().context(error_msg)?;
899
900 let mut artifact = artifacts
901 .get(&CrateType::CDyLib)
902 .cloned()
903 .ok_or_else(|| anyhow!(error_msg,))?;
904
905 if let Some(extension_name) = extension_name {
906 // globin has an issue parsing MIPS64 ELF, see https://github.com/m4b/goblin/issues/274
907 // But don't fail the build just because we can't emit a warning
908 let _ = warn_missing_py_init(&artifact.path, extension_name);
909 }
910
911 if self.editable || matches!(self.auditwheel, AuditWheelMode::Skip) {
912 return Ok(artifact);
913 }
914 // auditwheel repair will edit the file, so we need to copy it to avoid errors in reruns
915 let maturin_build = self.target_dir.join(env!("CARGO_PKG_NAME"));
916 fs::create_dir_all(&maturin_build)?;
917 let artifact_path = &artifact.path;
918 let new_artifact_path = maturin_build.join(artifact_path.file_name().unwrap());
919 fs::copy(artifact_path, &new_artifact_path)?;
920 artifact.path = new_artifact_path.normalize()?.into_path_buf();
921 Ok(artifact)
922 }
923
924 fn write_cffi_wheel(
925 &self,
926 artifact: BuildArtifact,
927 platform_tags: &[PlatformTag],
928 ext_libs: Vec<Library>,
929 ) -> Result<BuiltWheelMetadata> {
930 let (tag, tags) = self.get_universal_tags(platform_tags)?;
931
932 let mut writer = WheelWriter::new(
933 &tag,
934 &self.out,
935 &self.project_layout.project_root,
936 &self.metadata24,
937 &tags,
938 self.excludes(Format::Wheel)?,
939 self.compression,
940 )?;
941 self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
942
943 write_cffi_module(
944 &mut writer,
945 &self.target,
946 &self.project_layout,
947 self.manifest_path.parent().unwrap(),
948 &self.target_dir,
949 &self.module_name,
950 &artifact.path,
951 &self.interpreter[0].executable,
952 self.editable,
953 self.pyproject_toml.as_ref(),
954 )?;
955
956 self.add_pth(&mut writer)?;
957 add_data(
958 &mut writer,
959 &self.metadata24,
960 self.project_layout.data.as_deref(),
961 )?;
962 let wheel_path = writer.finish()?;
963 Ok((wheel_path, "py3".to_string()))
964 }
965
966 /// Builds a wheel with cffi bindings
967 pub fn build_cffi_wheel(&self) -> Result<Vec<BuiltWheelMetadata>> {
968 let mut wheels = Vec::new();
969 let artifact = self.compile_cdylib(None, None)?;
970 let (policy, external_libs) = self.auditwheel(&artifact, &self.platform_tag, None)?;
971 let platform_tags = if self.platform_tag.is_empty() {
972 vec![policy.platform_tag()]
973 } else {
974 self.platform_tag.clone()
975 };
976 let (wheel_path, tag) = self.write_cffi_wheel(artifact, &platform_tags, external_libs)?;
977
978 // Warn if cffi isn't specified in the requirements
979 if !self
980 .metadata24
981 .requires_dist
982 .iter()
983 .any(|requirement| requirement.name.as_ref() == "cffi")
984 {
985 eprintln!(
986 "⚠️ Warning: missing cffi package dependency, please add it to pyproject.toml. \
987 e.g: `dependencies = [\"cffi\"]`. This will become an error."
988 );
989 }
990
991 eprintln!("📦 Built wheel to {}", wheel_path.display());
992 wheels.push((wheel_path, tag));
993
994 Ok(wheels)
995 }
996
997 fn write_uniffi_wheel(
998 &self,
999 artifact: BuildArtifact,
1000 platform_tags: &[PlatformTag],
1001 ext_libs: Vec<Library>,
1002 ) -> Result<BuiltWheelMetadata> {
1003 let (tag, tags) = self.get_universal_tags(platform_tags)?;
1004
1005 let mut writer = WheelWriter::new(
1006 &tag,
1007 &self.out,
1008 &self.project_layout.project_root,
1009 &self.metadata24,
1010 &tags,
1011 self.excludes(Format::Wheel)?,
1012 self.compression,
1013 )?;
1014 self.add_external_libs(&mut writer, &[&artifact], &[ext_libs])?;
1015
1016 write_uniffi_module(
1017 &mut writer,
1018 &self.project_layout,
1019 self.manifest_path.parent().unwrap(),
1020 &self.target_dir,
1021 &self.module_name,
1022 &artifact.path,
1023 self.target.target_os(),
1024 self.editable,
1025 self.pyproject_toml.as_ref(),
1026 )?;
1027
1028 self.add_pth(&mut writer)?;
1029 add_data(
1030 &mut writer,
1031 &self.metadata24,
1032 self.project_layout.data.as_deref(),
1033 )?;
1034 let wheel_path = writer.finish()?;
1035 Ok((wheel_path, "py3".to_string()))
1036 }
1037
1038 /// Builds a wheel with uniffi bindings
1039 pub fn build_uniffi_wheel(&self) -> Result<Vec<BuiltWheelMetadata>> {
1040 let mut wheels = Vec::new();
1041 let artifact = self.compile_cdylib(None, None)?;
1042 let (policy, external_libs) = self.auditwheel(&artifact, &self.platform_tag, None)?;
1043 let platform_tags = if self.platform_tag.is_empty() {
1044 vec![policy.platform_tag()]
1045 } else {
1046 self.platform_tag.clone()
1047 };
1048 let (wheel_path, tag) = self.write_uniffi_wheel(artifact, &platform_tags, external_libs)?;
1049
1050 eprintln!("📦 Built wheel to {}", wheel_path.display());
1051 wheels.push((wheel_path, tag));
1052
1053 Ok(wheels)
1054 }
1055
1056 fn write_bin_wheel(
1057 &self,
1058 python_interpreter: Option<&PythonInterpreter>,
1059 artifacts: &[BuildArtifact],
1060 platform_tags: &[PlatformTag],
1061 ext_libs: &[Vec<Library>],
1062 ) -> Result<BuiltWheelMetadata> {
1063 let (tag, tags) = match (self.bridge(), python_interpreter) {
1064 (BridgeModel::Bin(None), _) => self.get_universal_tags(platform_tags)?,
1065 (BridgeModel::Bin(Some(..)), Some(python_interpreter)) => {
1066 let tag = python_interpreter.get_tag(self, platform_tags)?;
1067 (tag.clone(), vec![tag])
1068 }
1069 _ => unreachable!(),
1070 };
1071
1072 if !self.metadata24.scripts.is_empty() {
1073 bail!("Defining scripts and working with a binary doesn't mix well");
1074 }
1075
1076 let mut artifacts_and_files = Vec::new();
1077 for artifact in artifacts {
1078 // I wouldn't know of any case where this would be the wrong (and neither do
1079 // I know a better alternative)
1080 let bin_name = artifact
1081 .path
1082 .file_name()
1083 .context("Couldn't get the filename from the binary produced by cargo")?
1084 .to_str()
1085 .context("binary produced by cargo has non-utf8 filename")?
1086 .to_string();
1087
1088 // From https://packaging.python.org/en/latest/specifications/entry-points/
1089 // > The name may contain any characters except =, but it cannot start or end with any
1090 // > whitespace character, or start with [. For new entry points, it is recommended to
1091 // > use only letters, numbers, underscores, dots and dashes (regex [\w.-]+).
1092 // All of these rules are already enforced by cargo:
1093 // https://github.com/rust-lang/cargo/blob/58a961314437258065e23cb6316dfc121d96fb71/src/cargo/util/restricted_names.rs#L39-L84
1094 // i.e. we don't need to do any bin name validation here anymore
1095
1096 artifacts_and_files.push((artifact, bin_name))
1097 }
1098
1099 let metadata24 = if self.target.is_wasi() {
1100 bin_wasi_helper(&artifacts_and_files, self.metadata24.clone())?
1101 } else {
1102 self.metadata24.clone()
1103 };
1104
1105 let mut writer = WheelWriter::new(
1106 &tag,
1107 &self.out,
1108 &self.project_layout.project_root,
1109 &metadata24,
1110 &tags,
1111 self.excludes(Format::Wheel)?,
1112 self.compression,
1113 )?;
1114
1115 if self.project_layout.python_module.is_some() && self.target.is_wasi() {
1116 // TODO: Can we have python code and the wasm launchers coexisting
1117 // without clashes?
1118 bail!("Sorry, adding python code to a wasm binary is currently not supported")
1119 }
1120 if !self.editable {
1121 write_python_part(
1122 &mut writer,
1123 &self.project_layout,
1124 self.pyproject_toml.as_ref(),
1125 )
1126 .context("Failed to add the python module to the package")?;
1127 }
1128
1129 let mut artifacts_ref = Vec::with_capacity(artifacts.len());
1130 for (artifact, bin_name) in &artifacts_and_files {
1131 artifacts_ref.push(*artifact);
1132 write_bin(&mut writer, &artifact.path, &self.metadata24, bin_name)?;
1133 if self.target.is_wasi() {
1134 write_wasm_launcher(&mut writer, &self.metadata24, bin_name)?;
1135 }
1136 }
1137 self.add_external_libs(&mut writer, &artifacts_ref, ext_libs)?;
1138
1139 self.add_pth(&mut writer)?;
1140 add_data(
1141 &mut writer,
1142 &self.metadata24,
1143 self.project_layout.data.as_deref(),
1144 )?;
1145 let wheel_path = writer.finish()?;
1146 Ok((wheel_path, "py3".to_string()))
1147 }
1148
1149 /// Builds a wheel that contains a binary
1150 ///
1151 /// Runs [auditwheel_rs()] if not deactivated
1152 pub fn build_bin_wheel(
1153 &self,
1154 python_interpreter: Option<&PythonInterpreter>,
1155 ) -> Result<Vec<BuiltWheelMetadata>> {
1156 let mut wheels = Vec::new();
1157 let artifacts = compile(self, python_interpreter, &self.compile_targets)
1158 .context("Failed to build a native library through cargo")?;
1159 if artifacts.is_empty() {
1160 bail!("Cargo didn't build a binary")
1161 }
1162
1163 let mut policies = Vec::with_capacity(artifacts.len());
1164 let mut ext_libs = Vec::new();
1165 let mut artifact_paths = Vec::with_capacity(artifacts.len());
1166 for artifact in artifacts {
1167 let artifact = artifact
1168 .get(&CrateType::Bin)
1169 .cloned()
1170 .ok_or_else(|| anyhow!("Cargo didn't build a binary"))?;
1171
1172 let (policy, external_libs) = self.auditwheel(&artifact, &self.platform_tag, None)?;
1173 policies.push(policy);
1174 ext_libs.push(external_libs);
1175 artifact_paths.push(artifact);
1176 }
1177 let policy = policies.iter().min_by_key(|p| p.priority).unwrap();
1178 let platform_tags = if self.platform_tag.is_empty() {
1179 vec![policy.platform_tag()]
1180 } else {
1181 self.platform_tag.clone()
1182 };
1183
1184 let (wheel_path, tag) = self.write_bin_wheel(
1185 python_interpreter,
1186 &artifact_paths,
1187 &platform_tags,
1188 &ext_libs,
1189 )?;
1190 eprintln!("📦 Built wheel to {}", wheel_path.display());
1191 wheels.push((wheel_path, tag));
1192
1193 Ok(wheels)
1194 }
1195
1196 /// Builds a wheel that contains a binary
1197 ///
1198 /// Runs [auditwheel_rs()] if not deactivated
1199 pub fn build_bin_wheels(
1200 &self,
1201 interpreters: &[PythonInterpreter],
1202 ) -> Result<Vec<BuiltWheelMetadata>> {
1203 let mut wheels = Vec::new();
1204 for python_interpreter in interpreters {
1205 wheels.extend(self.build_bin_wheel(Some(python_interpreter))?);
1206 }
1207 Ok(wheels)
1208 }
1209 }
1210
1211 /// Calculate the sha256 of a file
1212 pub fn hash_file(path: impl AsRef<Path>) -> Result<String, io::Error> {
1213 let mut file = fs::File::open(path.as_ref())?;
1214 let mut hasher = Sha256::new();
1215 io::copy(&mut file, &mut hasher)?;
1216 let hex = format!("{:x}", hasher.finalize());
1217 Ok(hex)
1218 }
1219
1220 /// Get the default macOS deployment target version
1221 fn macosx_deployment_target(
1222 deploy_target: Option<&str>,
1223 universal2: bool,
1224 ) -> Result<((u16, u16), (u16, u16))> {
1225 let x86_64_default_rustc = rustc_macosx_target_version("x86_64-apple-darwin");
1226 let x86_64_default = if universal2 && x86_64_default_rustc.1 < 9 {
1227 (10, 9)
1228 } else {
1229 x86_64_default_rustc
1230 };
1231 let arm64_default = rustc_macosx_target_version("aarch64-apple-darwin");
1232 let mut x86_64_ver = x86_64_default;
1233 let mut arm64_ver = arm64_default;
1234 if let Some(deploy_target) = deploy_target {
1235 let err_ctx = "MACOSX_DEPLOYMENT_TARGET is invalid";
1236 let mut parts = deploy_target.split('.');
1237 let major = parts.next().context(err_ctx)?;
1238 let major: u16 = major.parse().context(err_ctx)?;
1239 let minor = parts.next().context(err_ctx)?;
1240 let minor: u16 = minor.parse().context(err_ctx)?;
1241 if (major, minor) > x86_64_default {
1242 x86_64_ver = (major, minor);
1243 }
1244 if (major, minor) > arm64_default {
1245 arm64_ver = (major, minor);
1246 }
1247 }
1248 Ok((
1249 python_macosx_target_version(x86_64_ver),
1250 python_macosx_target_version(arm64_ver),
1251 ))
1252 }
1253
1254 #[inline]
1255 fn python_macosx_target_version(version: (u16, u16)) -> (u16, u16) {
1256 let (major, minor) = version;
1257 if major >= 11 {
1258 // pip only supports (major, 0) for macOS 11+
1259 (major, 0)
1260 } else {
1261 (major, minor)
1262 }
1263 }
1264
1265 pub(crate) fn rustc_macosx_target_version(target: &str) -> (u16, u16) {
1266 use std::process::{Command, Stdio};
1267 use target_lexicon::OperatingSystem;
1268
1269 // On rustc 1.71.0+ we can use `rustc --print deployment-target`
1270 if let Ok(output) = Command::new("rustc")
1271 .stderr(Stdio::piped())
1272 .stdout(Stdio::piped())
1273 .env_remove("MACOSX_DEPLOYMENT_TARGET")
1274 .args(["--target", target])
1275 .args(["--print", "deployment-target"])
1276 .output()
1277 {
1278 if output.status.success() {
1279 let target_version = std::str::from_utf8(&output.stdout)
1280 .unwrap()
1281 .split('=')
1282 .next_back()
1283 .and_then(|v| v.trim().split_once('.'));
1284 if let Some((major, minor)) = target_version {
1285 let major: u16 = major.parse().unwrap();
1286 let minor: u16 = minor.parse().unwrap();
1287 return (major, minor);
1288 }
1289 }
1290 }
1291
1292 let fallback_version = if target == "aarch64-apple-darwin" {
1293 (11, 0)
1294 } else {
1295 (10, 7)
1296 };
1297
1298 let rustc_target_version = || -> Result<(u16, u16)> {
1299 let cmd = Command::new("rustc")
1300 .arg("-Z")
1301 .arg("unstable-options")
1302 .arg("--print")
1303 .arg("target-spec-json")
1304 .arg("--target")
1305 .arg(target)
1306 .env("RUSTC_BOOTSTRAP", "1")
1307 .env_remove("MACOSX_DEPLOYMENT_TARGET")
1308 .output()
1309 .context("Failed to run rustc to get the target spec")?;
1310 let stdout = String::from_utf8(cmd.stdout).context("rustc output is not valid utf-8")?;
1311 let spec: serde_json::Value =
1312 serde_json::from_str(&stdout).context("rustc output is not valid json")?;
1313 let llvm_target = spec
1314 .as_object()
1315 .context("rustc output is not a json object")?
1316 .get("llvm-target")
1317 .context("rustc output does not contain llvm-target")?
1318 .as_str()
1319 .context("llvm-target is not a string")?;
1320 let triple = llvm_target.parse::<target_lexicon::Triple>();
1321 let (major, minor) = match triple.map(|t| t.operating_system) {
1322 Ok(
1323 OperatingSystem::MacOSX(Some(deployment_target))
1324 | OperatingSystem::Darwin(Some(deployment_target)),
1325 ) => (deployment_target.major, u16::from(deployment_target.minor)),
1326 _ => fallback_version,
1327 };
1328 Ok((major, minor))
1329 };
1330 rustc_target_version().unwrap_or(fallback_version)
1331 }
1332
1333 /// Emscripten version
1334 fn emscripten_version() -> Result<String> {
1335 let os_version = env::var("MATURIN_EMSCRIPTEN_VERSION");
1336 let release = match os_version {
1337 Ok(os_ver) => os_ver,
1338 Err(_) => emcc_version()?,
1339 };
1340 Ok(release)
1341 }
1342
1343 fn emcc_version() -> Result<String> {
1344 use std::process::Command;
1345
1346 let emcc = Command::new(if cfg!(windows) { "emcc.bat" } else { "emcc" })
1347 .arg("-dumpversion")
1348 .output()
1349 .context("Failed to run emcc to get the version")?;
1350 let ver = String::from_utf8(emcc.stdout)?;
1351 let mut trimmed = ver.trim();
1352 trimmed = trimmed.strip_suffix("-git").unwrap_or(trimmed);
1353 Ok(trimmed.into())
1354 }
1355
1356 #[cfg(test)]
1357 mod test {
1358 use super::macosx_deployment_target;
1359 use pretty_assertions::assert_eq;
1360
1361 #[test]
1362 fn test_macosx_deployment_target() {
1363 let rustc_ver = rustc_version::version().unwrap();
1364 let rustc_ver = (rustc_ver.major, rustc_ver.minor);
1365 let x86_64_minor = if rustc_ver >= (1, 74) { 12 } else { 7 };
1366 let universal2_minor = if rustc_ver >= (1, 74) { 12 } else { 9 };
1367 assert_eq!(
1368 macosx_deployment_target(None, false).unwrap(),
1369 ((10, x86_64_minor), (11, 0))
1370 );
1371 assert_eq!(
1372 macosx_deployment_target(None, true).unwrap(),
1373 ((10, universal2_minor), (11, 0))
1374 );
1375 assert_eq!(
1376 macosx_deployment_target(Some("10.6"), false).unwrap(),
1377 ((10, x86_64_minor), (11, 0))
1378 );
1379 assert_eq!(
1380 macosx_deployment_target(Some("10.6"), true).unwrap(),
1381 ((10, universal2_minor), (11, 0))
1382 );
1383 assert_eq!(
1384 macosx_deployment_target(Some("10.9"), false).unwrap(),
1385 ((10, universal2_minor), (11, 0))
1386 );
1387 assert_eq!(
1388 macosx_deployment_target(Some("11.0.0"), false).unwrap(),
1389 ((11, 0), (11, 0))
1390 );
1391 assert_eq!(
1392 macosx_deployment_target(Some("11.1"), false).unwrap(),
1393 ((11, 0), (11, 0))
1394 );
1395 }
1396 }