Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some validation to rustc-link-arg #9523

Merged
merged 3 commits into from
Jun 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 43 additions & 5 deletions src/cargo/core/compiler/custom_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::job::{Freshness, Job, Work};
use super::{fingerprint, Context, LinkType, Unit};
use crate::core::compiler::context::Metadata;
use crate::core::compiler::job_queue::JobState;
use crate::core::{profiles::ProfileRoot, PackageId};
use crate::core::{profiles::ProfileRoot, PackageId, Target};
use crate::util::errors::CargoResult;
use crate::util::machine_message::{self, Message};
use crate::util::{internal, profile};
Expand Down Expand Up @@ -296,6 +296,9 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {

let extra_link_arg = cx.bcx.config.cli_unstable().extra_link_arg;
let nightly_features_allowed = cx.bcx.config.nightly_features_allowed;
let targets: Vec<Target> = unit.pkg.targets().iter().cloned().collect();
// Need a separate copy for the fresh closure.
let targets_fresh = targets.clone();

// Prepare the unit of "dirty work" which will actually run the custom build
// command.
Expand Down Expand Up @@ -405,6 +408,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
&script_out_dir,
extra_link_arg,
nightly_features_allowed,
&targets,
)?;

if json_messages {
Expand Down Expand Up @@ -432,6 +436,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
&script_out_dir,
extra_link_arg,
nightly_features_allowed,
&targets_fresh,
)?,
};

Expand Down Expand Up @@ -484,6 +489,7 @@ impl BuildOutput {
script_out_dir: &Path,
extra_link_arg: bool,
nightly_features_allowed: bool,
targets: &[Target],
) -> CargoResult<BuildOutput> {
let contents = paths::read_bytes(path)?;
BuildOutput::parse(
Expand All @@ -494,6 +500,7 @@ impl BuildOutput {
script_out_dir,
extra_link_arg,
nightly_features_allowed,
targets,
)
}

Expand All @@ -509,6 +516,7 @@ impl BuildOutput {
script_out_dir: &Path,
extra_link_arg: bool,
nightly_features_allowed: bool,
targets: &[Target],
) -> CargoResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
Expand Down Expand Up @@ -562,10 +570,28 @@ impl BuildOutput {
"rustc-link-lib" => library_links.push(value.to_string()),
"rustc-link-search" => library_paths.push(PathBuf::from(value)),
"rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
if !targets.iter().any(|target| target.is_cdylib()) {
bail!(
"invalid instruction `cargo:{}` from {}\n\
The package {} does not have a cdylib target.",
key,
whence,
pkg_descr
);
}
linker_args.push((LinkType::Cdylib, value))
}
"rustc-link-arg-bins" => {
if extra_link_arg {
if !targets.iter().any(|target| target.is_bin()) {
bail!(
"invalid instruction `cargo:{}` from {}\n\
The package {} does not have a bin target.",
key,
whence,
pkg_descr
);
}
Comment on lines +586 to +594
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we extract the same logic from these three bail!?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that, but I didn't see a way to consolidate it such that it wouldn't end up with more total lines of code. Only the first two have the same structure. The third has a different structure and text, which would need customization.

Thanks for the suggestion, I do agree it is a bit repetitive and verbose. Hopefully RFC 2795 will make progress, which I think would simplify this a bit.

If there are more link-types added in the future, perhaps might spend some more effort to consolidate it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. Thank for your detailed explanation!
BTW, RFC 2795 looks really promising 😲

linker_args.push((LinkType::Bin, value));
} else {
warnings.push(format!("cargo:{} requires -Zextra-link-arg flag", key));
Expand All @@ -575,10 +601,21 @@ impl BuildOutput {
if extra_link_arg {
let parts = value.splitn(2, "=").collect::<Vec<_>>();
if parts.len() == 2 {
linker_args.push((
LinkType::SingleBin(parts[0].to_string()),
parts[1].to_string(),
));
let bin_name = parts[0].to_string();
if !targets
.iter()
.any(|target| target.is_bin() && target.name() == bin_name)
{
bail!(
"invalid instruction `cargo:{}` from {}\n\
The package {} does not have a bin target with the name `{}`.",
key,
whence,
pkg_descr,
bin_name
);
}
linker_args.push((LinkType::SingleBin(bin_name), parts[1].to_string()));
} else {
warnings.push(format!(
"cargo:{} has invalid syntax: expected `cargo:{}=BIN=ARG`",
Expand Down Expand Up @@ -900,6 +937,7 @@ fn prev_build_output(cx: &mut Context<'_, '_>, unit: &Unit) -> (Option<BuildOutp
&script_out_dir,
extra_link_arg,
cx.bcx.config.nightly_features_allowed,
unit.pkg.targets(),
)
.ok(),
prev_script_out_dir,
Expand Down
53 changes: 53 additions & 0 deletions tests/testsuite/build_script_extra_link_arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,56 @@ fn build_script_extra_link_arg_warn_without_flag() {
.with_stderr_contains("warning: cargo:rustc-link-arg requires -Zextra-link-arg flag")
.run();
}

#[cargo_test]
fn link_arg_missing_target() {
// Errors when a given target doesn't exist.
let p = project()
.file("src/lib.rs", "")
.file(
"build.rs",
r#"fn main() { println!("cargo:rustc-link-arg-cdylib=--bogus"); }"#,
)
.build();

p.cargo("check")
.with_status(101)
.with_stderr("\
[COMPILING] foo [..]
error: invalid instruction `cargo:rustc-link-arg-cdylib` from build script of `foo v0.0.1 ([ROOT]/foo)`
The package foo v0.0.1 ([ROOT]/foo) does not have a cdylib target.
")
.run();

p.change_file(
"build.rs",
r#"fn main() { println!("cargo:rustc-link-arg-bins=--bogus"); }"#,
);

p.cargo("check -Zextra-link-arg")
.masquerade_as_nightly_cargo()
.with_status(101)
.with_stderr("\
[COMPILING] foo [..]
error: invalid instruction `cargo:rustc-link-arg-bins` from build script of `foo v0.0.1 ([ROOT]/foo)`
The package foo v0.0.1 ([ROOT]/foo) does not have a bin target.
")
.run();

p.change_file(
"build.rs",
r#"fn main() { println!("cargo:rustc-link-arg-bin=abc=--bogus"); }"#,
);

p.cargo("check -Zextra-link-arg")
.masquerade_as_nightly_cargo()
.with_status(101)
.with_stderr(
"\
[COMPILING] foo [..]
error: invalid instruction `cargo:rustc-link-arg-bin` from build script of `foo v0.0.1 ([ROOT]/foo)`
The package foo v0.0.1 ([ROOT]/foo) does not have a bin target with the name `abc`.
",
)
.run();
}