Skip to content

Commit 4a78001

Browse files
avikivitysylvestre
authored andcommitted
Strip basedirs from the compiler arguments too
SCCACHE_BASEDIRS strips the base directories from the preprocessed source, but the compiler arguments are hashed verbatim. That leaves out the one thing that most reliably ties a cache entry to a single checkout: a flag that names the tree it is building. -ffile-prefix-map=/home/user/project=. The flag exists precisely so the object file does not depend on where the tree lives - every path it records is rewritten to `.` - so two checkouts of the same commit produce identical objects. They just never agree on the hash, because the flag itself spells the path out, and so they never share an entry. Which is the case basedirs is for. Strip basedirs from each argument before hashing it, at the places where an argument is expected to spell a pathname, and only there: the whole argument, as in a source file or the path of a separated option; the value of an option written with an `=`, which covers either half of a prefix map; and the value glued to a short option such as -I. A basedir appearing anywhere else is left alone, so -DROOT="/home/user/project", which the compiler bakes into the output verbatim, still counts towards the hash. Basedirs carry a trailing slash so that they only match whole path components; in an argument a component can also end at the `=` of a prefix map, or at the end of the argument, so accept those two as well. A sibling /home/user/project-docs is still not a match. The longest basedir wins. Bump CACHE_VERSION and the preprocessor cache's FORMAT_VERSION, since the arguments now reach the hash as bytes rather than through OsString's Hash impl. An integration test is added to tests/integration.
1 parent 8c83b74 commit 4a78001

10 files changed

Lines changed: 440 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,10 @@ export SCCACHE_BASEDIRS="/home/user/project:/home/user/workspace"
344344

345345
Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems.
346346

347+
Base directories are stripped from the preprocessed source and from the compiler arguments alike. The arguments matter because a flag can name the tree it is building: `-ffile-prefix-map=/home/user/project=.` makes the object file independent of where the tree is checked out, but the flag itself is not, and it is hashed verbatim.
348+
349+
In an argument only the places that are expected to spell a pathname are considered: the whole argument, the value of an option written with an `=` (either half of a prefix map), and the value glued to a short option such as `-I`. A base directory appearing anywhere else is left alone, so a definition the compiler bakes into the output verbatim, `-DROOT="/home/user/project"`, still counts. A match also has to end where a path component ends, so a sibling `/home/user/project-docs` is not one.
350+
347351
This is similar to ccache's `CCACHE_BASEDIR` and helps when:
348352
* Building the same project from different directories
349353
* Sharing cache between CI jobs with different checkout paths

‎docs/Configuration.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ server_startup_timeout_ms = 10000
2020
#
2121
# Path matching is case-insensitive on Windows and case-sensitive on other OSes.
2222
#
23+
# Applies to the preprocessed source and to the compiler arguments
24+
# alike, so that a flag naming the tree, such as
25+
# -ffile-prefix-map=/home/user/project=., does not tie the cache
26+
# entry to one checkout. In an argument only the places expected to
27+
# spell a pathname are considered: the whole argument, the value of
28+
# an =-separated option, and the value glued to a short option.
29+
#
2330
# Example:
2431
# basedir = ["/home/user/project"] results in the path prefix rewrite:
2532
# "/home/user/project/src/main.c" -> "src/main.c"

‎src/compiler/c.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use crate::dist::pkg;
2727
use crate::mock_command::CommandCreatorSync;
2828
use crate::util::{
2929
Digest, HashToDigest, MetadataCtimeExt, TimeMacroFinder, Timestamp, decode_path, encode_path,
30-
hash_all, strip_basedirs,
30+
hash_all, strip_basedirs, strip_basedirs_from_arg,
3131
};
3232
use async_trait::async_trait;
3333
use fs_err as fs;
@@ -1457,7 +1457,7 @@ impl pkg::ToolchainPackager for CToolchainPackager {
14571457
}
14581458

14591459
/// The cache is versioned by the inputs to `HashKeyParams::compute`.
1460-
pub const CACHE_VERSION: &[u8] = b"12";
1460+
pub const CACHE_VERSION: &[u8] = b"13";
14611461

