Skip to content

Commit 0400592

Browse files
authored
Rollup merge of #165578 - Zalathar:hash, r=adwinwhite
Avoid `Hash::hash` when stable-hashing various types This PR makes StableHash independent of stdlib-dependent Hash impls for several types, to avoid potential inconsistency in stable hashing between stage1 and stage2 compilers. This covers all of the StableHash impls that I'm aware of. However, there are still various other places in the compiler where we rely on `Hash::hash` for hashes that probably should be made consistent between compiler stages.
2 parents 99c4e7d + b864cd3 commit 0400592

5 files changed

Lines changed: 104 additions & 70 deletions

File tree

‎compiler/rustc_abi/src/extern_abi.rs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -241,19 +241,33 @@ impl PartialEq for ExternAbi {
241241

242242
impl Eq for ExternAbi {}
243243

244+
impl ExternAbi {
245+
/// Common implementation for `Hash` and `StableHash`.
246+
fn stable_hash_inner(&self, hasher: &mut impl Hasher) {
247+
// To avoid staging inconsistencies in stable hashing, we must not rely
248+
// on any stdlib-provided or stdlib-derived impl of `Hash`.
249+
// See <https://github.com/rust-lang/rust/issues/164734> for context.
250+
251+
// Hardcoded copy of the unstable `Hasher::write_str`, with an explicit terminator.
252+
hasher.write(self.as_str().as_bytes());
253+
hasher.write_u8(0xFF);
254+
255+
// double-assurance of a prefix breaker
256+
hasher.write_u32(u32::from_be_bytes(*b"ABI\0"));
257+
}
258+
}
259+
244260
impl Hash for ExternAbi {
245261
fn hash<H: Hasher>(&self, state: &mut H) {
246-
self.as_str().hash(state);
247-
// double-assurance of a prefix breaker
248-
u32::from_be_bytes(*b"ABI\0").hash(state);
262+
self.stable_hash_inner(state);
249263
}
250264
}
251265

252266
#[cfg(feature = "nightly")]
253267
impl StableHash for ExternAbi {
254268
#[inline]
255269
fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
256-
Hash::hash(self, hasher);
270+
self.stable_hash_inner(hasher);
257271
}
258272
}
259273

‎compiler/rustc_attr_ir/src/lang_items.rs‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
//! * Functions called by the compiler itself.
99
1010
use rustc_data_structures::fx::FxIndexMap;
11-
use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
1211
use rustc_macros::{BlobDecodable, Encodable, PrintAttribute, StableHash};
1312
use rustc_span::def_id::DefId;
1413
use rustc_span::{Symbol, kw, sym};
@@ -80,7 +79,7 @@ macro_rules! language_item_table {
8079
$( $(#[$attr:meta])* $variant:ident, $module:ident :: $name:ident, $method:ident, $target:expr, $generics:expr; )*
8180
) => {
8281
/// A representation of all the valid lang items in Rust.
83-
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, BlobDecodable, PrintAttribute)]
82+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, StableHash, Encodable, BlobDecodable, PrintAttribute)]
8483
pub enum LangItem {
8584
$(
8685
#[doc = concat!("The `", stringify!($name), "` lang item.")]
@@ -149,12 +148,6 @@ macro_rules! language_item_table {
149148
}
150149
}
151150

152-
impl StableHash for LangItem {
153-
fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
154-
::std::hash::Hash::hash(self, hasher);
155-
}
156-
}
157-
158151
language_item_table! {
159152
// Variant name, Name, Getter method name, Target Generic requirements;
160153
Sized, sym::sized, sized_trait, Target::Trait, GenericRequirement::Exact(0);

‎compiler/rustc_data_structures/src/fingerprint.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ use std::hash::{Hash, Hasher};
33
use rustc_hashes::Hash64;
44
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
55

6-
use crate::stable_hash::{FromStableHash, StableHasherHash, impl_stable_traits_for_trivial_type};
6+
use crate::stable_hash::{
7+
FromStableHash, StableHash, StableHashCtxt, StableHasher, StableHasherHash,
8+
};
79

810
#[cfg(test)]
911
mod tests;
@@ -165,7 +167,13 @@ impl FromStableHash for Fingerprint {
165167
}
166168
}
167169

168-
impl_stable_traits_for_trivial_type!(Fingerprint);
170+
impl StableHash for Fingerprint {
171+
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
172+
let &Fingerprint(a, b) = self;
173+
a.stable_hash(hcx, hasher);
174+
b.stable_hash(hcx, hasher);
175+
}
176+
}
169177

