Skip to content

Commit

Permalink
Produce sane CARGO when invoked through ld.so
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon Gjengset committed Nov 23, 2021
1 parent e1fb176 commit 73a52f2
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/cargo/util/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,32 @@ impl Config {
}

let exe = from_current_exe()
.ok()
.filter(|exe| {
if let Some(name) = exe.file_name().and_then(|name| name.to_str()) {
if name.starts_with("ld-")
&& (name.ends_with(".so") || name.contains(".so."))
{
// Cargo seems to be executed directly through the dynamic linker
// (e.g., /usr/lib64/ld-linux-x86-64.so.2), which is then what
// current_exe points at. That's not the path to Cargo itself
// though, so we need to fall back to argv[0], which the step that
// set up the invocation of Cargo this way has hopefully set
// correctly (likely with exec -a).
//
// See
//
// https://github.com/rust-lang/cargo/issues/10113
//
// and
//
// https://linux.die.net/man/8/ld-linux.so
return false;
}
}
true
})
.ok_or(())
.or_else(|_| from_argv())
.with_context(|| "couldn't get the path to cargo executable")?;
Ok(exe)
Expand Down
42 changes: 40 additions & 2 deletions tests/testsuite/build_script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use cargo_test_support::compare::assert_match_exact;
use cargo_test_support::paths::CargoPathExt;
use cargo_test_support::registry::Package;
use cargo_test_support::tools;
use cargo_test_support::{basic_manifest, cross_compile, is_coarse_mtime, project};
use cargo_test_support::{basic_manifest, cargo_exe, cross_compile, is_coarse_mtime, project};
use cargo_test_support::{execs, process, tools};
use cargo_test_support::{rustc_host, sleep_ms, slow_cpu_multiplier, symlink_supported};
use cargo_util::paths::remove_dir_all;
use std::env;
Expand Down Expand Up @@ -137,6 +137,44 @@ fn custom_build_env_vars() {
p.cargo("build --features bar_feat").run();
}

#[cargo_test]
fn issue_10113() {
use std::path::Path;

let p = project()
.file(
"build.rs",
r#"
use std::env;
use std::path::Path;
fn main() {
let cargo = dbg!(env::var("CARGO").unwrap());
let cargo = Path::new(&cargo);
assert!(cargo.ends_with("cargo"));
assert!(cargo.exists());
}
"#,
)
.file("src/lib.rs", "")
.build();

p.cargo("build").run();

let ld = Path::new("/usr/lib64/ld-linux-x86-64.so.2");
if cfg!(target_os = "linux") {
assert!(ld.exists());
let mut proc = process(ld);
proc.cwd(p.root());
proc.arg(&cargo_exe());
proc.arg("build");
// Touch the file so build is re-run.
p.change_file("src/lib.rs", "");
let mut execs = execs().with_process_builder(proc);
execs.run();
}
}

#[cargo_test]
fn custom_build_env_var_rustflags() {
let rustflags = "--cfg=special";
Expand Down

0 comments on commit 73a52f2

Please sign in to comment.