14621462
/// Environment variables that are factored into the cache key.
14631463
static CACHED_ENV_VARS: LazyLock<HashSet<&'static OsStr>> = LazyLock::new(|| {
@@ -1479,6 +1479,20 @@ static CACHED_ENV_VARS: LazyLock<HashSet<&'static OsStr>> = LazyLock::new(|| {
14791479
.collect()
14801480
});
14811481

1482+
/// Feed the compiler arguments into `m`, with the base directories stripped.
1483+
///
1484+
/// The arguments are hashed verbatim, so any that spell out an absolute path -
1485+
/// `-ffile-prefix-map=/home/user/project=.` above all - would tie the cache
1486+
/// entry to one checkout of the tree. See [`strip_basedirs_from_arg`].
1487+
pub fn hash_arguments(m: &mut Digest, arguments: &[OsString], basedirs: &[Vec<u8>]) {
1488+
for arg in arguments {
1489+
// Same shape as OsString's own Hash impl: the bytes, then a separator
1490+
// that cannot occur in them.
1491+
m.update(&strip_basedirs_from_arg(arg.as_encoded_bytes(), basedirs));
1492+
m.update(&[0xff]);
1493+
}
1494+
}
1495+
14821496
/// Parameters for computing a hash key for C/C++ compilation caching.
14831497
///
14841498
/// Construct with required fields via [`HashKeyParams::new`], then add optional
@@ -1584,9 +1598,7 @@ impl<'a> HashKeyParams<'a> {
15841598
m.update(&[self.plusplus as u8]);
15851599
m.update(CACHE_VERSION);
15861600
m.update(self.language.as_str().as_bytes());
1587-
for arg in self.arguments {
1588-
arg.hash(&mut HashToDigest { digest: &mut m });
1589-
}
1601+
hash_arguments(&mut m, self.arguments, self.basedirs);
15901602
for hash in self.extra_hashes {
15911603
m.update(hash.as_bytes());
15921604
}

‎src/compiler/preprocessor_cache.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,11 @@ use crate::{
3838
};
3939

4040
use super::Language;
41+
use super::c::hash_arguments;
4142

4243
/// The current format is 1 header byte for the version + bincode encoding
4344
/// of the [`PreprocessorCacheEntry`] struct.
44-
const FORMAT_VERSION: u8 = 0;
45+
const FORMAT_VERSION: u8 = 1;
4546
const MAX_PREPROCESSOR_CACHE_ENTRIES: usize = 100;
4647
const MAX_PREPROCESSOR_CACHE_FILE_INFO_ENTRIES: usize = 10000;
4748

@@ -392,9 +393,7 @@ pub fn preprocessor_cache_entry_hash_key(
392393
m.update(&[plusplus as u8]);
393394
m.update(&[FORMAT_VERSION]);
394395
m.update(language.as_str().as_bytes());
395-
for arg in arguments {
396-
arg.hash(&mut HashToDigest { digest: &mut m });
397-
}
396+
hash_arguments(&mut m, arguments, basedirs);
398397
for hash in extra_hashes {
399398
m.update(hash.as_bytes());
400399
}

‎src/util.rs‎

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,123 @@ pub fn strip_basedirs<'a>(preprocessor_output: &'a [u8], basedirs: &[Vec<u8>]) -
12521252
Cow::Owned(result)
12531253
}
12541254

