Skip to content

Commit

Permalink
Better handling when host target == cross compile target
Browse files Browse the repository at this point in the history
  • Loading branch information
messense committed Feb 18, 2022
1 parent 84b5dd2 commit 407e2e4
Showing 1 changed file with 51 additions and 12 deletions.
63 changes: 51 additions & 12 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::env;
use std::path::PathBuf;
use std::process::{self, Command};
use std::str;

use anyhow::{Context, Result};
use anyhow::{bail, format_err, Context, Result};
use clap::Parser;
use fs_err as fs;

Expand Down Expand Up @@ -292,17 +293,21 @@ impl Build {

// setup zig as linker
if let Some(target) = self.target.as_ref() {
if let Some(rust_target) = rust_target {
let (zig_cc, zig_cxx) = prepare_zig_linker(target)?;
let env_target = rust_target.to_uppercase().replace("-", "_");
build.env("TARGET_CC", &zig_cc);
build.env("TARGET_CXX", &zig_cxx);
build.env(format!("CARGO_TARGET_{}_LINKER", env_target), &zig_cc);

self.setup_os_deps()?;

if rust_target.contains("windows-gnu") {
build.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
let host_target = get_host_target()?;
// we only setup zig as linker when target isn't exactly the same as host target
if host_target != *target {
if let Some(rust_target) = rust_target {
let (zig_cc, zig_cxx) = prepare_zig_linker(target)?;
let env_target = rust_target.to_uppercase().replace("-", "_");
build.env("TARGET_CC", &zig_cc);
build.env("TARGET_CXX", &zig_cxx);
build.env(format!("CARGO_TARGET_{}_LINKER", env_target), &zig_cc);

self.setup_os_deps()?;

if rust_target.contains("windows-gnu") {
build.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
}
}
}
}
Expand Down Expand Up @@ -355,3 +360,37 @@ impl Build {
Ok(())
}
}

fn get_host_target() -> Result<String> {
let output = Command::new("rustc").arg("-vV").output();
let output = match output {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
bail!(
"rustc, the rust compiler, is not installed or not in PATH. \
This package requires Rust and Cargo to compile extensions. \
Install it through the system's package manager or via https://rustup.rs/.",
);
}
Err(err) => {
return Err(err).context("Failed to run rustc to get the host target");
}
Ok(output) => output,
};

let output = str::from_utf8(&output.stdout).context("`rustc -vV` didn't return utf8 output")?;

let field = "host: ";
let host = output
.lines()
.find(|l| l.starts_with(field))
.map(|l| &l[field.len()..])
.ok_or_else(|| {
format_err!(
"`rustc -vV` didn't have a line for `{}`, got:\n{}",
field.trim(),
output
)
})?
.to_string();
Ok(host)
}

0 comments on commit 407e2e4

Please sign in to comment.