| 1 |
use crate::target::RUST_1_64_0; |
| 2 |
#[cfg(feature = "zig")] |
| 3 |
use crate::PlatformTag; |
| 4 |
use crate::{BridgeModel, BuildContext, PythonInterpreter, Target}; |
| 5 |
use anyhow::{anyhow, bail, Context, Result}; |
| 6 |
use cargo_metadata::CrateType; |
| 7 |
use fat_macho::FatWriter; |
| 8 |
use fs_err::{self as fs, File}; |
| 9 |
use normpath::PathExt; |
| 10 |
use std::collections::HashMap; |
| 11 |
use std::env; |
| 12 |
use std::io::{BufReader, Read}; |
| 13 |
use std::path::{Path, PathBuf}; |
| 14 |
use std::process::{Command, Stdio}; |
| 15 |
use std::str; |
| 16 |
use tracing::{debug, instrument, trace}; |
| 17 |
|
| 18 |
/// The first version of pyo3 that supports building Windows abi3 wheel |
| 19 |
/// without `PYO3_NO_PYTHON` environment variable |
| 20 |
const PYO3_ABI3_NO_PYTHON_VERSION: (u64, u64, u64) = (0, 16, 4); |
| 21 |
|
| 22 |
/// crate types excluding `bin`, `cdylib` and `proc-macro` |
| 23 |
pub(crate) const LIB_CRATE_TYPES: [CrateType; 4] = [ |
| 24 |
CrateType::Lib, |
| 25 |
CrateType::DyLib, |
| 26 |
CrateType::RLib, |
| 27 |
CrateType::StaticLib, |
| 28 |
]; |
| 29 |
|
| 30 |
/// A cargo target to build |
| 31 |
#[derive(Debug, Clone)] |
| 32 |
pub struct CompileTarget { |
| 33 |
/// The cargo target to build |
| 34 |
pub target: cargo_metadata::Target, |
| 35 |
/// The bridge model to use |
| 36 |
pub bridge_model: BridgeModel, |
| 37 |
} |
| 38 |
|
| 39 |
/// A cargo build artifact |
| 40 |
#[derive(Debug, Clone)] |
| 41 |
pub struct BuildArtifact { |
| 42 |
/// Path to the build artifact |
| 43 |
pub path: PathBuf, |
| 44 |
/// Array of paths to include in the library search path, as indicated by |
| 45 |
/// the `cargo:rustc-link-search` instruction. |
| 46 |
pub linked_paths: Vec<String>, |
| 47 |
} |
| 48 |
|
| 49 |
/// Builds the rust crate into a native module (i.e. an .so or .dll) for a |
| 50 |
/// specific python version. Returns a mapping from crate type (e.g. cdylib) |
| 51 |
/// to artifact location. |
| 52 |
pub fn compile( |
| 53 |
context: &BuildContext, |
| 54 |
python_interpreter: Option<&PythonInterpreter>, |
| 55 |
targets: &[CompileTarget], |
| 56 |
) -> Result<Vec<HashMap<CrateType, BuildArtifact>>> { |
| 57 |
if context.universal2 { |
| 58 |
compile_universal2(context, python_interpreter, targets) |
| 59 |
} else { |
| 60 |
compile_targets(context, python_interpreter, targets) |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
/// Build an universal2 wheel for macos which contains both an x86 and an aarch64 binary |
| 65 |
fn compile_universal2( |
| 66 |
context: &BuildContext, |
| 67 |
python_interpreter: Option<&PythonInterpreter>, |
| 68 |
targets: &[CompileTarget], |
| 69 |
) -> Result<Vec<HashMap<CrateType, BuildArtifact>>> { |
| 70 |
let mut aarch64_context = context.clone(); |
| 71 |
aarch64_context.target = Target::from_resolved_target_triple("aarch64-apple-darwin")?; |
| 72 |
|
| 73 |
let aarch64_artifacts = compile_targets(&aarch64_context, python_interpreter, targets) |
| 74 |
.context("Failed to build a aarch64 library through cargo")?; |
| 75 |
let mut x86_64_context = context.clone(); |
| 76 |
x86_64_context.target = Target::from_resolved_target_triple("x86_64-apple-darwin")?; |
| 77 |
|
| 78 |
let x86_64_artifacts = compile_targets(&x86_64_context, python_interpreter, targets) |
| 79 |
.context("Failed to build a x86_64 library through cargo")?; |
| 80 |
|
| 81 |
let mut universal_artifacts = Vec::with_capacity(targets.len()); |
| 82 |
for (bridge_model, (aarch64_artifact, x86_64_artifact)) in targets |
| 83 |
.iter() |
| 84 |
.map(|target| &target.bridge_model) |
| 85 |
.zip(aarch64_artifacts.iter().zip(&x86_64_artifacts)) |
| 86 |
{ |
| 87 |
let build_type = if bridge_model.is_bin() { |
| 88 |
CrateType::Bin |
| 89 |
} else { |
| 90 |
CrateType::CDyLib |
| 91 |
}; |
| 92 |
let aarch64_artifact = aarch64_artifact.get(&build_type).cloned().ok_or_else(|| { |
| 93 |
if build_type == CrateType::CDyLib { |
| 94 |
anyhow!( |
| 95 |
"Cargo didn't build an aarch64 cdylib. Did you miss crate-type = [\"cdylib\"] \ |
| 96 |
in the lib section of your Cargo.toml?", |
| 97 |
) |
| 98 |
} else { |
| 99 |
anyhow!("Cargo didn't build an aarch64 bin.") |
| 100 |
} |
| 101 |
})?; |
| 102 |
let x86_64_artifact = x86_64_artifact.get(&build_type).cloned().ok_or_else(|| { |
| 103 |
if build_type == CrateType::CDyLib { |
| 104 |
anyhow!( |
| 105 |
"Cargo didn't build a x86_64 cdylib. Did you miss crate-type = [\"cdylib\"] \ |
| 106 |
in the lib section of your Cargo.toml?", |
| 107 |
) |
| 108 |
} else { |
| 109 |
anyhow!("Cargo didn't build a x86_64 bin.") |
| 110 |
} |
| 111 |
})?; |
| 112 |
// Create an universal dylib |
| 113 |
let output_path = aarch64_artifact |
| 114 |
.path |
| 115 |
.display() |
| 116 |
.to_string() |
| 117 |
.replace("aarch64-apple-darwin/", ""); |
| 118 |
let mut writer = FatWriter::new(); |
| 119 |
let aarch64_file = fs::read(&aarch64_artifact.path)?; |
| 120 |
let x86_64_file = fs::read(&x86_64_artifact.path)?; |
| 121 |
writer |
| 122 |
.add(aarch64_file) |
| 123 |
.map_err(|e| anyhow!("Failed to add aarch64 cdylib: {:?}", e))?; |
| 124 |
writer |
| 125 |
.add(x86_64_file) |
| 126 |
.map_err(|e| anyhow!("Failed to add x86_64 cdylib: {:?}", e))?; |
| 127 |
writer |
| 128 |
.write_to_file(&output_path) |
| 129 |
.map_err(|e| anyhow!("Failed to create universal cdylib: {:?}", e))?; |
| 130 |
|
| 131 |
let mut result = HashMap::new(); |
| 132 |
let universal_artifact = BuildArtifact { |
| 133 |
path: PathBuf::from(output_path), |
| 134 |
..x86_64_artifact |
| 135 |
}; |
| 136 |
result.insert(build_type, universal_artifact); |
| 137 |
universal_artifacts.push(result); |
| 138 |
} |
| 139 |
Ok(universal_artifacts) |
| 140 |
} |
| 141 |
|
| 142 |
fn compile_targets( |
| 143 |
context: &BuildContext, |
| 144 |
python_interpreter: Option<&PythonInterpreter>, |
| 145 |
targets: &[CompileTarget], |
| 146 |
) -> Result<Vec<HashMap<CrateType, BuildArtifact>>> { |
| 147 |
let mut artifacts = Vec::with_capacity(targets.len()); |
| 148 |
for target in targets { |
| 149 |
let build_command = cargo_build_command(context, python_interpreter, target)?; |
| 150 |
artifacts.push(compile_target(context, build_command)?); |
| 151 |
} |
| 152 |
Ok(artifacts) |
| 153 |
} |
| 154 |
|
| 155 |
fn cargo_build_command( |
| 156 |
context: &BuildContext, |
| 157 |
python_interpreter: Option<&PythonInterpreter>, |
| 158 |
compile_target: &CompileTarget, |
| 159 |
) -> Result<Command> { |
| 160 |
let target = &context.target; |
| 161 |
|
| 162 |
let user_specified_target = if target.user_specified { |
| 163 |
Some(target.target_triple().to_string()) |
| 164 |
} else { |
| 165 |
None |
| 166 |
}; |
| 167 |
let mut cargo_rustc = context |
| 168 |
.cargo_options |
| 169 |
.clone() |
| 170 |
.into_rustc_options(user_specified_target); |
| 171 |
cargo_rustc.message_format = vec!["json-render-diagnostics".to_string()]; |
| 172 |
|
| 173 |
// --release and --profile are conflicting options |
| 174 |
if context.release && cargo_rustc.profile.is_none() { |
| 175 |
cargo_rustc.release = true; |
| 176 |
} |
| 177 |
|
| 178 |
// Add `--crate-type cdylib` if available |
| 179 |
if compile_target |
| 180 |
.target |
| 181 |
.crate_types |
| 182 |
.iter() |
| 183 |
.any(|crate_type| LIB_CRATE_TYPES.contains(crate_type)) |
| 184 |
{ |
| 185 |
// `--crate-type` is stable since Rust 1.64.0 |
| 186 |
// See https://github.com/rust-lang/cargo/pull/10838 |
| 187 |
if target.rustc_version.semver >= RUST_1_64_0 { |
| 188 |
debug!("Setting crate_type to cdylib for Rust >= 1.64.0"); |
| 189 |
cargo_rustc.crate_type = vec!["cdylib".to_string()]; |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
let target_triple = target.target_triple(); |
| 194 |
|
| 195 |
let manifest_dir = context.manifest_path.parent().unwrap(); |
| 196 |
let mut rustflags = cargo_config2::Config::load_with_cwd(manifest_dir)? |
| 197 |
.rustflags(target_triple)? |
| 198 |
.unwrap_or_default(); |
| 199 |
let original_rustflags = rustflags.flags.clone(); |
| 200 |
|
| 201 |
// We need to pass --bin / --lib |
| 202 |
let bridge_model = &compile_target.bridge_model; |
| 203 |
match bridge_model { |
| 204 |
BridgeModel::Bin(..) => { |
| 205 |
cargo_rustc.bin.push(compile_target.target.name.clone()); |
| 206 |
} |
| 207 |
BridgeModel::Cffi | BridgeModel::UniFfi | BridgeModel::PyO3 { .. } => { |
| 208 |
cargo_rustc.lib = true; |
| 209 |
// https://github.com/rust-lang/rust/issues/59302#issue-422994250 |
| 210 |
// We must only do this for libraries as it breaks binaries |
| 211 |
// For some reason this value is ignored when passed as rustc argument |
| 212 |
if context.target.is_musl_libc() |
| 213 |
&& !rustflags |
| 214 |
.flags |
| 215 |
.iter() |
| 216 |
.any(|f| f == "target-feature=-crt-static") |
| 217 |
{ |
| 218 |
debug!("Setting `-C target-features=-crt-static` for musl dylib"); |
| 219 |
rustflags.push("-C"); |
| 220 |
rustflags.push("target-feature=-crt-static"); |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// https://github.com/PyO3/pyo3/issues/88#issuecomment-337744403 |
| 226 |
if target.is_macos() { |
| 227 |
if let BridgeModel::PyO3 { .. } = bridge_model { |
| 228 |
// Change LC_ID_DYLIB to the final .so name for macOS targets to avoid linking with |
| 229 |
// non-existent library. |
| 230 |
// See https://github.com/PyO3/setuptools-rust/issues/106 for detail |
| 231 |
let module_name = &context.module_name; |
| 232 |
let so_filename = if bridge_model.is_abi3() { |
| 233 |
format!("{module_name}.abi3.so") |
| 234 |
} else { |
| 235 |
python_interpreter |
| 236 |
.expect("missing python interpreter for non-abi3 wheel build") |
| 237 |
.get_library_name(module_name) |
| 238 |
}; |
| 239 |
let macos_dylib_install_name = |
| 240 |
format!("link-args=-Wl,-install_name,@rpath/{so_filename}"); |
| 241 |
let mac_args = [ |
| 242 |
"-C".to_string(), |
| 243 |
"link-arg=-undefined".to_string(), |
| 244 |
"-C".to_string(), |
| 245 |
"link-arg=dynamic_lookup".to_string(), |
| 246 |
"-C".to_string(), |
| 247 |
macos_dylib_install_name, |
| 248 |
]; |
| 249 |
debug!("Setting additional linker args for macOS: {:?}", mac_args); |
| 250 |
cargo_rustc.args.extend(mac_args); |
| 251 |
} |
| 252 |
} else if target.is_emscripten() { |
| 253 |
// Allow user to override these default flags |
| 254 |
if !rustflags |
| 255 |
.flags |
| 256 |
.iter() |
| 257 |
.any(|f| f.contains("link-native-libraries")) |
| 258 |
{ |
| 259 |
debug!("Setting `-Z link-native-libraries=no` for Emscripten"); |
| 260 |
rustflags.push("-Z"); |
| 261 |
rustflags.push("link-native-libraries=no"); |
| 262 |
} |
| 263 |
let mut emscripten_args = Vec::new(); |
| 264 |
// Allow user to override these default settings |
| 265 |
if !cargo_rustc |
| 266 |
.args |
| 267 |
.iter() |
| 268 |
.any(|arg| arg.contains("SIDE_MODULE")) |
| 269 |
{ |
| 270 |
emscripten_args.push("-C".to_string()); |
| 271 |
emscripten_args.push("link-arg=-sSIDE_MODULE=2".to_string()); |
| 272 |
} |
| 273 |
if !cargo_rustc |
| 274 |
.args |
| 275 |
.iter() |
| 276 |
.any(|arg| arg.contains("WASM_BIGINT")) |
| 277 |
{ |
| 278 |
emscripten_args.push("-C".to_string()); |
| 279 |
emscripten_args.push("link-arg=-sWASM_BIGINT".to_string()); |
| 280 |
} |
| 281 |
debug!( |
| 282 |
"Setting additional linker args for Emscripten: {:?}", |
| 283 |
emscripten_args |
| 284 |
); |
| 285 |
cargo_rustc.args.extend(emscripten_args); |
| 286 |
} |
| 287 |
|
| 288 |
if context.strip { |
| 289 |
// https://doc.rust-lang.org/rustc/codegen-options/index.html#strip |
| 290 |
cargo_rustc |
| 291 |
.args |
| 292 |
.extend(["-C".to_string(), "strip=symbols".to_string()]); |
| 293 |
} |
| 294 |
|
| 295 |
let mut build_command = if target.is_msvc() && target.cross_compiling() { |
| 296 |
#[cfg(feature = "xwin")] |
| 297 |
{ |
| 298 |
// Don't use xwin if the Windows MSVC compiler can compile to the target |
| 299 |
let native_compile = target.host_triple().contains("windows-msvc") |
| 300 |
&& cc::Build::new() |
| 301 |
.opt_level(0) |
| 302 |
.host(target.host_triple()) |
| 303 |
.target(target_triple) |
| 304 |
.cargo_metadata(false) |
| 305 |
.cargo_warnings(false) |
| 306 |
.cargo_output(false) |
| 307 |
.try_get_compiler() |
| 308 |
.is_ok(); |
| 309 |
let force_xwin = env::var("MATURIN_USE_XWIN").ok().as_deref() == Some("1"); |
| 310 |
if !native_compile || force_xwin { |
| 311 |
println!("🛠️ Using xwin for cross-compiling to {target_triple}"); |
| 312 |
let xwin_options = { |
| 313 |
use clap::Parser; |
| 314 |
|
| 315 |
// This will populate the default values for the options |
| 316 |
// and then override them with cargo-xwin environment variables. |
| 317 |
cargo_xwin::XWinOptions::parse_from(Vec::<&str>::new()) |
| 318 |
}; |
| 319 |
|
| 320 |
let mut build = cargo_xwin::Rustc::from(cargo_rustc); |
| 321 |
build.target = vec![target_triple.to_string()]; |
| 322 |
build.xwin = xwin_options; |
| 323 |
build.build_command()? |
| 324 |
} else { |
| 325 |
if target.user_specified { |
| 326 |
cargo_rustc.target = vec![target_triple.to_string()]; |
| 327 |
} |
| 328 |
cargo_rustc.command() |
| 329 |
} |
| 330 |
} |
| 331 |
#[cfg(not(feature = "xwin"))] |
| 332 |
{ |
| 333 |
if target.user_specified { |
| 334 |
cargo_rustc.target = vec![target_triple.to_string()]; |
| 335 |
} |
| 336 |
cargo_rustc.command() |
| 337 |
} |
| 338 |
} else { |
| 339 |
#[cfg(feature = "zig")] |
| 340 |
{ |
| 341 |
let mut build = cargo_zigbuild::Rustc::from(cargo_rustc); |
| 342 |
if !context.zig { |
| 343 |
build.disable_zig_linker = true; |
| 344 |
if target.user_specified { |
| 345 |
build.target = vec![target_triple.to_string()]; |
| 346 |
} |
| 347 |
} else { |
| 348 |
println!("🛠️ Using zig for cross-compiling to {target_triple}"); |
| 349 |
build.enable_zig_ar = true; |
| 350 |
let zig_triple = if target.is_linux() && !target.is_musl_libc() { |
| 351 |
match context.platform_tag.iter().find(|tag| tag.is_manylinux()) { |
| 352 |
Some(PlatformTag::Manylinux { major, minor }) => { |
| 353 |
format!("{target_triple}.{major}.{minor}") |
| 354 |
} |
| 355 |
_ => target_triple.to_string(), |
| 356 |
} |
| 357 |
} else { |
| 358 |
target_triple.to_string() |
| 359 |
}; |
| 360 |
build.target = vec![zig_triple]; |
| 361 |
} |
| 362 |
build.build_command()? |
| 363 |
} |
| 364 |
#[cfg(not(feature = "zig"))] |
| 365 |
{ |
| 366 |
if target.user_specified { |
| 367 |
cargo_rustc.target = vec![target_triple.to_string()]; |
| 368 |
} |
| 369 |
cargo_rustc.command() |
| 370 |
} |
| 371 |
}; |
| 372 |
|
| 373 |
#[cfg(feature = "zig")] |
| 374 |
if context.zig { |
| 375 |
// Pass zig command to downstream, eg. python3-dll-a |
| 376 |
if let Ok((zig_cmd, zig_args)) = cargo_zigbuild::Zig::find_zig() { |
| 377 |
if zig_args.is_empty() { |
| 378 |
build_command.env("ZIG_COMMAND", zig_cmd); |
| 379 |
} else { |
| 380 |
build_command.env( |
| 381 |
"ZIG_COMMAND", |
| 382 |
format!("{} {}", zig_cmd.display(), zig_args.join(" ")), |
| 383 |
); |
| 384 |
}; |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
build_command |
| 389 |
// We need to capture the json messages |
| 390 |
.stdout(Stdio::piped()) |
| 391 |
// We can't get colored human and json messages from rustc as they are mutually exclusive, |
| 392 |
// but forwarding stderr is still useful in case there some non-json error |
| 393 |
.stderr(Stdio::inherit()); |
| 394 |
|
| 395 |
if !rustflags.flags.is_empty() && rustflags.flags != original_rustflags { |
| 396 |
build_command.env("CARGO_ENCODED_RUSTFLAGS", rustflags.encode()?); |
| 397 |
} |
| 398 |
|
| 399 |
if bridge_model.is_abi3() { |
| 400 |
let is_pypy_or_graalpy = python_interpreter |
| 401 |
.map(|p| p.interpreter_kind.is_pypy() || p.interpreter_kind.is_graalpy()) |
| 402 |
.unwrap_or(false); |
| 403 |
if !is_pypy_or_graalpy && !target.is_windows() { |
| 404 |
let pyo3_ver = pyo3_version(&context.cargo_metadata) |
| 405 |
.context("Failed to get pyo3 version from cargo metadata")?; |
| 406 |
if pyo3_ver < PYO3_ABI3_NO_PYTHON_VERSION { |
| 407 |
// This will make old pyo3's build script only set some predefined linker |
| 408 |
// arguments without trying to read any python configuration |
| 409 |
build_command.env("PYO3_NO_PYTHON", "1"); |
| 410 |
} |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
// Set PYO3_BUILD_EXTENSION_MODULE when building pyo3 extension modules |
| 415 |
if bridge_model.is_pyo3() && !bridge_model.is_bin() { |
| 416 |
build_command.env("PYO3_BUILD_EXTENSION_MODULE", "1"); |
| 417 |
} |
| 418 |
|
| 419 |
// Setup `PYO3_CONFIG_FILE` if we are cross compiling for pyo3 bindings |
| 420 |
if let Some(interpreter) = python_interpreter { |
| 421 |
// Target python interpreter isn't runnable when cross compiling |
| 422 |
if interpreter.runnable { |
| 423 |
if bridge_model.is_pyo3() { |
| 424 |
debug!( |
| 425 |
"Setting PYO3_PYTHON to {}", |
| 426 |
interpreter.executable.display() |
| 427 |
); |
| 428 |
build_command |
| 429 |
.env("PYO3_PYTHON", &interpreter.executable) |
| 430 |
.env( |
| 431 |
"PYO3_ENVIRONMENT_SIGNATURE", |
| 432 |
interpreter.environment_signature(), |
| 433 |
); |
| 434 |
} |
| 435 |
|
| 436 |
// and legacy pyo3 versions |
| 437 |
build_command.env("PYTHON_SYS_EXECUTABLE", &interpreter.executable); |
| 438 |
} else if bridge_model.is_pyo3() && env::var_os("PYO3_CONFIG_FILE").is_none() { |
| 439 |
let pyo3_config = interpreter.pyo3_config_file(); |
| 440 |
let maturin_target_dir = context.target_dir.join(env!("CARGO_PKG_NAME")); |
| 441 |
let config_file = maturin_target_dir.join(format!( |
| 442 |
"pyo3-config-{}-{}.{}.txt", |
| 443 |
target_triple, interpreter.major, interpreter.minor |
| 444 |
)); |
| 445 |
fs::create_dir_all(&maturin_target_dir)?; |
| 446 |
// We don't want to rewrite the file every time as that will make cargo |
| 447 |
// trigger a rebuild of the project every time |
| 448 |
let existing_pyo3_config = fs::read_to_string(&config_file).unwrap_or_default(); |
| 449 |
if pyo3_config != existing_pyo3_config { |
| 450 |
fs::write(&config_file, pyo3_config).with_context(|| { |
| 451 |
format!( |
| 452 |
"Failed to create pyo3 config file at '{}'", |
| 453 |
config_file.display() |
| 454 |
) |
| 455 |
})?; |
| 456 |
} |
| 457 |
let abs_config_file = config_file.normalize()?.into_path_buf(); |
| 458 |
build_command.env("PYO3_CONFIG_FILE", abs_config_file); |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
if let Some(lib_dir) = env::var_os("MATURIN_PYTHON_SYSCONFIGDATA_DIR") { |
| 463 |
build_command.env("PYO3_CROSS_LIB_DIR", lib_dir); |
| 464 |
} |
| 465 |
|
| 466 |
// Set default macOS deployment target version for non-editable builds |
| 467 |
if !context.editable && target.is_macos() && env::var_os("MACOSX_DEPLOYMENT_TARGET").is_none() { |
| 468 |
use crate::build_context::rustc_macosx_target_version; |
| 469 |
|
| 470 |
let target_config = context |
| 471 |
.pyproject_toml |
| 472 |
.as_ref() |
| 473 |
.and_then(|x| x.target_config(target_triple)); |
| 474 |
let deployment_target = if let Some(deployment_target) = target_config |
| 475 |
.as_ref() |
| 476 |
.and_then(|config| config.macos_deployment_target.as_ref()) |
| 477 |
{ |
| 478 |
eprintln!( |
| 479 |
"💻 Using `MACOSX_DEPLOYMENT_TARGET={deployment_target}` for {target_triple} by configuration" |
| 480 |
); |
| 481 |
deployment_target.clone() |
| 482 |
} else { |
| 483 |
let (major, minor) = rustc_macosx_target_version(target_triple); |
| 484 |
eprintln!( |
| 485 |
"💻 Using `MACOSX_DEPLOYMENT_TARGET={major}.{minor}` for {target_triple} by default" |
| 486 |
); |
| 487 |
format!("{major}.{minor}") |
| 488 |
}; |
| 489 |
build_command.env("MACOSX_DEPLOYMENT_TARGET", deployment_target); |
| 490 |
} |
| 491 |
Ok(build_command) |
| 492 |
} |
| 493 |
|
| 494 |
fn compile_target( |
| 495 |
context: &BuildContext, |
| 496 |
mut build_command: Command, |
| 497 |
) -> Result<HashMap<CrateType, BuildArtifact>> { |
| 498 |
debug!("Running {:?}", build_command); |
| 499 |
|
| 500 |
let using_cross = build_command |
| 501 |
.get_program() |
| 502 |
.to_string_lossy() |
| 503 |
.starts_with("cross"); |
| 504 |
let mut cargo_build = build_command |
| 505 |
.spawn() |
| 506 |
.context("Failed to run `cargo rustc`")?; |
| 507 |
|
| 508 |
let mut artifacts = HashMap::new(); |
| 509 |
let mut linked_paths = Vec::new(); |
| 510 |
|
| 511 |
let stream = cargo_build |
| 512 |
.stdout |
| 513 |
.take() |
| 514 |
.expect("Cargo build should have a stdout"); |
| 515 |
for message in cargo_metadata::Message::parse_stream(BufReader::new(stream)) { |
| 516 |
let message = message.context("Failed to parse cargo metadata message")?; |
| 517 |
trace!("cargo message: {:?}", message); |
| 518 |
match message { |
| 519 |
cargo_metadata::Message::CompilerArtifact(artifact) => { |
| 520 |
let package_in_metadata = context |
| 521 |
.cargo_metadata |
| 522 |
.packages |
| 523 |
.iter() |
| 524 |
.find(|package| package.id == artifact.package_id); |
| 525 |
let crate_name = match package_in_metadata { |
| 526 |
Some(package) => &package.name, |
| 527 |
None => { |
| 528 |
let package_id = &artifact.package_id; |
| 529 |
// Ignore the package if it's coming from Rust sysroot when compiling with `-Zbuild-std` |
| 530 |
let should_warn = !package_id.repr.contains("rustup") |
| 531 |
&& !package_id.repr.contains("rustlib") |
| 532 |
&& !artifact.features.contains(&"rustc-dep-of-std".to_string()); |
| 533 |
if should_warn { |
| 534 |
// This is a spurious error I don't really understand |
| 535 |
eprintln!( |
| 536 |
"⚠️ Warning: The package {package_id} wasn't listed in `cargo metadata`" |
| 537 |
); |
| 538 |
} |
| 539 |
continue; |
| 540 |
} |
| 541 |
}; |
| 542 |
|
| 543 |
// Extract the location of the .so/.dll/etc. from cargo's json output |
| 544 |
if crate_name == &context.crate_name { |
| 545 |
let tuples = artifact |
| 546 |
.target |
| 547 |
.crate_types |
| 548 |
.into_iter() |
| 549 |
.zip(artifact.filenames); |
| 550 |
for (crate_type, filename) in tuples { |
| 551 |
let path = if using_cross && filename.starts_with("/target") { |
| 552 |
// Convert cross target path in docker back to path on host |
| 553 |
context |
| 554 |
.cargo_metadata |
| 555 |
.target_directory |
| 556 |
.join(filename.strip_prefix("/target").unwrap()) |
| 557 |
.into_std_path_buf() |
| 558 |
} else { |
| 559 |
filename.into() |
| 560 |
}; |
| 561 |
let artifact = BuildArtifact { |
| 562 |
path, |
| 563 |
linked_paths: Vec::new(), |
| 564 |
}; |
| 565 |
artifacts.insert(crate_type, artifact); |
| 566 |
} |
| 567 |
} |
| 568 |
} |
| 569 |
// See https://doc.rust-lang.org/cargo/reference/external-tools.html#build-script-output |
| 570 |
cargo_metadata::Message::BuildScriptExecuted(msg) => { |
| 571 |
for path in msg.linked_paths.iter().map(|p| p.as_str()) { |
| 572 |
// `linked_paths` may include a "KIND=" prefix in the string where KIND is the library kind |
| 573 |
if let Some(index) = path.find('=') { |
| 574 |
linked_paths.push(path[index + 1..].to_string()); |
| 575 |
} else { |
| 576 |
linked_paths.push(path.to_string()); |
| 577 |
} |
| 578 |
} |
| 579 |
} |
| 580 |
cargo_metadata::Message::CompilerMessage(msg) => { |
| 581 |
println!("{}", msg.message); |
| 582 |
} |
| 583 |
_ => (), |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
// Add linked_paths to build artifacts |
| 588 |
for artifact in artifacts.values_mut() { |
| 589 |
artifact.linked_paths.clone_from(&linked_paths); |
| 590 |
} |
| 591 |
|
| 592 |
let status = cargo_build |
| 593 |
.wait() |
| 594 |
.expect("Failed to wait on cargo child process"); |
| 595 |
|
| 596 |
if !status.success() { |
| 597 |
bail!( |
| 598 |
r#"Cargo build finished with "{}": `{:?}`"#, |
| 599 |
status, |
| 600 |
build_command, |
| 601 |
) |
| 602 |
} |
| 603 |
|
| 604 |
Ok(artifacts) |
| 605 |
} |
| 606 |
|
| 607 |
/// Checks that the native library contains a function called `PyInit_<module name>` and warns |
| 608 |
/// if it's missing. |
| 609 |
/// |
| 610 |
/// That function is the python's entrypoint for loading native extensions, i.e. python will fail |
| 611 |
/// to import the module with error if it's missing or named incorrectly |
| 612 |
/// |
| 613 |
/// Currently the check is only run on linux, macOS and Windows |
| 614 |
#[instrument(skip_all)] |
| 615 |
pub fn warn_missing_py_init(artifact: &Path, module_name: &str) -> Result<()> { |
| 616 |
let py_init = format!("PyInit_{module_name}"); |
| 617 |
let mut fd = File::open(artifact)?; |
| 618 |
let mut buffer = Vec::new(); |
| 619 |
fd.read_to_end(&mut buffer)?; |
| 620 |
let mut found = false; |
| 621 |
match goblin::Object::parse(&buffer)? { |
| 622 |
goblin::Object::Elf(elf) => { |
| 623 |
for dyn_sym in elf.dynsyms.iter() { |
| 624 |
if py_init == elf.dynstrtab[dyn_sym.st_name] { |
| 625 |
found = true; |
| 626 |
break; |
| 627 |
} |
| 628 |
} |
| 629 |
} |
| 630 |
goblin::Object::Mach(mach) => { |
| 631 |
match mach { |
| 632 |
goblin::mach::Mach::Binary(macho) => { |
| 633 |
for sym in macho.exports()? { |
| 634 |
let sym_name = sym.name; |
| 635 |
if py_init == sym_name.strip_prefix('_').unwrap_or(&sym_name) { |
| 636 |
found = true; |
| 637 |
break; |
| 638 |
} |
| 639 |
} |
| 640 |
if !found { |
| 641 |
for sym in macho.symbols() { |
| 642 |
let (sym_name, _) = sym?; |
| 643 |
if py_init == sym_name.strip_prefix('_').unwrap_or(sym_name) { |
| 644 |
found = true; |
| 645 |
break; |
| 646 |
} |
| 647 |
} |
| 648 |
} |
| 649 |
} |
| 650 |
goblin::mach::Mach::Fat(_) => { |
| 651 |
// Ignore fat macho, |
| 652 |
// we only generate them by combining thin binaries which is handled above |
| 653 |
found = true |
| 654 |
} |
| 655 |
} |
| 656 |
} |
| 657 |
goblin::Object::PE(pe) => { |
| 658 |
for sym in &pe.exports { |
| 659 |
if let Some(sym_name) = sym.name { |
| 660 |
if py_init == sym_name { |
| 661 |
found = true; |
| 662 |
break; |
| 663 |
} |
| 664 |
} |
| 665 |
} |
| 666 |
} |
| 667 |
_ => { |
| 668 |
// Currently, only linux, macOS and Windows are implemented |
| 669 |
found = true |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
if !found { |
| 674 |
eprintln!( |
| 675 |
"⚠️ Warning: Couldn't find the symbol `{py_init}` in the native library. \ |
| 676 |
Python will fail to import this module. \ |
| 677 |
If you're using pyo3, check that `#[pymodule]` uses `{module_name}` as module name" |
| 678 |
) |
| 679 |
} |
| 680 |
|
| 681 |
Ok(()) |
| 682 |
} |
| 683 |
|
| 684 |
fn pyo3_version(cargo_metadata: &cargo_metadata::Metadata) -> Option<(u64, u64, u64)> { |
| 685 |
let packages: HashMap<&str, &cargo_metadata::Package> = cargo_metadata |
| 686 |
.packages |
| 687 |
.iter() |
| 688 |
.filter_map(|pkg| { |
| 689 |
let name = &pkg.name; |
| •690 |
if name.as_str() == "pyo3" || name.as_str() == "pyo3-ffi" { |
| 691 |
Some((name.as_ref(), pkg)) |
| 692 |
} else { |
| 693 |
None |
| 694 |
} |
| 695 |
}) |
| 696 |
.collect(); |
| 697 |
packages |
| 698 |
.get("pyo3") |
| 699 |
.or_else(|| packages.get("pyo3-ffi")) |
| 700 |
.map(|pkg| (pkg.version.major, pkg.version.minor, pkg.version.patch)) |
| 701 |
} |