1255+
/// Strip the base directories from a single compiler argument, for hashing.
1256+
///
1257+
/// [`strip_basedirs`] looks for a basedir where preprocessor output would put
1258+
/// one: at the start of a line, after a quote, after whitespace. A compiler
1259+
/// argument spells the same paths differently. `-I/home/user/project/include`
1260+
/// has no boundary at all before the path, and `-ffile-prefix-map` names a
1261+
/// directory without a trailing slash, as in
1262+
/// `-ffile-prefix-map=/home/user/project=.`, which is what keeps two checkouts
1263+
/// of the same tree from agreeing on a hash.
1264+
///
1265+
/// Only the places where an argument is expected to spell a pathname are
1266+
/// considered, rather than any offset that happens to match:
1267+
///
1268+
/// * the whole argument, as in a source file or the path of a separated
1269+
/// option such as `-include-pch <path>`;
1270+
/// * the value of an option written with an `=`, as in `--sysroot=<path>` or
1271+
/// either half of `-ffile-prefix-map=<path>=<path>`;
1272+
/// * the value glued to a short option, as in `-I<path>` or `-L<path>`.
1273+
///
1274+
/// A basedir sitting anywhere else is left alone, so `-DROOT="/home/user/project"`
1275+
/// keeps a definition the compiler will bake into the output verbatim. A match
1276+
/// also has to end where a path component ends, so `/home/user/project` does not
1277+
/// match the start of `/home/user/project-docs`. The longest basedir wins, so a
1278+
/// nested one takes precedence over the tree that contains it.
1279+
pub fn strip_basedirs_from_arg<'a>(arg: &'a [u8], basedirs: &[Vec<u8>]) -> Cow<'a, [u8]> {
1280+
if basedirs.is_empty() || arg.is_empty() {
1281+
return Cow::Borrowed(arg);
1282+
}
1283+
1284+
// We must return the original argument on all platforms, so we only
1285+
// normalize a copy for searching.
1286+
#[cfg(not(target_os = "windows"))]
1287+
let haystack: &[u8] = arg;
1288+
#[cfg(target_os = "windows")]
1289+
let normalized = normalize_win_path(arg);
1290+
#[cfg(target_os = "windows")]
1291+
let haystack: &[u8] = &normalized;
1292+
1293+
let mut order: Vec<usize> = (0..basedirs.len()).collect();
1294+
order.sort_by_key(|&i| std::cmp::Reverse(basedirs[i].len()));
1295+
1296+
let mut result: Option<Vec<u8>> = None;
1297+
let mut copied = 0;
1298+
for pos in pathname_positions(haystack) {
1299+
if pos < copied {
1300+
// Inside a basedir we already stripped.
1301+
continue;
1302+
}
1303+
let rest = &haystack[pos..];
1304+
let mut matched = 0;
1305+
for &i in &order {
1306+
// Basedirs carry a trailing slash, see Config::basedirs. A path
1307+
// component can also end at the end of the argument, or at a
1308+
// separator such as the `=` of -ffile-prefix-map.
1309+
let with_slash = basedirs[i].as_slice();
1310+
let bare = &with_slash[..with_slash.len() - 1];
1311+
if rest.starts_with(with_slash) {
1312+
matched = with_slash.len();
1313+
} else if rest.starts_with(bare) && matches!(rest.get(bare.len()), None | Some(b'=')) {
1314+
matched = bare.len();
1315+
}
1316+
if matched > 0 {
1317+
trace!(
1318+
"Matched basedir {} at position {} of argument",
1319+
String::from_utf8_lossy(with_slash),
1320+
pos
1321+
);
1322+
break;
1323+
}
1324+
}
1325+
if matched > 0 {
1326+
let out = result.get_or_insert_with(|| Vec::with_capacity(arg.len()));
1327+
out.extend_from_slice(&arg[copied..pos]);
1328+
copied = pos + matched;
1329+
}
1330+
}
1331+
1332+
match result {
1333+
Some(mut out) => {
1334+
out.extend_from_slice(&arg[copied..]);
1335+
Cow::Owned(out)
1336+
}
1337+
None => Cow::Borrowed(arg),
1338+
}
1339+
}
1340+
1341+
/// The offsets in a compiler argument where a pathname can begin.
1342+
///
1343+
/// See [`strip_basedirs_from_arg`] for what they are and why the rest of the
1344+
/// argument is off limits.
1345+
fn pathname_positions(arg: &[u8]) -> impl Iterator<Item = usize> + '_ {
1346+
// The value glued to a short option: everything up to the first byte that
1347+
// cannot be part of an option name. `-I/path` yields 2, `-isystem/path` 8.
1348+
let glued = if arg.first() == Some(&b'-') {
1349+
let name_len = arg[1..]
1350+
.iter()
1351+
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'-' || **b == b'_')
1352+
.count();
1353+
Some(1 + name_len)
1354+
} else {
1355+
None
1356+
};
1357+
1358+
// The whole argument, the value of each `=`-separated option, and the one
1359+
// glued position, in ascending order and without duplicates.
1360+
let equals = arg
1361+
.iter()
1362+
.enumerate()
1363+
.filter(|(_, b)| **b == b'=')
1364+
.map(|(i, _)| i + 1);
1365+
1366+
let mut positions: Vec<usize> = std::iter::once(0).chain(glued).chain(equals).collect();
1367+
positions.sort_unstable();
1368+
positions.dedup();
1369+
positions.into_iter().filter(move |&p| p < arg.len())
1370+
}
1371+
12551372
/// Double every `/` in a normalized path.
12561373
///
12571374
/// Paths inside preprocessor output are C string literals, so on Windows
@@ -1695,6 +1812,126 @@ mod tests {
16951812
assert!(empty_result.is_empty(), "{:?}", empty_result);
16961813
}
16971814

