Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ gimli = { version = "0.34.0", default-features = false, features = ["read", "std
git2 = { version = "0.21", optional = true }
humantime-serde = "1"
indexmap = { version = "~1.8", features = ["serde-1"] }
llvm_profparser = { version = "0.15", default-features = false }
llvm_profparser = { version = "0.16", default-features = false }
object = "0.40"
proc-macro2 = { version = "1.0", features = ["span-locations"] }
quick-xml = "0.42"
Expand All @@ -59,6 +59,7 @@ tracing-subscriber = { version = "0.3.23", default-features = false, features =
walkdir = "2.5.0"
glob = "0.3.3"
cargo-config2 = "0.1.44"
tempfile = "3"

[target.'cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")))'.dependencies]
libc = "0.2.184"
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Options:
--profile <NAME> Build artifacts with the specified profile
--ignore-tests Ignore lines of test functions when collecting coverage (default)
--no-dead-code Stops tarpaulin from building projects with -Clink-dead-code
--instrument-all Instrument all dependencies as well as project crates (LLVM only)
--include-tests Include lines of test functions when collecting coverage
--ignore-panics Ignore panic macros in tests
--count Counts the number of hits during coverage
Expand Down
3 changes: 3 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ pub struct ConfigArgs {
/// Stops tarpaulin from building projects with -Clink-dead-code
#[arg(long)]
pub no_dead_code: bool,
/// Instrument all dependencies as well as project crates (LLVM only)
#[arg(long)]
pub instrument_all: bool,
/// Include lines of test functions when collecting coverage
#[arg(long)]
pub include_tests: bool,
Expand Down
61 changes: 61 additions & 0 deletions src/cargo/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::config::Config;
use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::{info, warn};
Expand All @@ -13,6 +14,8 @@ pub struct CargoConfigFields {
pub target_rust_flags: Vec<String>,
pub env_vars: HashMap<String, String>,
pub target_runner: Option<CargoTargetRunner>,
// Keep the allowlist available to rustc wrappers and nested Cargo builds.
pub(crate) local_packages_file: Option<tempfile::NamedTempFile>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -113,6 +116,64 @@ pub fn get_cargo_config(config: &Config) -> CargoConfigFields {
result
}

pub(super) fn configure_coverage_wrapper(
config: &Config,
metadata: &cargo_metadata::Metadata,
result: &mut CargoConfigFields,
) -> io::Result<()> {
// A library caller's executable need not implement our compiler protocol.
let Ok(executable) = env::var("__TARPAULIN_WRAPPER_EXE") else {
return Ok(());
};
if config.engine() != crate::config::TraceEngine::Llvm || config.instrument_all {
return Ok(());
}
let cargo_config =
cargo_config2::Config::load_with_cwd(config.root()).map_err(io::Error::other)?;
let directories: Vec<_> = metadata
.packages
.iter()
.filter(|package| package.source.is_none())
.map(|package| {
package
.manifest_path
.parent()
.expect("Cargo manifest has a parent directory")
.as_str()
})
.collect();
// A large workspace can exceed the OS limit for a single environment value.
let mut packages_file = tempfile::Builder::new()
.prefix("tarpaulin-packages-")
.tempfile()?;
packages_file.write_all(
serde_json::to_string(&directories)
.expect("package paths serialize to JSON")
.as_bytes(),
)?;
result.env_vars.insert(
"__TARPAULIN_LOCAL_PACKAGES_FILE".into(),
packages_file.path().to_string_lossy().into_owned(),
);
result.local_packages_file = Some(packages_file);
info!("Using RUSTC_WRAPPER for local-package coverage");
result.env_vars.insert("RUSTC_WRAPPER".into(), executable);
result.env_vars.insert(
"__TARPAULIN_PREVIOUS_WRAPPER".into(),
cargo_config
.build
.rustc_wrapper
.as_ref()
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_default(),
);
result.env_vars.insert(
"__TARPAULIN_COVERAGE_FLAGS".into(),
super::llvm_coverage_rustflag().trim().into(),
);
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
51 changes: 43 additions & 8 deletions src/cargo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ mod config_file;

const BUILD_PROFRAW: &str = "build_rs_cov.profraw";

pub(crate) const COVERAGE_WRAPPER_ENV: [&str; 5] = [
"RUSTC_WORKSPACE_WRAPPER",
"RUSTC_WRAPPER",
"__TARPAULIN_COVERAGE_FLAGS",
"__TARPAULIN_PREVIOUS_WRAPPER",
"__TARPAULIN_LOCAL_PACKAGES_FILE",
];

cfg_if::cfg_if! {
if #[cfg(target_os = "windows")] {
pub const LD_PATH_VAR: &'static str ="PATH";
Expand Down Expand Up @@ -230,17 +238,12 @@ static CARGO_VERSION_INFO: LazyLock<Option<CargoVersionInfo>> = LazyLock::new(||
});

pub fn get_tests(config: &Config) -> Result<CargoOutput, RunError> {
let cargo_config = Rc::new(get_cargo_config(config));
let mut cargo_config = get_cargo_config(config);
if config.engine() == TraceEngine::Ptrace && cargo_config.target_runner.is_some() {
warn!(
"Target runner configured, but the ptrace engine does not support target runners. The runner will be ignored"
);
}
let mut result = CargoOutput {
test_binaries: vec![],
binaries: vec![],
cargo_config: cargo_config.clone(),
};
if config.force_clean() {
let cleanup_dir = if config.release {
config.target_dir().join("release")
Expand Down Expand Up @@ -284,6 +287,15 @@ pub fn get_tests(config: &Config) -> Result<CargoOutput, RunError> {
.exec()
.map_err(|e| RunError::Cargo(e.to_string()))?;

config_file::configure_coverage_wrapper(config, &metadata, &mut cargo_config)
.map_err(|e| RunError::Cargo(format!("Unable to configure coverage wrapper: {e}")))?;
let cargo_config = Rc::new(cargo_config);
let mut result = CargoOutput {
test_binaries: vec![],
binaries: vec![],
cargo_config: cargo_config.clone(),
};

for ty in &config.run_types {
run_cargo(
&metadata,
Expand Down Expand Up @@ -803,6 +815,22 @@ fn handle_llvm_flags(value: &mut String, config: &Config) {
}

pub fn rust_flags(config: &Config, cargo_config: &CargoConfigFields) -> String {
rust_flags_impl(config, cargo_config, true)
}

pub(crate) fn build_rust_flags(config: &Config, cargo_config: &CargoConfigFields) -> String {
let wrapped = cargo_config
.env_vars
.contains_key("__TARPAULIN_COVERAGE_FLAGS");
let mut flags = rust_flags_impl(config, cargo_config, !wrapped);
if wrapped {
// Nested build systems can clear rustflags to opt out of instrumentation.
flags.push_str(" --cfg=tarpaulin_instrumentation");
}
flags
}

fn rust_flags_impl(config: &Config, cargo_config: &CargoConfigFields, instrument: bool) -> String {
const RUSTFLAGS: &str = "RUSTFLAGS";
let mut value = config.rustflags.clone().unwrap_or_default();
value.push_str(" -Cdebuginfo=2 ");
Expand All @@ -813,7 +841,9 @@ pub fn rust_flags(config: &Config, cargo_config: &CargoConfigFields) -> String {
if config.release {
value.push_str("-Cdebug-assertions=off ");
}
handle_llvm_flags(&mut value, config);
if instrument || config.engine() != TraceEngine::Llvm {
handle_llvm_flags(&mut value, config);
}
static DEBUG_INFO: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\-C\s*debuginfo=\d").unwrap());
static DEAD_CODE: LazyLock<Regex> =
Expand Down Expand Up @@ -903,7 +933,12 @@ fn setup_environment(cmd: &mut Command, config: &Config, cargo_config: &CargoCon
// https://github.com/rust-lang/rust/issues/107447
cmd.env("LLVM_PROFILE_FILE", config.root().join(BUILD_PROFRAW));
cmd.env("TARPAULIN", "1");
let value = rust_flags(config, cargo_config);
let value = build_rust_flags(config, cargo_config);
for key in COVERAGE_WRAPPER_ENV {
if let Some(value) = cargo_config.env_vars.get(key) {
cmd.env(key, value);
}
}
// Cargo splits RUSTFLAGS on whitespace, so pass each flag as an encoded argument.
cmd.env_remove("RUSTFLAGS");
cmd.env(
Expand Down
21 changes: 21 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ pub struct Config {
/// Doesn't link projects with `-Clink-dead-code`
#[serde(rename = "no-dead-code")]
pub no_dead_code: bool,
/// Instrument registry and Git dependencies as well as local crates (LLVM only).
#[serde(rename = "instrument-all")]
pub instrument_all: bool,
/// Include all available features in target build
#[serde(rename = "all-features")]
pub all_features: bool,
Expand Down Expand Up @@ -220,6 +223,7 @@ impl Default for Config {
force_clean: true,
skip_clean: false,
no_dead_code: false,
instrument_all: false,
verbose: false,
debug: false,
follow_exec: false,
Expand Down Expand Up @@ -316,6 +320,7 @@ impl From<ConfigArgs> for ConfigWrapper {
include_tests: args.include_tests,
ignore_panics: args.ignore_panics,
no_dead_code: args.no_dead_code,
instrument_all: args.instrument_all,
force_clean,
skip_clean: !force_clean,
no_fail_fast: args.no_fail_fast,
Expand Down Expand Up @@ -636,6 +641,7 @@ impl Config {
self.run_ignored |= other.run_ignored;
self.release |= other.release;
self.no_dead_code |= other.no_dead_code;
self.instrument_all |= other.instrument_all;
self.count |= other.count;
self.all_features |= other.all_features;
self.implicit_test_threads |= other.implicit_test_threads;
Expand Down Expand Up @@ -980,6 +986,21 @@ mod tests {
assert!(conf[0].root().is_absolute());
}

/// CLI and file opt-outs survive merging in either direction.
#[test]
fn instrument_all_configuration() {
let args = TarpaulinCli::parse_from(["tarpaulin", "--ignore-config", "--instrument-all"]);
let cli = ConfigWrapper::from(args.config).0.remove(0);
assert!(cli.instrument_all);
let file: Config =
toml::from_str("instrument-all = true").expect("parse instrumentation opt-out");
let default = Config::default();
for (mut base, override_config) in [(default.clone(), cli), (file, default)] {
base.merge(&override_config);
assert!(base.instrument_all);
}
}

#[test]
fn features_args() {
let args = TarpaulinCli::parse_from(vec![
Expand Down
9 changes: 9 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use cargo_tarpaulin::{run, setup_logging};
use std::collections::HashMap;
use tracing::{info, trace};

mod rustc_wrapper;

fn print_env(seen_rustflags: HashMap<String, Vec<String>>, prefix: &str, default_val: &str) {
info!("Printing `{}`", prefix);
if seen_rustflags.is_empty() {
Expand All @@ -23,6 +25,13 @@ fn print_env(seen_rustflags: HashMap<String, Vec<String>>, prefix: &str, default
}

fn main() -> Result<(), String> {
if rustc_wrapper::is_active() {
return rustc_wrapper::run().map_err(|e| e.to_string());
}
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
// SAFETY: CLI startup is single-threaded; this runs before argument parsing,
// logging initialization, or any application threads are started.
unsafe { std::env::set_var("__TARPAULIN_WRAPPER_EXE", executable) };
let args = CargoTarpaulinCli::from_args();

let logging_args = args.config.logging;
Expand Down
12 changes: 10 additions & 2 deletions src/process_handling/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::cargo::{CargoConfigFields, LD_PATH_VAR, rust_flags};
use crate::cargo::{CargoConfigFields, LD_PATH_VAR};
use crate::config::Color;
use crate::generate_tracemap;
use crate::path_utils::get_profile_walker;
Expand Down Expand Up @@ -223,7 +223,15 @@ fn get_env_vars(
if test.has_linker_paths() {
envars.insert(LD_PATH_VAR.to_string(), test.ld_library_path());
}
envars.insert("RUSTFLAGS".to_string(), rust_flags(config, cargo_config));
envars.insert(
"RUSTFLAGS".to_string(),
crate::cargo::build_rust_flags(config, cargo_config),
);
for key in crate::cargo::COVERAGE_WRAPPER_ENV {
if let Some(value) = cargo_config.env_vars.get(key) {
envars.insert(key.into(), value.clone());
}
}

envars
}
Expand Down
57 changes: 57 additions & 0 deletions src/rustc_wrapper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use std::{env, io, process::Command};

pub(crate) fn is_active() -> bool {
env::var_os("__TARPAULIN_COVERAGE_FLAGS").is_some()
&& env::args_os().nth(1).is_some_and(|arg| arg != "tarpaulin")
}

pub(crate) fn run() -> io::Result<()> {
let mut args = env::args_os().skip(1);
let rustc = args.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"missing compiler for coverage wrapper",
)
})?;
let previous = env::var_os("__TARPAULIN_PREVIOUS_WRAPPER").filter(|path| !path.is_empty());
let mut command = if let Some(previous) = previous {
let mut command = Command::new(previous);
command.arg(rustc);
command
} else {
Command::new(rustc)
};
let args: Vec<_> = args.collect();
// Cargo also uses the wrapper for compiler capability probes. Only actual
// crate compilations should receive instrumentation.
let compiling = args.iter().any(|arg| arg == "--crate-name")
&& !args
.iter()
.any(|arg| arg == "--print" || arg.to_string_lossy().starts_with("--print="));
command.args(&args);
let requested = args
.iter()
.any(|arg| arg == "--cfg=tarpaulin_instrumentation");
let packages_file = env::var_os("__TARPAULIN_LOCAL_PACKAGES_FILE")
.expect("wrapper requires a local package file");
let packages: Vec<std::path::PathBuf> = serde_json::from_slice(&std::fs::read(packages_file)?)
.expect("wrapper package paths must be valid JSON");
let local = env::var_os("CARGO_MANIFEST_DIR")
.is_some_and(|directory| packages.contains(&std::path::PathBuf::from(directory)));
if compiling && requested && local {
command.arg(
env::var_os("__TARPAULIN_COVERAGE_FLAGS")
.expect("wrapper mode requires coverage flags"),
);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
Err(command.exec())
}
#[cfg(not(unix))]
{
let status = command.status()?;
std::process::exit(status.code().unwrap_or(1));
}
}
Loading
Loading