Skip to content
Merged
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
1 change: 1 addition & 0 deletions cli/cli/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ rust_binary(
"//core/quality/markdown:quality_markdown_lib",
"//core/quality/notebook:quality_notebook_lib",
"//core/quality/runner:quality_runner_lib",
"//core/quality/tools/diff:diff_lib",
"//deploy/private:dx_deploy_tools",
"//deploy/private/release:dx_release_tools",
"//qt/private/tools/rust:qt_rust_bridge",
Expand Down
1 change: 1 addition & 0 deletions cli/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ fn run_as_tool() -> Option<i32> {
Tool::SiteAggregate => dx_site_aggregate::run_process(&lossy(args)),
Tool::SiteBuild => dx_site_build::run_process(&lossy(args)),
Tool::SiteCheck => dx_site_check::run_process(&lossy(args)),
Tool::BufDiff => unified_diff::run_process(&args.collect::<Vec<_>>()),
Tool::Archiver => dx_deploy_tools::entry::archiver(&named("archiver", args)),
Tool::Hasher => dx_deploy_tools::entry::hasher(&named("hasher", args)),
Tool::SizeChecker => dx_deploy_tools::entry::size_checker(&named("size_checker", args)),
Expand Down
5 changes: 5 additions & 0 deletions cli/cli/src/multicall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub enum Tool {
SiteAggregate,
SiteBuild,
SiteCheck,
BufDiff,
}

/// The tool `dx` was started as, judged by the file stem of argv[0] so `.exe` does not matter.
Expand Down Expand Up @@ -120,6 +121,7 @@ pub fn subcommand_for(arg1: &OsStr) -> Option<Tool> {
"site_aggregate" => Some(Tool::SiteAggregate),
"site_build" => Some(Tool::SiteBuild),
"site_check" => Some(Tool::SiteCheck),
"buf_diff" => Some(Tool::BufDiff),
_ => None,
}
}
Expand Down Expand Up @@ -226,6 +228,7 @@ mod tests {
("site_aggregate", Tool::SiteAggregate),
("site_build", Tool::SiteBuild),
("site_check", Tool::SiteCheck),
("buf_diff", Tool::BufDiff),
] {
assert_eq!(subcommand_for(OsStr::new(name)), Some(tool), "{name}");
}
Expand Down Expand Up @@ -273,6 +276,8 @@ mod tests {
"site_aggregate",
"site_build",
"site_check",
"buf_diff",
"diff",
] {
assert_eq!(tool_for(OsStr::new(name)), None, "{name}");
}
Expand Down
10 changes: 5 additions & 5 deletions core/quality/families/generation.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load("//avro/private:providers.bzl", "AvroInfo")
load("//capnproto/private:providers.bzl", "CapnprotoInfo")
load("//flatbuffers:defs.bzl", "FlatBuffersInfo")
load("//core/quality:family_hooks.bzl", "upstream_files")
load("//core/quality:real_core.bzl", "real_config", "real_context", "real_make_aspect", "real_make_probe_aspect")
load("//flatbuffers:defs.bzl", "FlatBuffersInfo")
load("//thrift:defs.bzl", "ThriftInfo")

visibility(["//core/...", "//tools/..."])
Expand Down Expand Up @@ -48,7 +48,7 @@ TOOLS = {
}

_BUF_FORMAT_ATTRS = {
"_buf_diff": attr.label(default = "//core/quality/tools/diff", executable = True, cfg = "exec", doc = "The diff buf format runs from PATH."),
"_dx": attr.label(default = "@dx_prebuilt//:dx", executable = True, cfg = "exec", doc = "The dx whose buf_diff subcommand buf format runs as diff."),
}

SHARD_SPECS = {
Expand Down Expand Up @@ -149,12 +149,12 @@ def _closure_hook(tool):
return _hook

def _buf_format_context(ctx, capability):
"""Returns the inputs and options that put the pinned diff on buf format's PATH."""
"""Returns the inputs and options that put `dx buf_diff` on buf format's PATH as diff."""
if capability != "format":
return {}
return {
"inputs": [ctx.executable._buf_diff],
"options": {"path_tools": [("diff", ctx.executable._buf_diff)]},
"inputs": [ctx.executable._dx],
"options": {"path_tools": [("diff", ctx.executable._dx, ["buf_diff"])]},
}

def _buf_hook(target, ctx, _resolved, capability, _what, _shared):
Expand Down
9 changes: 8 additions & 1 deletion core/quality/real_core.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,13 @@ def _staged_line(f):
return None
return rel + "\t" + f.path

def _path_tool(helper):
"""Returns the request entry of a (name, file) or (name, file, leading args) path tool."""
entry = {"binary": helper[1].path, "name": helper[0]}
if len(helper) > 2:
entry["args"] = helper[2]
return entry

def _staged_file_list(ctx, name, staged):
"""Writes one `rel<TAB>exec path` line per staged file without flattening the depsets."""
out = ctx.actions.declare_file(name)
Expand Down Expand Up @@ -542,7 +549,7 @@ def _real_pipeline_action(cfg, target, ctx, capability, allowed_tools, output_su
env = tool_env_entries.get(tool, []),
upstream = [f.path for f in (found.upstream if found != None else [])],
search_paths = [f.path for f in options.get("search_paths", [])],
path_tools = [{"binary": f.path, "name": name} for (name, f) in options.get("path_tools", [])],
path_tools = [_path_tool(helper) for helper in options.get("path_tools", [])],
)

doc = real_request_doc(
Expand Down
5 changes: 4 additions & 1 deletion core/quality/runner/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ fn real_tool(
path_tools: entry
.path_tools
.iter()
.map(|(name, binary)| (name.clone(), absolute(cwd, binary.clone())))
.map(|helper| crate::real::PathTool {
binary: absolute(cwd, helper.binary.clone()),
..helper.clone()
})
.collect(),
search_paths: entry
.search_paths
Expand Down
16 changes: 13 additions & 3 deletions core/quality/runner/src/matrix_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ pub struct ManifestTool {
pub struct ManifestPathTool {
pub name: String,
pub binary_key: String,
#[serde(default)]
pub args: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
Expand Down Expand Up @@ -159,7 +161,8 @@ pub struct ResolvedTool {
pub binary: Option<PathBuf>,
pub files: Vec<(String, PathBuf)>,
pub upstream: Vec<PathBuf>,
pub path_tools: Vec<(String, PathBuf)>,
/// Name, binary and leading args of each helper on the tool's `PATH`.
pub path_tools: Vec<(String, PathBuf, Vec<String>)>,
}

fn lookup(resolver: &Resolver, key: &str) -> Result<PathBuf, HarnessError> {
Expand Down Expand Up @@ -233,7 +236,11 @@ pub fn resolve_manifest(resolver: &Resolver, manifest: Manifest) -> Result<Resol
}
let mut path_tools = Vec::with_capacity(entry.path_tools.len());
for helper in &entry.path_tools {
path_tools.push((helper.name.clone(), lookup(resolver, &helper.binary_key)?));
path_tools.push((
helper.name.clone(),
lookup(resolver, &helper.binary_key)?,
helper.args.clone(),
));
}
tools.insert(
tool.clone(),
Expand Down Expand Up @@ -294,6 +301,8 @@ struct RequestEnv {
struct RequestPathTool {
name: String,
binary: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
args: Vec<String>,
}

#[derive(serde::Serialize)]
Expand Down Expand Up @@ -389,9 +398,10 @@ pub fn build_request(
.map(|paths| paths.path_tools.as_slice())
.unwrap_or_default()
.iter()
.map(|(name, path)| RequestPathTool {
.map(|(name, path, args)| RequestPathTool {
name: name.clone(),
binary: display(path),
args: args.clone(),
})
.collect(),
},
Expand Down
112 changes: 85 additions & 27 deletions core/quality/runner/src/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,17 @@ pub struct RealTool {
pub tool_files: Vec<(String, Vec<u8>)>,
pub upstream_diagnostics: Vec<PathBuf>,
pub search_paths: Vec<PathBuf>,
/// Helper executables placed on the child's `PATH` as shims: `(name, binary)`.
pub path_tools: Vec<(String, PathBuf)>,
/// Helper executables placed on the child's `PATH` as shims.
pub path_tools: Vec<PathTool>,
}

/// One helper the tool finds by name on its `PATH`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathTool {
pub name: String,
pub binary: PathBuf,
/// Arguments the shim passes before the caller's, such as a dx subcommand.
pub args: Vec<String>,
}

pub type SpawnFn = fn(&[OsString], &Path, &[(OsString, OsString)]) -> io::Result<ChildOutput>;
Expand Down Expand Up @@ -185,21 +194,25 @@ fn launcher_env(tool_id: &str, binary: &Path) -> Vec<(OsString, OsString)> {
Vec::new()
}

/// A `/bin/sh` shim that sets the launcher's env, then execs its absolute path.
fn unix_shim(binary: &str, env: &[(String, String)]) -> String {
/// A `/bin/sh` shim that sets the launcher's env, then execs its absolute path with `args` first.
fn unix_shim(binary: &str, args: &[String], env: &[(String, String)]) -> String {
use dx_process::shell::quote;
let mut out = String::from("#!/bin/sh\n");
for (key, value) in env {
out.push_str(&format!("{key}={}\nexport {key}\n", quote(value)));
}
// The child PATH is only the shim dir.
out.push_str("unset PATH\n");
out.push_str(&format!("exec {} \"$@\"\n", quote(binary)));
out.push_str(&format!("exec {}", quote(binary)));
for arg in args {
out.push_str(&format!(" {}", quote(arg)));
}
out.push_str(" \"$@\"\n");
out
}

/// A `.cmd` shim with CRLF endings. Characters `cmd.exe` would reinterpret are refused.
fn windows_shim(binary: &str, env: &[(String, String)]) -> Result<String, String> {
fn windows_shim(binary: &str, args: &[String], env: &[(String, String)]) -> Result<String, String> {
let bad = |text: &str| {
text.chars()
.any(|c| matches!(c, '%' | '"' | '^' | '!' | '\n' | '\r'))
Expand All @@ -215,16 +228,24 @@ fn windows_shim(binary: &str, env: &[(String, String)]) -> Result<String, String
return Err("unsafe character in launcher path".to_owned());
}
out.push_str("set \"PATH=\"\r\n");
out.push_str(&format!("\"{binary}\" %*\r\n"));
out.push_str(&format!("\"{binary}\""));
for arg in args {
// A space would split the argument; `bad` covers the rest of cmd.exe's syntax.
if bad(arg) || arg.is_empty() || arg.contains([' ', '\t']) {
return Err(format!("unsafe shim argument {arg:?}"));
}
out.push_str(&format!(" {arg}"));
}
out.push_str(" %*\r\n");
Ok(out)
}

fn write_path_shim(
dir: &Path,
name: &str,
binary: &Path,
tool: &PathTool,
env: &[(OsString, OsString)],
) -> Result<(), String> {
let name = tool.name.as_str();
let env: Vec<(String, String)> = env
.iter()
.map(|(key, value)| {
Expand All @@ -234,13 +255,14 @@ fn write_path_shim(
)
})
.collect();
let binary = binary.to_string_lossy();
let binary = tool.binary.to_string_lossy();
if cfg!(windows) {
let body = windows_shim(&binary, &env)?;
let body = windows_shim(&binary, &tool.args, &env)?;
std::fs::write(dir.join(format!("{name}.cmd")), body).map_err(|err| err.to_string())
} else {
let path = dir.join(name);
std::fs::write(&path, unix_shim(&binary, &env)).map_err(|err| err.to_string())?;
std::fs::write(&path, unix_shim(&binary, &tool.args, &env))
.map_err(|err| err.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
Expand Down Expand Up @@ -543,10 +565,10 @@ fn base_env(
let dir = scratch.root().join(PATH_TOOLS_DIR_REL);
std::fs::create_dir_all(&dir)
.map_err(|err| execution(tool_id, format!("path tools dir: {err}")))?;
for (name, binary) in &tool.path_tools {
let shim_env = launcher_env(name, binary);
write_path_shim(&dir, name, binary, &shim_env)
.map_err(|err| execution(tool_id, format!("path tool {name}: {err}")))?;
for helper in &tool.path_tools {
let shim_env = launcher_env(&helper.name, &helper.binary);
write_path_shim(&dir, helper, &shim_env)
.map_err(|err| execution(tool_id, format!("path tool {}: {err}", helper.name)))?;
}
env.retain(|(key, _)| !key.to_string_lossy().eq_ignore_ascii_case("PATH"));
env.push((OsString::from("PATH"), dir.into_os_string()));
Expand Down Expand Up @@ -601,7 +623,7 @@ fn tool_specific_env(
|| tool
.path_tools
.iter()
.any(|(name, binary)| name == "bicep" && bicep_argv0 == Some(binary.as_path()));
.any(|helper| helper.name == "bicep" && bicep_argv0 == Some(helper.binary.as_path()));
if runs_bicep {
let home = scratch.root().join(BICEP_HOME_REL);
std::fs::create_dir_all(&home)
Expand Down Expand Up @@ -1041,6 +1063,7 @@ mod tests {
fn unix_shims_export_env_then_exec_the_quoted_launcher() {
let body = super::unix_shim(
"/w/it's/bin",
&[],
&[("RUNFILES_MANIFEST_FILE".to_owned(), "/w/m".to_owned())],
);
assert_eq!(
Expand All @@ -1049,16 +1072,40 @@ mod tests {
);
}

#[test]
fn unix_shims_pass_quoted_leading_args_before_the_callers() {
let body = super::unix_shim("/w/dx", &["buf_diff".to_owned(), "a b".to_owned()], &[]);
assert_eq!(
body,
"#!/bin/sh\nunset PATH\nexec '/w/dx' 'buf_diff' 'a b' \"$@\"\n"
);
}

#[test]
fn windows_shims_use_crlf_and_refuse_cmd_metacharacters() {
let body = super::windows_shim("C:\\t\\bin.bat", &[("K".to_owned(), "V".to_owned())])
let body = super::windows_shim("C:\\t\\bin.bat", &[], &[("K".to_owned(), "V".to_owned())])
.expect("shim");
assert_eq!(
body,
"@echo off\r\nset \"K=V\"\r\nset \"PATH=\"\r\n\"C:\\t\\bin.bat\" %*\r\n"
);
for bad in ["a%b", "a\"b", "a^b", "a!b", "a\nb"] {
assert!(super::windows_shim(bad, &[]).is_err(), "{bad}");
assert!(super::windows_shim(bad, &[], &[]).is_err(), "{bad}");
}
}

#[test]
fn windows_shims_pass_leading_args_and_refuse_ones_cmd_would_split() {
let body = super::windows_shim("C:\\dx.exe", &["buf_diff".to_owned()], &[]).expect("shim");
assert_eq!(
body,
"@echo off\r\nset \"PATH=\"\r\n\"C:\\dx.exe\" buf_diff %*\r\n"
);
for bad in ["a b", "", "a%b", "a\tb"] {
assert!(
super::windows_shim("C:\\dx.exe", &[bad.to_owned()], &[]).is_err(),
"{bad:?}"
);
}
}

Expand All @@ -1070,18 +1117,24 @@ mod tests {
let launcher = dir.path().join("fake");
std::fs::write(&launcher, "#!/bin/sh\necho \"$1:$K\"\n").expect("write");
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).expect("mode");
super::write_path_shim(
dir.path(),
"rst2html",
&launcher,
&[(OsString::from("K"), OsString::from("v"))],
)
.expect("shim");
let helper = |name: &str, args: &[&str]| super::PathTool {
name: name.to_owned(),
binary: launcher.clone(),
args: args.iter().map(|arg| (*arg).to_owned()).collect(),
};
let env = [(OsString::from("K"), OsString::from("v"))];
super::write_path_shim(dir.path(), &helper("rst2html", &[]), &env).expect("shim");
let out = std::process::Command::new(dir.path().join("rst2html"))
.arg("arg")
.output()
.expect("run");
assert_eq!(String::from_utf8_lossy(&out.stdout), "arg:v\n");
super::write_path_shim(dir.path(), &helper("diff", &["buf_diff"]), &env).expect("shim");
let out = std::process::Command::new(dir.path().join("diff"))
.arg("arg")
.output()
.expect("run");
assert_eq!(String::from_utf8_lossy(&out.stdout), "buf_diff:v\n");
}

#[cfg(unix)]
Expand All @@ -1092,7 +1145,12 @@ mod tests {
let launcher = dir.path().join("fake");
std::fs::write(&launcher, "#!/usr/bin/env sh\necho ok\n").expect("write");
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).expect("mode");
super::write_path_shim(dir.path(), "tool", &launcher, &[]).expect("shim");
let helper = super::PathTool {
name: "tool".to_owned(),
binary: launcher,
args: Vec::new(),
};
super::write_path_shim(dir.path(), &helper, &[]).expect("shim");
let body = std::fs::read_to_string(dir.path().join("tool")).expect("read");
assert!(body.contains("unset PATH\n"), "{body}");
let out = std::process::Command::new(dir.path().join("tool"))
Expand Down
Loading
Loading