1815+
#[test]
1816+
fn test_strip_basedirs_from_arg() {
1817+
let basedir = b"/home/user/project/".to_vec();
1818+
let strip = |arg: &[u8]| {
1819+
super::strip_basedirs_from_arg(arg, std::slice::from_ref(&basedir)).into_owned()
1820+
};
1821+
1822+
// The flag that ties an object file to one checkout: the tree is named
1823+
// without a trailing slash, so the path component ends at the `=`.
1824+
assert_eq!(
1825+
strip(b"-ffile-prefix-map=/home/user/project=."),
1826+
b"-ffile-prefix-map==."
1827+
);
1828+
assert_eq!(
1829+
strip(b"-ffile-prefix-map=/home/user/project/build=."),
1830+
b"-ffile-prefix-map=build=."
1831+
);
1832+
assert_eq!(
1833+
strip(b"-ffile-prefix-map=/home/user/project/build/=build/"),
1834+
b"-ffile-prefix-map=build/=build/"
1835+
);
1836+
1837+
// Paths with no boundary before them.
1838+
assert_eq!(strip(b"-I/home/user/project/include"), b"-Iinclude");
1839+
assert_eq!(strip(b"/home/user/project/src/main.c"), b"src/main.c");
1840+
1841+
// A sibling directory that merely starts with the same bytes is not a
1842+
// match, in either spelling.
1843+
assert_eq!(
1844+
strip(b"-I/home/user/project-docs/include"),
1845+
b"-I/home/user/project-docs/include"
1846+
);
1847+
assert_eq!(
1848+
strip(b"-ffile-prefix-map=/home/user/project-docs=."),
1849+
b"-ffile-prefix-map=/home/user/project-docs=."
1850+
);
1851+
1852+
// Untouched without basedirs, and when nothing matches.
1853+
assert_eq!(
1854+
&*super::strip_basedirs_from_arg(b"-ffile-prefix-map=/home/user/project=.", &[]),
1855+
b"-ffile-prefix-map=/home/user/project=."
1856+
);
1857+
assert_eq!(strip(b"-O2"), b"-O2");
1858+
assert_eq!(strip(b""), b"");
1859+
}
1860+
1861+
#[test]
1862+
fn test_strip_basedirs_from_arg_only_at_pathname_positions() {
1863+
let basedir = b"/home/user/project/".to_vec();
1864+
let strip = |arg: &[u8]| {
1865+
super::strip_basedirs_from_arg(arg, std::slice::from_ref(&basedir)).into_owned()
1866+
};
1867+
1868+
// A macro definition the compiler bakes into the output verbatim: the
1869+
// path is inside a string literal, not where a pathname is expected.
1870+
assert_eq!(
1871+
strip(b"-DROOT=\"/home/user/project\""),
1872+
b"-DROOT=\"/home/user/project\""
1873+
);
1874+
1875+
// Not the value of an option, just a path further along in one.
1876+
assert_eq!(
1877+
strip(b"-Wl,-rpath,/home/user/project/lib"),
1878+
b"-Wl,-rpath,/home/user/project/lib"
1879+
);
1880+
assert_eq!(
1881+
strip(b"-fplugin-arg-p=x/home/user/project/y"),
1882+
b"-fplugin-arg-p=x/home/user/project/y"
1883+
);
1884+
1885+
// The value glued to a short option, however long its name.
1886+
assert_eq!(
1887+
strip(b"-isystem/home/user/project/abseil"),
1888+
b"-isystemabseil"
1889+
);
1890+
assert_eq!(strip(b"-L/home/user/project/lib"), b"-Llib");
1891+
1892+
// The value of an =-separated option, and both halves of a prefix map.
1893+
assert_eq!(strip(b"--sysroot=/home/user/project/sys"), b"--sysroot=sys");
1894+
assert_eq!(
1895+
strip(b"-ffile-prefix-map=/home/user/project/build=/home/user/project"),
1896+
b"-ffile-prefix-map=build="
1897+
);
1898+
}
1899+
1900+
#[test]
1901+
fn test_strip_basedirs_from_arg_skips_positions_inside_a_match() {
1902+
// A directory whose name contains an `=` is legal, and it puts one of
1903+
// the positions where an option value could start inside the basedir
1904+
// itself. If a second basedir then matches at that position, the two
1905+
// matches overlap, and the tail of the first directory name must not
1906+
// be stripped a second time.
1907+
let basedirs = vec![b"/home/user/a=/b/".to_vec(), b"/b/".to_vec()];
1908+
let strip = |arg: &[u8]| super::strip_basedirs_from_arg(arg, &basedirs).into_owned();
1909+
1910+
assert_eq!(strip(b"-I/home/user/a=/b/include"), b"-Iinclude");
1911+
assert_eq!(strip(b"/home/user/a=/b/src/main.c"), b"src/main.c");
1912+
assert_eq!(strip(b"--sysroot=/home/user/a=/b/sys"), b"--sysroot=sys");
1913+
}
1914+
1915+
#[test]
1916+
fn test_strip_basedirs_from_arg_longest_match_wins() {
1917+
// A build directory nested inside the tree, both listed.
1918+
let basedirs = vec![
1919+
b"/home/user/project/".to_vec(),
1920+
b"/home/user/project/build/".to_vec(),
1921+
];
1922+
assert_eq!(
1923+
&*super::strip_basedirs_from_arg(
1924+
b"-ffile-prefix-map=/home/user/project/build=.",
1925+
&basedirs
1926+
),
1927+
b"-ffile-prefix-map==."
1928+
);
1929+
assert_eq!(
1930+
&*super::strip_basedirs_from_arg(b"-ffile-prefix-map=/home/user/project=.", &basedirs),
1931+
b"-ffile-prefix-map==."
1932+
);
1933+
}
1934+
16981935
#[test]
16991936
fn test_strip_basedir_simple() {
17001937
// Simple cases

‎tests/integration/Makefile‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ endgroup =
3131
endif
3232

3333
BACKENDS := redis redis-deprecated memcached memcached-deprecated s3 azblob webdav basedirs multilevel multilevel-chain
34-
TOOLS := gcc clang cmake cmake-modules cmake-modules-v4 autotools coverage zstd
34+
TOOLS := gcc clang cmake cmake-modules cmake-modules-v4 autotools coverage zstd file-prefix-map
3535

3636
# Map backends to their compose profiles
3737
PROFILES_autotools := autotools
@@ -42,6 +42,7 @@ PROFILES_cmake := cmake
4242
PROFILES_cmake-modules := cmake-modules
4343
PROFILES_cmake-modules-v4 := cmake-modules-v4
4444
PROFILES_coverage := coverage
45+
PROFILES_file-prefix-map := file-prefix-map
4546
PROFILES_gcc := gcc
4647
PROFILES_memcached := memcached
4748
PROFILES_memcached-deprecated := memcached
@@ -62,6 +63,7 @@ SERVICES_cmake :=
6263
SERVICES_cmake-modules :=
6364
SERVICES_cmake-modules-v4 :=
6465
SERVICES_coverage :=
66+
SERVICES_file-prefix-map :=
6567
SERVICES_gcc :=
6668
SERVICES_memcached := memcached
6769
SERVICES_memcached-deprecated := memcached
@@ -102,6 +104,7 @@ help:
102104
@echo " make test-coverage Run Rust coverage instrumentation test"
103105
@echo " make test-zstd Run ZSTD compression levels test"
104106
@echo " make test-basedirs Run basedirs test across all backends"
107+
@echo " make test-file-prefix-map Run basedirs vs -ffile-prefix-map test"
105108
@echo " make test-multilevel Run multi-level cache test across all backends"
106109
@echo " make test-multilevel-chain Run multi-level backfill chain test (4 levels)"
107110
@echo ""

0 commit comments

Comments
 (0)