Skip to main content

cargo/compiler/
trim_paths.rs

1//! Path prefix remapping for [RFC 3127] `trim-paths`.
2//!
3//! [RFC 3127]: https://rust-lang.github.io/rfcs/3127-trim-paths.html
4
5use std::collections::BTreeMap;
6use std::collections::btree_map::Entry;
7use std::ffi::OsString;
8use std::io::Write;
9use std::path::Path;
10use std::path::PathBuf;
11
12use cargo_util::ProcessBuilder;
13use cargo_util_schemas::manifest::TomlTrimPaths;
14use serde::Serialize;
15use tracing::debug;
16
17use super::BuildRunner;
18use super::Unit;
19use crate::util::errors::CargoResult;
20use crate::util::hex;
21use crate::util::path_args;
22use cargo_util::collections::HashSet;
23
24/// The current version of the unremap file.
25const CURRENT_UNREMAP_VERSION: u8 = 1;
26
27/// Filename suffix of the unremap file.
28pub(crate) const UNREMAP_SUFFIX: &str = ".trim-paths.json";
29
30/// This is an internal contract with rustc bootstrap,
31/// which needs workspace sources remapped to `/rust{c,-dev}/<sha>`.
32///
33/// See <https://github.com/rust-lang/cargo/issues/17309>.
34pub(crate) const WS_REMAP_ENV: &str = "__CARGO_RUSTC_BOOTSTRAP_WS_REMAP";
35
36/// A single `<from>=<to>` remap rule.
37type RemapPair = (PathBuf, String);
38
39/// Like [`trim_paths_args`] but for rustdoc invocations.
40pub(crate) fn trim_paths_args_rustdoc(
41    cmd: &mut ProcessBuilder,
42    build_runner: &BuildRunner<'_, '_>,
43    unit: &Unit,
44    trim_paths: &TomlTrimPaths,
45) -> CargoResult<()> {
46    // rustdoc supports diagnostics trimming only.
47    if !matches!(trim_paths, TomlTrimPaths::All) {
48        return Ok(());
49    }
50
51    for pair in trim_paths_remap(build_runner, unit) {
52        let mut arg = OsString::from("--remap-path-prefix=");
53        arg.push(pair);
54        cmd.arg(arg);
55    }
56
57    Ok(())
58}
59
60/// Generates the `--remap-path-scope` and `--remap-path-prefix` for [RFC 3127].
61/// See also the [`trim-paths`] profile option.
62///
63/// [RFC 3127]: https://rust-lang.github.io/rfcs/3127-trim-paths.html
64/// [`trim-paths`]: https://doc.rust-lang.org/cargo/reference/profiles.html#trim-paths
65pub(crate) fn trim_paths_args(
66    cmd: &mut ProcessBuilder,
67    build_runner: &BuildRunner<'_, '_>,
68    unit: &Unit,
69    trim_paths: &TomlTrimPaths,
70) -> CargoResult<()> {
71    if trim_paths.is_none() {
72        return Ok(());
73    }
74
75    cmd.arg(format!("--remap-path-scope={trim_paths}"));
76
77    for pair in trim_paths_remap(build_runner, unit) {
78        let mut arg = OsString::from("--remap-path-prefix=");
79        arg.push(pair);
80        cmd.arg(arg);
81    }
82
83    Ok(())
84}
85
86/// Computes the `<from>=<to>` path remap pairs for [RFC 3127] trim-paths.
87///
88/// Order of `--remap-path-prefix` flags is important for `-Zbuild-std`.
89/// We want to show `/rustc/<hash>/library/std` instead of `std-0.0.0`.
90///
91/// | Category     | From                                             | To                                 |
92/// |--------------|--------------------------------------------------|------------------------------------|
93/// | Sysroot      | `<sysroot>/lib/rustlib/src/rust`                 | `/rustc/<commit-hash>`             |
94/// | Registry dep | `$CARGO_HOME/registry/src/<registry-dir>`        | `/cargo/registry/<registry-id>`    |
95/// | Git dep      | `$CARGO_HOME/git/checkouts/<repo-dir>/<rev-dir>` | `/cargo/git/<git-source-id>/<rev>` |
96/// | Workspace    | `<workspace-root>`                               | `.` (workspace-relative)           |
97/// | Path dep†    | `<pkg-root>`                                     | `/cargo/deps/<name>-<version>`     |
98/// | Vendored     | `<pkg-root>` (by file location)                  | workspace or path rules above      |
99/// | Build dir    | `<build-dir>`                                    | `/cargo/build-dir`                 |
100///
101/// **†**: path dependencies outside the workspace and other uncategorized dependencies.
102///
103/// [RFC 3127]: https://rust-lang.github.io/rfcs/3127-trim-paths.html
104pub(crate) fn trim_paths_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<OsString> {
105    remap_pairs(build_runner, unit).map(join_remap).collect()
106}
107
108/// Remaps `path` the same way rustc does with [`trim_paths_remap`] rules,
109/// like the last takes precedence.
110///
111/// `None` if no rule matches.
112pub(crate) fn remap_path(
113    build_runner: &BuildRunner<'_, '_>,
114    unit: &Unit,
115    path: &Path,
116) -> Option<PathBuf> {
117    remap_pairs(build_runner, unit)
118        .filter_map(|(from, to)| {
119            let rest = path.strip_prefix(&from).ok()?;
120            Some(Path::new(&to).join(rest))
121        })
122        .last()
123}
124
125/// Like [`trim_paths_remap`] but yields `(from, to)` pairs.
126fn remap_pairs(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> impl Iterator<Item = RemapPair> {
127    package_remap(build_runner, unit).into_iter().chain([
128        build_dir_remap(build_runner),
129        sysroot_remap(build_runner, unit),
130    ])
131}
132
133fn join_remap((from, to): RemapPair) -> OsString {
134    let mut remap = OsString::with_capacity(from.as_os_str().len() + 1 + to.len());
135    remap.push(from);
136    remap.push("=");
137    remap.push(to);
138    remap
139}
140
141/// Path prefix remap rules for sysroot.
142///
143/// This remap logic aligns with rustc:
144/// <https://github.com/rust-lang/rust/blob/c2ef3516/src/bootstrap/src/lib.rs#L1113-L1116>
145fn sysroot_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> RemapPair {
146    // See also `detect_sysroot_src_path()`.
147    let mut sysroot = build_runner.bcx.target_data.info(unit.kind).sysroot.clone();
148    sysroot.push("lib");
149    sysroot.push("rustlib");
150    sysroot.push("src");
151    sysroot.push("rust");
152
153    let rustc = build_runner.bcx.rustc();
154    let to = match rustc.commit_hash.as_ref() {
155        Some(commit_hash) => format!("/rustc/{commit_hash}"),
156        None => format!("/rustc/{}", rustc.version),
157    };
158    (sysroot, to)
159}
160
161/// Path prefix remap rules for dependencies.
162fn package_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<RemapPair> {
163    let pkg_root = unit.pkg.root();
164    let ws_root = build_runner.bcx.ws.root();
165    let source_id = unit.pkg.package_id().source_id();
166
167    if source_id.is_git() {
168        if let Some((from, rev)) = git_checkout(build_runner, pkg_root) {
169            const GIT_OID_LEN: usize = 7; // This matches MIN_ABBREV_LEN in git source
170            let repo = hex::short_hash(source_id.canonical_url());
171            let rev = &rev[..rev.len().min(GIT_OID_LEN)];
172            return vec![(from.to_path_buf(), format!("/cargo/git/{repo}/{rev}"))];
173        }
174    } else if source_id.is_registry() {
175        let registry_src = build_runner.bcx.gctx.registry_source_path();
176        let registry_src = registry_src.as_path_unlocked();
177        let from = pkg_root.parent().unwrap();
178        if from.starts_with(registry_src) {
179            let registry = hex::short_hash(&source_id);
180            return vec![(from.to_path_buf(), format!("/cargo/registry/{registry}"))];
181        }
182    }
183
184    // Handle path local dependencies and abnormal reg/git deps source location.
185    if pkg_root.strip_prefix(ws_root).is_ok() {
186        workspace_remap(build_runner, unit)
187    } else {
188        let from = pkg_root.to_path_buf();
189        let to = format!("/cargo/deps/{}-{}", unit.pkg.name(), unit.pkg.version());
190        vec![(from, to)]
191    }
192}
193
194/// Path prefix remap rules for dependencies within workspaces.
195fn workspace_remap(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Vec<RemapPair> {
196    let ws_root = build_runner.bcx.ws.root();
197    // rustc working directory is usually workspace root.
198    // However, when `-Zroot-dir` is set, it may not be.
199    // We may need to remap to that otherwise debuginfo like `DW_AT_comp_dir`
200    // would point to rustc working directory,
201    // and won't be remapped by workspace root.
202    let (src, rustc_workdir) = path_args(build_runner.bcx.ws, unit);
203
204    let custom_prefix = build_runner
205        .bcx
206        .gctx
207        .get_env(WS_REMAP_ENV)
208        .ok()
209        .filter(|prefix| !prefix.is_empty());
210
211    // When custom prefix for workspace remap is set via `WS_REMAP_ENV`,
212    // an extra remap rule for relative member paths is required
213    // for correctly adding prefix to member paths.
214    //
215    // For more, see <https://github.com/rust-lang/cargo/pull/17366>
216    let relative_remap = if let Some(prefix) = custom_prefix
217        && src.is_relative()
218        && let Ok(rel) = unit.pkg.root().strip_prefix(&rustc_workdir)
219        && !rel.is_empty()
220    {
221        let mut rel_to = prefix.to_owned();
222        for comp in rel.components() {
223            // e.g., library -> <custom-prefix>/library
224            rel_to.push('/');
225            rel_to.push_str(&comp.as_os_str().to_string_lossy());
226        }
227        Some((rel.to_path_buf(), rel_to))
228    } else {
229        None
230    };
231
232    let from = if ws_root.starts_with(&rustc_workdir) {
233        rustc_workdir
234    } else {
235        ws_root.to_path_buf()
236    };
237
238    let absolute_remap = (from, custom_prefix.unwrap_or(".").to_owned());
239
240    let mut remaps = vec![absolute_remap];
241    remaps.extend(relative_remap);
242    remaps
243}
244
245/// Finds the checkout root and revision directory name of a git dependency.
246///
247/// This is built under this layout: `$CARGO_HOME/git/checkouts/<repo>-<hash>[-shallow]/<rev>`.
248///
249/// `None` when the package does not live under the global git checkouts directory,
250/// for example a vendored git dependency.
251fn git_checkout<'a>(
252    build_runner: &BuildRunner<'_, '_>,
253    pkg_root: &'a Path,
254) -> Option<(&'a Path, &'a str)> {
255    let checkouts = build_runner.bcx.gctx.git_checkouts_path();
256    let checkouts = checkouts.as_path_unlocked();
257    let rel = pkg_root.strip_prefix(checkouts).ok()?;
258    let mut components = rel.components();
259    let (_repo, rev) = (components.next()?, components.next()?);
260    let rev = rev.as_os_str().to_str()?;
261    let checkout_root = pkg_root.ancestors().nth(components.count())?;
262    Some((checkout_root, rev))
263}
264
265/// Remap all paths pointing to `build.build-dir`,
266/// i.e., `[BUILD_DIR]/debug/deps/foo-[HASH].dwo` would be remapped to
267/// `/cargo/build-dir/debug/deps/foo-[HASH].dwo`
268/// (note the `/cargo/build-dir` prefix).
269///
270/// This covers scenarios like:
271///
272/// * Build script generated code. For example, a build script may call `file!`
273///   macros, and the associated crate uses [`include!`] to include the expanded
274///   [`file!`] macro in-place via the `OUT_DIR` environment.
275/// * On Linux, `DW_AT_GNU_dwo_name` that contains paths to split debuginfo
276///   files (dwp and dwo).
277fn build_dir_remap(build_runner: &BuildRunner<'_, '_>) -> RemapPair {
278    let from = build_runner.bcx.ws.build_dir().into_path_unlocked();
279    let to = "/cargo/build-dir".to_owned();
280    (from, to)
281}
282
283/// On-disk schema of the unremap file.
284#[derive(Serialize)]
285#[serde(rename_all = "snake_case")]
286struct UnremapFile<'a> {
287    v: u8,
288    rust_version: &'a str,
289    workspace_root: &'a Path,
290    remaps: Vec<Remap<'a>>,
291}
292
293#[derive(Serialize)]
294#[serde(rename_all = "snake_case")]
295struct Remap<'a> {
296    from: &'a str,
297    to: &'a Path,
298}
299
300/// Whether an unremap file is worth emitting beside its artifacts.
301pub(crate) fn should_emit_unremap_file(unit: &Unit) -> bool {
302    // The unremap file is a debug companion like a dSYM or PDB.
303    // Without debuginfo there is nothing worth unmapping.
304    if !unit.profile.debuginfo.is_turned_on() {
305        return false;
306    }
307
308    match unit.profile.trim_paths {
309        TomlTrimPaths::None => false,
310        TomlTrimPaths::Object | TomlTrimPaths::All => true,
311    }
312}
313
314/// Writes the unremap file for a unit's final artifacts.
315pub(crate) fn write_unremap_file(
316    mut out: impl Write,
317    build_runner: &BuildRunner<'_, '_>,
318    unit: &Unit,
319) -> CargoResult<()> {
320    let mut remaps = BTreeMap::new();
321
322    let mut insert = |(from, to): RemapPair| match remaps.entry(to) {
323        Entry::Vacant(entry) => {
324            entry.insert(from);
325        }
326        Entry::Occupied(entry) if *entry.get() != from => {
327            debug!(
328                "conflicting unremap records for `{}`: `{}` and `{}`",
329                entry.key(),
330                entry.get().display(),
331                from.display(),
332            );
333        }
334        Entry::Occupied(_) => {}
335    };
336
337    insert(sysroot_remap(build_runner, unit));
338    insert(build_dir_remap(build_runner));
339
340    let mut seen = HashSet::default();
341    let mut stack = vec![unit.clone()];
342    while let Some(unit) = stack.pop() {
343        if !seen.insert(unit.clone()) {
344            continue;
345        }
346        for dep in build_runner.unit_deps(&unit) {
347            stack.push(dep.unit.clone());
348        }
349        for (from, to) in package_remap(build_runner, &unit) {
350            // No need to emit records for relative rules as
351            // the absolute workspace record already covers their prefixes.
352            if from.is_relative() {
353                continue;
354            }
355            insert((from, to));
356        }
357    }
358
359    let rust_version = build_runner.bcx.rustc().version.to_string();
360    let file = UnremapFile {
361        v: CURRENT_UNREMAP_VERSION,
362        rust_version: &rust_version,
363        workspace_root: build_runner.bcx.ws.root(),
364        remaps: remaps.iter().map(|(from, to)| Remap { from, to }).collect(),
365    };
366    serde_json::to_writer(&mut out, &file)?;
367    out.write_all(b"\n")?;
368
369    Ok(())
370}
371
372/// Appends the unremap file suffix to an artifact path.
373pub(crate) fn append_unremap_suffix(link: &PathBuf) -> PathBuf {
374    let mut link_buf = link.clone().into_os_string();
375    link_buf.push(UNREMAP_SUFFIX);
376    PathBuf::from(link_buf)
377}