170178
impl<E: Encoder> Encodable<E> for Fingerprint {
171179
#[inline]

‎compiler/rustc_data_structures/src/stable_hash.rs‎

Lines changed: 56 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1-
use std::hash::{BuildHasher, Hash, Hasher};
1+
use std::ffi::OsStr;
2+
use std::hash::{BuildHasher, Hasher};
23
use std::marker::PhantomData;
34
use std::num::NonZero;
45

5-
use rustc_index::bit_set::{self, DenseBitSet};
6-
use rustc_index::{Idx, IndexSlice, IndexVec};
6+
use rustc_hashes::{Hash64, Hash128};
7+
use rustc_index::{Idx, IndexSlice, IndexVec, bit_set};
78
use rustc_macros::StableHash;
9+
pub use rustc_stable_hash::{
10+
FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher,
11+
};
812
use smallvec::SmallVec;
913
use thin_vec::ThinVec;
1014

@@ -13,11 +17,6 @@ use crate::fingerprint::Fingerprint;
1317
#[cfg(test)]
1418
mod tests;
1519

16-
use rustc_hashes::{Hash64, Hash128};
17-
pub use rustc_stable_hash::{
18-
FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher,
19-
};
20-
2120
/// This trait lets `StableHash` and `derive(StableHash)` be used in
2221
/// this crate (and other crates upstream of `rustc_middle`), while leaving
2322
/// certain operations to be defined in `rustc_middle` where more things are
@@ -186,29 +185,20 @@ impl<T: StableOrd> StableCompare for T {
186185
}
187186
}
188187

