use crate::{
preflight::{self, verified_bytes},
receipt,
};
use anyhow::{Context, Result, ensure};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use clap::Subcommand;
use flate2::read::MultiGzDecoder;
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
cmp::Reverse,
collections::{BTreeMap, BTreeSet},
env, fs,
io::{BufReader, Seek, Write},
os::unix::fs::PermissionsExt,
path::{Component, Path, PathBuf},
process::{Command, Stdio},
};
#[derive(Subcommand)]
pub(crate) enum ProfileCommand {
Symbolize {
#[arg(long)]
artifact: PathBuf,
#[arg(long)]
trace: PathBuf,
#[arg(long, default_value = "llvm-symbolizer")]
llvm_symbolizer: PathBuf,
#[arg(long, default_value_t = 200)]
top_blocks: usize,
#[arg(long)]
output: PathBuf,
},
}
impl ProfileCommand {
pub(crate) fn run(self) -> Result<()> {
match self {
Self::Symbolize {
artifact,
trace,
llvm_symbolizer,
top_blocks,
output,
} => {
ensure!(top_blocks > 0, "--top-blocks must be positive");
ensure!(
!output.try_exists()?,
"choose a fresh profile report path: {}",
output.display()
);
let directory = output
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut staging = tempfile::NamedTempFile::new_in(directory)?;
let evidence = symbolize(&artifact, &trace, &llvm_symbolizer, top_blocks)?;
serde_json::to_writer_pretty(&mut staging, &evidence)?;
staging.write_all(b"\n")?;
staging
.persist_noclobber(&output)
.with_context(|| format!("write new profile report {}", output.display()))?;
Ok(())
}
}
}
}
fn document<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T> {
if bytes.starts_with(&[0x1f, 0x8b]) {
Ok(serde_json::from_reader(BufReader::new(
MultiGzDecoder::new(bytes),
))?)
} else {
Ok(serde_json::from_slice(bytes)?)
}
}
fn normalized(path: &Path) -> PathBuf {
let mut result = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => (),
Component::ParentDir if result.file_name().is_some_and(|last| last != "..") => {
result.pop();
}
Component::ParentDir if result.has_root() => (),
_ => result.push(component),
}
}
result
}
fn executable(command: &Path) -> Option<PathBuf> {
let is_executable = |path: &Path| {
path.metadata()
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
};
if command.is_absolute() || command.parent().is_some_and(|p| !p.as_os_str().is_empty()) {
return is_executable(command).then(|| command.to_path_buf());
}
env::split_paths(&env::var_os("PATH")?)
.map(|dir| dir.join(command))
.find(|path| is_executable(path))
}
fn trusted_executable(command: &Path, artifact_directory: &Path) -> Result<PathBuf> {
let path = executable(command)
.with_context(|| format!("executable not found: {}", command.display()))?;
let absolute = std::path::absolute(path)?;
let resolved = absolute.canonicalize()?;
let parent = absolute
.parent()
.context("missing executable directory")?
.canonicalize()?;
ensure!(
!normalized(&absolute).starts_with(artifact_directory)
&& !parent.starts_with(artifact_directory)
&& !resolved.starts_with(artifact_directory),
"select a trusted executable outside the artifact directory: {}",
command.display()
);
Ok(resolved)
}
fn output(command: &mut Command, input: Option<&[u8]>) -> Result<String> {
if let Some(input) = input {
let mut file = tempfile::tempfile()?;
file.write_all(input)?;
file.rewind()?;
command.stdin(Stdio::from(file));
}
let result = command
.output()
.with_context(|| format!("run {}", command.get_program().to_string_lossy()))?;
ensure!(
result.status.success(),
"{} exited with {}: {}",
command.get_program().to_string_lossy(),
result.status,
String::from_utf8_lossy(&result.stderr).trim()
);
Ok(String::from_utf8(result.stdout)?)
}
fn tool_record(tool: &receipt::FileRecord) -> Result<Value> {
let version = output(Command::new(&tool.path).arg("--version"), None)?;
ensure!(
receipt::record(&tool.path)? == *tool,
"profiling tool changed during analysis: {}",
tool.path.display()
);
Ok(json!({"path": tool.path, "version": version, "sha256": tool.sha256}))
}
#[derive(Deserialize)]
struct SourceArchive {
format: String,
installed_sha256: String,
files: Vec<ArchivedSource>,
}
#[derive(Deserialize)]
struct ArchivedSource {
path: PathBuf,
sha256: String,
bytes: u64,
contents_base64: String,
}
struct Source {
sha256: String,
text: String,
}
fn sources(
bundle: &preflight::CompletedOutputs,
installed_hash: &str,
) -> Result<BTreeMap<PathBuf, Source>> {
let Some(archive) = bundle.optional_output("debug-sources.json.gz") else {
return Ok(BTreeMap::new());
};
let archive: SourceArchive = document(&verified_bytes(archive)?)?;
ensure!(
archive.format == "cdk-rsx-debug-sources-v1",
"unsupported debug source archive"
);
ensure!(
archive.installed_sha256 == installed_hash,
"source bundle module hash mismatch"
);
let mut result = BTreeMap::<_, Source>::new();
for row in archive.files {
let contents = STANDARD
.decode(row.contents_base64)
.with_context(|| format!("decode archived source {}", row.path.display()))?;
ensure!(
contents.len() as u64 == row.bytes && receipt::hash_bytes(&contents) == row.sha256,
"source hash mismatch: {}",
row.path.display()
);
let path = normalized(&row.path);
if let Some(previous) = result.get(&path) {
ensure!(
previous.sha256 == row.sha256,
"ambiguous source path: {}",
path.display()
);
} else {
result.insert(
path,
Source {
sha256: row.sha256,
text: String::from_utf8_lossy(&contents).into_owned(),
},
);
}
}
Ok(result)
}
fn source_frame(
frame: &Value,
sources: &BTreeMap<PathBuf, Source>,
compiler_commit: Option<&str>,
) -> Value {
let path = normalized(Path::new(frame["FileName"].as_str().unwrap_or_default()));
let path = compiler_commit
.and_then(|commit| path.strip_prefix(Path::new("/rustc").join(commit)).ok())
.map_or_else(
|| path.clone(),
|relative| Path::new("/rust-src").join(relative),
);
let line = frame["Line"].as_u64().filter(|line| *line > 0);
let source = line.and_then(|_| sources.get(&path));
let mut result = json!({
"function": frame["FunctionName"].as_str().filter(|name| !name.is_empty()),
"file": line.map(|_| &path), "line": line, "column": frame["Column"],
"discriminator": frame["Discriminator"], "source_sha256": source.map(|source| &source.sha256),
});
if let Some(source) = source
&& let Some(index) = line.and_then(|line| usize::try_from(line - 1).ok())
&& let Some(text) = source.text.lines().nth(index)
{
result["source"] = json!(text);
}
result
}
fn unsigned(value: &Value, field: &str) -> Result<u128> {
if let Some(value) = value.as_u64() {
return Ok(value.into());
}
value
.as_str()
.context("expected an unsigned count or decimal string")?
.parse()
.with_context(|| format!("invalid {field}"))
}
fn unsigned64(value: &Value, field: &str) -> Result<u64> {
u64::try_from(unsigned(value, field)?).with_context(|| format!("out-of-range {field}"))
}
fn array<'a>(value: &'a Value, field: &str) -> Result<&'a [Value]> {
value[field]
.as_array()
.map(Vec::as_slice)
.with_context(|| format!("expected {field} array"))
}
fn add(total: &mut u128, amount: u128) -> Result<()> {
*total = total
.checked_add(amount)
.context("profile count exceeds 128 bits")?;
Ok(())
}
struct Body {
length: u64,
raw_start: Option<u64>,
}
type Bodies = BTreeMap<u64, Body>;
fn bodies(origin: &Value) -> Result<Bodies> {
array(origin, "functions")?
.iter()
.map(|row| {
let start = unsigned64(&row["installed_body_start"], "installed_body_start")?;
let end = unsigned64(&row["installed_body_end"], "installed_body_end")?;
let raw_start = (row["kind"] == "rust")
.then(|| unsigned64(&row["raw_code_relative_start"], "raw_code_relative_start"))
.transpose()?;
Ok((
unsigned64(&row["function_index"], "function_index")?,
Body {
length: end.checked_sub(start).context("reversed body offsets")?,
raw_start,
},
))
})
.collect()
}
fn pc(bodies: &Bodies, function: u64, offset: u64, allow_end: bool) -> Result<Option<u64>> {
let body = bodies
.get(&function)
.with_context(|| format!("unknown installed function index {function}"))?;
ensure!(
offset < body.length || (allow_end && offset == body.length),
"body offset outside installed function {function}: {offset}"
);
if offset == body.length {
return Ok(None);
}
body.raw_start
.map(|start| start.checked_add(offset).context("raw PC overflow"))
.transpose()
}
#[derive(Default)]
struct Charges {
first_seen: usize,
instructions: u128,
count: u128,
fields: Value,
}
#[derive(Default)]
struct Costs {
first_seen: usize,
static_instructions: u128,
dynamic_instructions: u128,
names: BTreeSet<String>,
}
#[derive(Default)]
struct Aggregation {
executions: Vec<Value>,
blocks: BTreeMap<(u64, u64, u64), Charges>,
sites: BTreeMap<(u64, u64, String), Charges>,
functions: BTreeMap<u64, Costs>,
}
impl Aggregation {
fn function_cost(&mut self, index: u64) -> &mut Costs {
let first_seen = self.functions.len();
self.functions.entry(index).or_insert_with(|| Costs {
first_seen,
..Costs::default()
})
}
}
fn aggregate(trace: &Value, installed_hash: &str, bodies: &Bodies) -> Result<Aggregation> {
let mut result = Aggregation::default();
for execution in array(trace, "executions")? {
let Some(profile) = execution["instruction_profile"]
.as_object()
.filter(|p| !p.is_empty())
else {
continue;
};
ensure!(
execution["module_hash_kind"] == "installed_uncompressed_sha256",
"trace module hash does not identify installed uncompressed bytes"
);
ensure!(
execution["module_hash"] == installed_hash,
"trace module hash mismatch at execution {}",
execution["sequence_number"]
);
let mut static_total = 0;
let mut dynamic_total = 0;
let list = |field: &str| {
profile
.get(field)
.and_then(Value::as_array)
.with_context(|| format!("expected {field} array"))
};
for block in list("blocks")? {
let function = unsigned64(&block["function_index"], "function_index")?;
let start = unsigned64(&block["body_offset"], "body_offset")?;
let end = unsigned64(&block["end_body_offset"], "end_body_offset")?;
ensure!(end >= start, "reversed block offsets");
pc(bodies, function, start, end == start)?;
if end > start {
pc(bodies, function, end - 1, false)?;
}
let first_seen = result.blocks.len();
let row = result.blocks.entry((function, start, end)).or_insert_with(|| Charges {
first_seen,
fields: json!({"function_index": function, "body_offset": start.to_string(), "end_body_offset": end.to_string(),
"weight": block["weight"], "entry_weight": block["entry_weight"]}), ..Charges::default()
});
let amount = unsigned(&block["instructions"], "instructions")?;
add(&mut row.instructions, amount)?;
add(&mut row.count, unsigned(&block["hits"], "hits")?)?;
add(
&mut result.function_cost(function).static_instructions,
amount,
)?;
add(&mut static_total, amount)?;
}
for charge in list("dynamic_charges")? {
let amount = unsigned(&charge["instructions"], "instructions")?;
add(&mut dynamic_total, amount)?;
if charge["function_index"].is_null() {
continue;
}
let function = unsigned64(&charge["function_index"], "function_index")?;
add(
&mut result.function_cost(function).dynamic_instructions,
amount,
)?;
if charge["body_offset"].is_null() {
continue;
}
let offset = unsigned64(&charge["body_offset"], "body_offset")?;
pc(bodies, function, offset, false)?;
let category = charge["category"]
.as_str()
.context("missing charge category")?;
let first_seen = result.sites.len();
let row = result.sites.entry((function, offset, category.to_owned())).or_insert_with(|| Charges {
first_seen,
fields: json!({"function_index": function, "body_offset": charge["body_offset"], "category": category}),
..Charges::default()
});
add(&mut row.instructions, amount)?;
add(&mut row.count, unsigned(&charge["events"], "events")?)?;
}
result.executions.push(json!({
"sequence_number": execution["sequence_number"], "api_type": execution["api_type"],
"function": execution["function"], "instructions": execution["instructions"], "outcome": execution["outcome"],
"detail_truncated": execution["detail_truncated"], "attempt": execution["attempt"], "disposition": execution["disposition"],
"ledger": profile.get("ledger"), "profile_truncated": profile.get("truncated"), "limitations": profile.get("limitations"),
"recorded_static_instructions": static_total.to_string(), "recorded_dynamic_instructions": dynamic_total.to_string(),
}));
}
ensure!(
!result.executions.is_empty(),
"trace contains no instruction profiles"
);
Ok(result)
}
fn dwarf_frames(
raw: &Path,
points: &BTreeSet<u64>,
symbolizer: &Path,
sources: &BTreeMap<PathBuf, Source>,
compiler_commit: Option<&str>,
) -> Result<BTreeMap<u64, Vec<Value>>> {
if points.is_empty() {
return Ok(BTreeMap::new());
}
let input: String = points.iter().map(|pc| format!("0x{pc:x}\n")).collect();
let rows = output(
Command::new(symbolizer)
.arg(format!("--obj={}", raw.display()))
.args([
"--output-style=JSON",
"--inlines",
"--functions=short",
"--demangle",
"--no-debuginfod",
]),
Some(input.as_bytes()),
)?;
let rows: Vec<_> = rows
.lines()
.filter(|line| !line.trim().is_empty())
.collect();
ensure!(
rows.len() == points.len(),
"symbolizer returned an unexpected address count"
);
points
.iter()
.zip(rows)
.map(|(&pc, line)| {
let row: Value = serde_json::from_str(line)?;
ensure!(row.get("Error").is_none(), "symbolizer error: {row}");
let address = row["Address"]
.as_str()
.context("missing symbolizer address")?;
let decoded = if let Some(hex) = address.strip_prefix("0x") {
u64::from_str_radix(hex, 16)?
} else {
address.parse()?
};
ensure!(decoded == pc, "symbolizer address mismatch");
let frames = row["Symbol"]
.as_array()
.into_iter()
.flatten()
.map(|frame| source_frame(frame, sources, compiler_commit))
.collect();
Ok((pc, frames))
})
.collect()
}
fn physical_names(raw: &Path, artifact_directory: &Path) -> Result<(BTreeMap<u64, String>, Value)> {
let reader = Path::new("llvm-readobj");
if executable(reader).is_none() {
return Ok((BTreeMap::new(), Value::Null));
}
let mut demangler = Path::new("llvm-cxxfilt");
let mut format = None;
let gnu = Path::new("c++filt");
if executable(gnu).is_some() {
let candidate = trusted_executable(gnu, artifact_directory)?;
if output(Command::new(candidate).arg("--version"), None)
.is_ok_and(|version| version.starts_with("GNU c++filt"))
{
demangler = gnu;
format = Some("--format=rust");
}
}
if executable(demangler).is_none() {
return Ok((BTreeMap::new(), Value::Null));
}
let reader = receipt::record(&trusted_executable(reader, artifact_directory)?)?;
let demangler = receipt::record(&trusted_executable(demangler, artifact_directory)?)?;
let symbols = output(Command::new(&reader.path).arg("--symbols").arg(raw), None)?;
let mut indices = Vec::new();
let mut names = String::new();
for symbol in symbols.split(" Symbol {").skip(1) {
if !symbol
.lines()
.any(|line| line.starts_with(" Type: FUNCTION"))
{
continue;
}
let name = symbol
.lines()
.find_map(|line| line.strip_prefix(" Name: "));
let index = symbol
.lines()
.find_map(|line| line.strip_prefix(" ElementIndex: 0x"));
if let (Some(name), Some(index)) = (name, index) {
indices.push(u64::from_str_radix(index, 16)?);
names.push_str(name);
names.push('\n');
}
}
let demangled = output(
Command::new(&demangler.path).args(format),
Some(names.as_bytes()),
)?;
ensure!(
indices.len() == demangled.lines().count(),
"physical function demangler count mismatch"
);
Ok((
indices
.into_iter()
.zip(demangled.lines().map(str::to_owned))
.collect(),
json!([tool_record(&reader)?, tool_record(&demangler)?]),
))
}
fn annotate(
row: &mut Value,
offsets: &[(Option<u64>, &str)],
frames: &BTreeMap<u64, Vec<Value>>,
costs: &mut Costs,
) {
row["source_points"] = json!(offsets.iter().filter_map(|(pc, boundary)| {
let pc = (*pc)?;
let found = &frames[&pc];
if let Some(name) = found.last().and_then(|frame| frame["function"].as_str()) {
costs.names.insert(name.to_owned());
}
Some(json!({"boundary": boundary, "raw_dwarf_pc": pc.to_string(), "inline_frames": found}))
}).collect::<Vec<_>>());
}
fn symbolize(
artifact: &Path,
trace: &Path,
llvm_symbolizer: &Path,
top_blocks: usize,
) -> Result<Value> {
let bundle = preflight::completed_outputs(artifact, true)?;
let directory = bundle
.manifest_record
.path
.parent()
.context("missing artifact directory")?;
ensure!(
bundle.manifest["canonicalBuild"]["debug_artifacts"] == true,
"artifact has no optimized DWARF bundle"
);
let analyzer = receipt::record(&trusted_executable(&env::current_exe()?, directory)?)?;
let raw = bundle.output("raw.wasm")?;
let installed = bundle.output("wasm")?;
let raw_bytes = verified_bytes(raw)?;
let installed_bytes = verified_bytes(installed)?;
cdk_rsx_wasm::origin::verify_debug_strip(
&raw_bytes,
&verified_bytes(bundle.output("stripped.raw.wasm")?)?,
)?;
let recorded_origin: Value = document(&verified_bytes(bundle.output("origin.json")?)?)?;
let origin = cdk_rsx_wasm::origin::sdk_origin_map(&raw_bytes, &installed_bytes)?;
ensure!(
recorded_origin == origin,
"SDK origin map differs from exact function bodies"
);
ensure!(
bundle.manifest["wasmSha256"] == installed.sha256,
"installed module hash mismatch"
);
let trace_bytes = fs::read(trace).with_context(|| format!("read trace {}", trace.display()))?;
let trace: Value = document(&trace_bytes)?;
let bodies = bodies(&origin)?;
let Aggregation {
executions,
blocks,
sites,
mut functions,
} = aggregate(&trace, &installed.sha256, &bodies)?;
let (recorded_blocks, recorded_sites) = (blocks.len(), sites.len());
let mut blocks: Vec<_> = blocks.into_iter().collect();
let mut sites: Vec<_> = sites.into_iter().collect();
blocks.sort_by_key(|(_, row)| (Reverse(row.instructions), row.first_seen));
sites.sort_by_key(|(_, row)| (Reverse(row.instructions), row.first_seen));
blocks.truncate(top_blocks);
sites.truncate(top_blocks);
let block_points: Vec<_> = blocks
.iter()
.map(|&((function, start, end), _)| {
if start == end {
return Ok([None, None]);
}
Ok([
pc(&bodies, function, start, false)?,
pc(&bodies, function, end - 1, false)?,
])
})
.collect::<Result<_>>()?;
let site_points: Vec<_> = sites
.iter()
.map(|((function, offset, _), _)| pc(&bodies, *function, *offset, false))
.collect::<Result<_>>()?;
let points = block_points
.iter()
.flatten()
.chain(&site_points)
.flatten()
.copied()
.collect();
let sources = sources(&bundle, &installed.sha256)?;
let symbolizer = receipt::record(&trusted_executable(llvm_symbolizer, directory)?)?;
let compiler_commit = bundle.manifest["compiler"]
.as_str()
.unwrap_or_default()
.lines()
.find_map(|line| line.strip_prefix("commit-hash: "));
let mut input = tempfile::NamedTempFile::with_suffix(".wasm")?;
input.write_all(&raw_bytes)?;
input.flush()?;
let frames = dwarf_frames(
input.path(),
&points,
&symbolizer.path,
&sources,
compiler_commit,
)?;
let (physical_names, name_tools) = physical_names(input.path(), directory)?;
let blocks: Vec<_> = blocks
.into_iter()
.zip(block_points)
.map(|(((function, _, _), mut row), [start, end])| {
annotate(
&mut row.fields,
&[(start, "start"), (end, "last_byte")],
&frames,
functions.get_mut(&function).unwrap(),
);
row.fields["instructions"] = json!(row.instructions.to_string());
row.fields["hits"] = json!(row.count.to_string());
row.fields
})
.collect();
let sites: Vec<_> = sites
.into_iter()
.zip(site_points)
.map(|(((function, _, _), mut row), point)| {
annotate(
&mut row.fields,
&[(point, "original-operation")],
&frames,
functions.get_mut(&function).unwrap(),
);
row.fields["instructions"] = json!(row.instructions.to_string());
row.fields["events"] = json!(row.count.to_string());
row.fields
})
.collect();
let mut function_rows: Vec<_> = functions.into_iter().map(|(index, costs)| {
let total = costs.static_instructions.checked_add(costs.dynamic_instructions).context("profile count exceeds 128 bits")?;
Ok((Reverse(total), costs.first_seen, json!({"function_index": index, "names": costs.names, "physical_name": physical_names.get(&index),
"static_instructions": costs.static_instructions.to_string(), "dynamic_instructions": costs.dynamic_instructions.to_string(),
"attributed_instructions": total.to_string()})))
}).collect::<Result<_>>()?;
function_rows.sort_by_key(|(total, first_seen, _)| (*total, *first_seen));
let all_points: Vec<_> = blocks
.iter()
.chain(&sites)
.flat_map(|row| row["source_points"].as_array().into_iter().flatten())
.collect();
let coverage = |field: &str| {
all_points
.iter()
.filter(|point| {
point["inline_frames"]
.as_array()
.into_iter()
.flatten()
.any(|frame| !frame[field].is_null())
})
.count()
};
ensure!(
receipt::record(&analyzer.path)? == analyzer,
"CLI executable changed during analysis"
);
Ok(json!({
"format": "cdk-rsx-symbolized-charge-blocks-v1", "installed_sha256": installed.sha256,
"raw_sha256": raw.sha256, "server_generation": trace["server_generation"], "server_binary_hash": trace["server_binary_hash"],
"trace_sha256": receipt::hash_bytes(&trace_bytes), "trace_truncated": trace["truncated"], "analyzer_sha256": analyzer.sha256,
"origin_tool": {"path": analyzer.path, "sha256": analyzer.sha256}, "physical_name_tools": name_tools,
"dwarf_function_names": "short names; physical_name uses the exact Wasm ElementIndex", "symbolizer": tool_record(&symbolizer)?,
"source_attribution": "Block boundary locations only. Prepaid block charges are not assigned to individual source lines; inline frames are compiler frames, not dynamic caller stacks. API/page/unknown charges remain in the complete execution ledgers.",
"symbolized_blocks": blocks.len(), "recorded_blocks": recorded_blocks,
"source_coverage": {"queried_points": all_points.len(), "points_with_source_line": coverage("line"),
"points_with_archived_source": coverage("source_sha256")},
"executions": executions, "functions": function_rows.into_iter().map(|(_, _, row)| row).collect::<Vec<_>>(),
"blocks": blocks, "dynamic_sites": sites, "recorded_dynamic_sites": recorded_sites,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounds_and_trace_hash_precede_attribution() {
let bodies = BTreeMap::from([(
7,
Body {
length: 10,
raw_start: Some(42),
},
)]);
assert_eq!(pc(&bodies, 7, 3, false).unwrap(), Some(45));
assert_eq!(pc(&bodies, 7, 10, true).unwrap(), None);
assert!(pc(&bodies, 7, 10, false).is_err());
assert!(pc(&bodies, 8, 0, false).is_err());
let trace = json!({"executions": [{"module_hash": "wrong", "module_hash_kind": "installed_uncompressed_sha256", "instruction_profile": {"version": 1}}]});
assert!(
aggregate(&trace, "installed", &bodies)
.err()
.unwrap()
.to_string()
.contains("trace module hash mismatch")
);
}
#[test]
fn compiler_source_remap_only_applies_to_the_exact_commit() {
let sources = BTreeMap::from([(
PathBuf::from("/rust-src/library/foo.rs"),
Source {
sha256: "pinned".into(),
text: "source line\n".into(),
},
)]);
let frame = json!({"FileName": "/rustc/abc/library/foo.rs", "Line": 1, "FunctionName": "test", "Column": 4});
assert_eq!(
source_frame(&frame, &sources, Some("abc"))["source"],
"source line"
);
assert!(source_frame(&frame, &sources, Some("def"))["source_sha256"].is_null());
let mut frame = frame;
frame["Line"] = 0.into();
let missing = source_frame(&frame, &sources, Some("abc"));
assert!(missing["line"].is_null() && missing["source_sha256"].is_null());
}
#[test]
fn archive_entry_hash_must_match_even_in_a_verified_bundle() {
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path();
let archive = directory.join("app.debug-sources.json.gz");
receipt::write_gzip_json(
&archive,
&json!({
"format": "cdk-rsx-debug-sources-v1",
"installed_sha256": "installed",
"files": [{
"path": "/app/src/lib.rs",
"sha256": receipt::hash_bytes(b"right"),
"bytes": 5,
"contents_base64": STANDARD.encode(b"wrong"),
}],
}),
)
.unwrap();
let archive_record = receipt::record(&archive).unwrap();
let manifest = directory.join("app.manifest.json");
receipt::write_json(
&manifest,
&json!({
"format": receipt::FORMAT,
"implementation": "cdk-rsx",
"sourceUnchangedDuringBuild": true,
"canonicalBuild": {"source_unchanged_during_build": true, "runtime": "typed-root"},
"outputs": [archive_record],
}),
)
.unwrap();
let manifest_record = receipt::record(&manifest).unwrap();
fs::write(
directory.join("app.SHA256SUMS"),
format!(
"{} app.debug-sources.json.gz\n{} app.manifest.json\n",
archive_record.sha256, manifest_record.sha256
),
)
.unwrap();
let bundle = preflight::completed_outputs(&manifest, false).unwrap();
let error = sources(&bundle, "installed").err().unwrap();
assert!(error.to_string().contains("source hash mismatch"));
}
#[test]
fn dwarf_uses_short_names_and_matches_the_requested_address() {
let temporary = tempfile::tempdir().unwrap();
let tool = temporary.path().join("llvm-symbolizer");
fs::write(
&tool,
r#"#!/bin/sh
case " $* " in
*" --functions=short "*) ;;
*) exit 1 ;;
esac
read -r address
printf '{"Address":"%s","Symbol":[{"FunctionName":"exact_function","Line":0}]}\n' "$address"
"#,
)
.unwrap();
fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap();
let frames = dwarf_frames(
Path::new("unused.wasm"),
&BTreeSet::from([32]),
&tool,
&BTreeMap::new(),
None,
)
.unwrap();
assert_eq!(frames[&32][0]["function"], "exact_function");
}
#[test]
fn rejects_artifact_executable_even_via_alias() {
let temporary = tempfile::tempdir().unwrap();
let directory = temporary.path().join("artifacts");
fs::create_dir(&directory).unwrap();
let tool = directory.join("tool");
fs::File::create(&tool).unwrap();
fs::set_permissions(&tool, fs::Permissions::from_mode(0o700)).unwrap();
let alias = temporary.path().join("alias");
std::os::unix::fs::symlink(&tool, &alias).unwrap();
for path in [tool, alias] {
assert!(trusted_executable(&path, &directory).is_err());
}
}
}