189-
/// Implement StableHash by just calling `Hash::hash()`. Also implement `StableOrd` for the type
190-
/// since that has the same requirements.
191-
///
192-
/// **WARNING** This is only valid for types that *really* don't need any context for fingerprinting.
193-
/// But it is easy to misuse this macro (see [#96013](https://github.com/rust-lang/rust/issues/96013)
194-
/// for examples). Therefore this macro is not exported and should only be used in the limited cases
195-
/// here in this module.
196-
///
197-
/// Use `#[derive(StableHash)]` instead.
198-
macro_rules! impl_stable_traits_for_trivial_type {
199-
($t:ty) => {
200-
impl $crate::stable_hash::StableHash for $t {
188+
/// Implements [`StableHash`] and [`StableOrd`] for a primitive integer type.
189+
/// The stable-hash impl calls the corresponding `Hasher::write_*` method.
190+
macro_rules! impl_stable_traits_for_int {
191+
(
192+
$ty:ty, $write_ty_method:ident
193+
) => {
194+
impl StableHash for $ty {
201195
#[inline]
202-
fn stable_hash<Hcx>(
203-
&self,
204-
_: &mut Hcx,
205-
hasher: &mut $crate::stable_hash::StableHasher,
206-
) {
207-
::std::hash::Hash::hash(self, hasher);
196+
fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
197+
hasher.$write_ty_method(*self);
208198
}
209199
}
210200

211-
impl $crate::stable_hash::StableOrd for $t {
201+
impl StableOrd for $ty {
212202
const CAN_USE_UNSTABLE_SORT: bool = true;
213203

214204
// Encoding and decoding doesn't change the bytes of trivial types
@@ -218,34 +208,42 @@ macro_rules! impl_stable_traits_for_trivial_type {
218208
};
219209
}
220210

221-
pub(crate) use impl_stable_traits_for_trivial_type;
222-
223-
impl_stable_traits_for_trivial_type!(i8);
224-
impl_stable_traits_for_trivial_type!(i16);
225-
impl_stable_traits_for_trivial_type!(i32);
226-
impl_stable_traits_for_trivial_type!(i64);
227-
impl_stable_traits_for_trivial_type!(isize);
211+
impl_stable_traits_for_int!(u8, write_u8);
212+
impl_stable_traits_for_int!(u16, write_u16);
213+
impl_stable_traits_for_int!(u32, write_u32);
214+
impl_stable_traits_for_int!(u64, write_u64);
215+
impl_stable_traits_for_int!(u128, write_u128);
216+
impl_stable_traits_for_int!(usize, write_usize);
228217

229-
impl_stable_traits_for_trivial_type!(u8);
230-
impl_stable_traits_for_trivial_type!(u16);
231-
impl_stable_traits_for_trivial_type!(u32);
232-
impl_stable_traits_for_trivial_type!(u64);
233-
impl_stable_traits_for_trivial_type!(usize);
218+
impl_stable_traits_for_int!(i8, write_i8);
219+
impl_stable_traits_for_int!(i16, write_i16);
220+
impl_stable_traits_for_int!(i32, write_i32);
221+
impl_stable_traits_for_int!(i64, write_i64);
222+
impl_stable_traits_for_int!(i128, write_i128);
223+
impl_stable_traits_for_int!(isize, write_isize);
234224

235-
impl_stable_traits_for_trivial_type!(u128);
236-
impl_stable_traits_for_trivial_type!(i128);
225+
impl StableHash for char {
226+
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
227+
u32::from(*self).stable_hash(hcx, hasher);
228+
}
229+
}
237230

238-
impl_stable_traits_for_trivial_type!(char);
239-
impl_stable_traits_for_trivial_type!(());
231+
impl StableHash for () {
232+
fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {
233+
// No need to hash anything for the unit type.
234+
}
235+
}
240236

241-
impl_stable_traits_for_trivial_type!(Hash64);
237+
impl StableHash for Hash64 {
238+
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
239+
self.as_u64().stable_hash(hcx, hasher);
240+
}
241+
}
242242

243-
// We need a custom impl as the default hash function will only hash half the bits. For stable
244-
// hashing we want to hash the full 128-bit hash.
245243
impl StableHash for Hash128 {
246244
#[inline]
247-
fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
248-
self.as_u128().hash(hasher);
245+
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
246+
self.as_u128().stable_hash(hcx, hasher);
249247
}
250248
}
251249

@@ -394,7 +392,7 @@ impl<T: StableHash> StableHash for Vec<T> {
394392

395393
impl<K, V, R> StableHash for indexmap::IndexMap<K, V, R>
396394
where
397-
K: StableHash + Eq + Hash,
395+
K: StableHash,
398396
V: StableHash,
399397
R: BuildHasher,
400398
{
@@ -409,7 +407,7 @@ where
409407

410408
impl<K, R> StableHash for indexmap::IndexSet<K, R>
411409
where
412-
K: StableHash + Eq + Hash,
410+
K: StableHash,
413411
R: BuildHasher,
414412
{
415413
#[inline]
@@ -609,19 +607,23 @@ where
609607
}
610608
}
611609

612-
impl<I: Idx> StableHash for DenseBitSet<I> {
610+
impl<I: Idx> StableHash for bit_set::DenseBitSet<I> {
613611
fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, hasher: &mut StableHasher) {
614-
::std::hash::Hash::hash(self, hasher);
612+
bit_set::DenseBitSet::stable_hash_inner(self, hasher);
615613
}
616614
}
617615

618616
impl<R: Idx, C: Idx> StableHash for bit_set::BitMatrix<R, C> {
619617
fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, hasher: &mut StableHasher) {
620-
::std::hash::Hash::hash(self, hasher);
618+
bit_set::BitMatrix::stable_hash_inner(self, hasher);
621619
}
622620
}
623621

624-
impl_stable_traits_for_trivial_type!(::std::ffi::OsStr);
622+
impl StableHash for OsStr {
623+
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
624+
self.as_encoded_bytes().stable_hash(hcx, hasher);
625+
}
626+
}
625627

626628
impl StableHash for std::path::Path {
627629
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {

‎compiler/rustc_index/src/bit_set.rs‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ fn inclusive_start_end<T: Idx>(
7575
/// will panic if the bitsets have differing domain sizes.
7676
///
7777
#[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext))]
78-
#[derive(Eq, PartialEq, Hash)]
78+
#[derive(Eq, PartialEq)]
7979
pub struct DenseBitSet<T> {
8080
domain_size: usize,
8181
words: Box<[Word]>,
@@ -114,6 +114,14 @@ impl<T: Idx> DenseBitSet<T> {
114114
result
115115
}
116116

117+
/// Should only be called by `impl StableHash for DenseBitSet`.
118+
pub fn stable_hash_inner(this: &Self, hasher: &mut impl std::hash::Hasher) {
119+
let &DenseBitSet { domain_size, ref words, marker: PhantomData } = this;
120+
hasher.write_usize(domain_size);
121+
// No need to hash `words.len()`, since it is derived from the domain size.
122+
words.iter().for_each(|&word| hasher.write_u64(word));
123+
}
124+
117125
/// Clear all elements.
118126
#[inline]
119127
pub fn clear(&mut self) {
@@ -1306,7 +1314,7 @@ impl<T: Idx> GrowableBitSet<T> {
13061314
/// All operations that involve a row and/or column index will panic if the
13071315
/// index exceeds the relevant bound.
13081316
#[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext))]
1309-
#[derive(Clone, Eq, PartialEq, Hash)]
1317+
#[derive(Clone, Eq, PartialEq)]
13101318
pub struct BitMatrix<R: Idx, C: Idx> {
13111319
num_rows: usize,
13121320
num_columns: usize,
@@ -1341,6 +1349,15 @@ impl<R: Idx, C: Idx> BitMatrix<R, C> {
13411349
}
13421350
}
13431351

1352+
/// Should only be called by `impl StableHash for BitMatrix`.
1353+
pub fn stable_hash_inner(this: &Self, hasher: &mut impl std::hash::Hasher) {
1354+
let &BitMatrix { num_rows, num_columns, ref words, marker: PhantomData } = this;
1355+
hasher.write_usize(num_rows);
1356+
hasher.write_usize(num_columns);
1357+
// No need to hash `words.len()`, since it is derived from the matrix dimensions.
1358+
words.iter().for_each(|&word| hasher.write_u64(word));
1359+
}
1360+
13441361
pub fn rows(&self) -> impl Iterator<Item = R> {
13451362
(0..self.num_rows).map(R::new)
13461363
}

0 commit comments

Comments
 (0)