]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/stable_hasher.rs
Rollup merge of #96167 - CAD97:weak-dlsym-less-ptr-crime, r=thomcc
[rust.git] / compiler / rustc_data_structures / src / stable_hasher.rs
1 use crate::sip128::SipHasher128;
2 use rustc_index::bit_set;
3 use rustc_index::vec;
4 use smallvec::SmallVec;
5 use std::hash::{BuildHasher, Hash, Hasher};
6 use std::mem;
7
8 #[cfg(test)]
9 mod tests;
10
11 /// When hashing something that ends up affecting properties like symbol names,
12 /// we want these symbol names to be calculated independently of other factors
13 /// like what architecture you're compiling *from*.
14 ///
15 /// To that end we always convert integers to little-endian format before
16 /// hashing and the architecture dependent `isize` and `usize` types are
17 /// extended to 64 bits if needed.
18 pub struct StableHasher {
19     state: SipHasher128,
20 }
21
22 impl ::std::fmt::Debug for StableHasher {
23     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24         write!(f, "{:?}", self.state)
25     }
26 }
27
28 pub trait StableHasherResult: Sized {
29     fn finish(hasher: StableHasher) -> Self;
30 }
31
32 impl StableHasher {
33     #[inline]
34     pub fn new() -> Self {
35         StableHasher { state: SipHasher128::new_with_keys(0, 0) }
36     }
37
38     #[inline]
39     pub fn finish<W: StableHasherResult>(self) -> W {
40         W::finish(self)
41     }
42 }
43
44 impl StableHasherResult for u128 {
45     #[inline]
46     fn finish(hasher: StableHasher) -> Self {
47         let (_0, _1) = hasher.finalize();
48         u128::from(_0) | (u128::from(_1) << 64)
49     }
50 }
51
52 impl StableHasherResult for u64 {
53     #[inline]
54     fn finish(hasher: StableHasher) -> Self {
55         hasher.finalize().0
56     }
57 }
58
59 impl StableHasher {
60     #[inline]
61     pub fn finalize(self) -> (u64, u64) {
62         self.state.finish128()
63     }
64 }
65
66 impl Hasher for StableHasher {
67     fn finish(&self) -> u64 {
68         panic!("use StableHasher::finalize instead");
69     }
70
71     #[inline]
72     fn write(&mut self, bytes: &[u8]) {
73         self.state.write(bytes);
74     }
75
76     #[inline]
77     fn write_u8(&mut self, i: u8) {
78         self.state.write_u8(i);
79     }
80
81     #[inline]
82     fn write_u16(&mut self, i: u16) {
83         self.state.short_write(i.to_le_bytes());
84     }
85
86     #[inline]
87     fn write_u32(&mut self, i: u32) {
88         self.state.short_write(i.to_le_bytes());
89     }
90
91     #[inline]
92     fn write_u64(&mut self, i: u64) {
93         self.state.short_write(i.to_le_bytes());
94     }
95
96     #[inline]
97     fn write_u128(&mut self, i: u128) {
98         self.state.write(&i.to_le_bytes());
99     }
100
101     #[inline]
102     fn write_usize(&mut self, i: usize) {
103         // Always treat usize as u64 so we get the same results on 32 and 64 bit
104         // platforms. This is important for symbol hashes when cross compiling,
105         // for example.
106         self.state.short_write((i as u64).to_le_bytes());
107     }
108
109     #[inline]
110     fn write_i8(&mut self, i: i8) {
111         self.state.write_i8(i);
112     }
113
114     #[inline]
115     fn write_i16(&mut self, i: i16) {
116         self.state.short_write((i as u16).to_le_bytes());
117     }
118
119     #[inline]
120     fn write_i32(&mut self, i: i32) {
121         self.state.short_write((i as u32).to_le_bytes());
122     }
123
124     #[inline]
125     fn write_i64(&mut self, i: i64) {
126         self.state.short_write((i as u64).to_le_bytes());
127     }
128
129     #[inline]
130     fn write_i128(&mut self, i: i128) {
131         self.state.write(&(i as u128).to_le_bytes());
132     }
133
134     #[inline]
135     fn write_isize(&mut self, i: isize) {
136         // Always treat isize as a 64-bit number so we get the same results on 32 and 64 bit
137         // platforms. This is important for symbol hashes when cross compiling,
138         // for example. Sign extending here is preferable as it means that the
139         // same negative number hashes the same on both 32 and 64 bit platforms.
140         let value = i as u64;
141
142         // Cold path
143         #[cold]
144         #[inline(never)]
145         fn hash_value(state: &mut SipHasher128, value: u64) {
146             state.write_u8(0xFF);
147             state.short_write(value.to_le_bytes());
148         }
149
150         // `isize` values often seem to have a small (positive) numeric value in practice.
151         // To exploit this, if the value is small, we will hash a smaller amount of bytes.
152         // However, we cannot just skip the leading zero bytes, as that would produce the same hash
153         // e.g. if you hash two values that have the same bit pattern when they are swapped.
154         // See https://github.com/rust-lang/rust/pull/93014 for context.
155         //
156         // Therefore, we employ the following strategy:
157         // 1) When we encounter a value that fits within a single byte (the most common case), we
158         // hash just that byte. This is the most common case that is being optimized. However, we do
159         // not do this for the value 0xFF, as that is a reserved prefix (a bit like in UTF-8).
160         // 2) When we encounter a larger value, we hash a "marker" 0xFF and then the corresponding
161         // 8 bytes. Since this prefix cannot occur when we hash a single byte, when we hash two
162         // `isize`s that fit within a different amount of bytes, they should always produce a different
163         // byte stream for the hasher.
164         if value < 0xFF {
165             self.state.write_u8(value as u8);
166         } else {
167             hash_value(&mut self.state, value);
168         }
169     }
170 }
171
172 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
173 /// stable across multiple compilation sessions.
174 ///
175 /// Note that `HashStable` imposes rather more strict requirements than usual
176 /// hash functions:
177 ///
178 /// - Stable hashes are sometimes used as identifiers. Therefore they must
179 ///   conform to the corresponding `PartialEq` implementations:
180 ///
181 ///     - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
182 ///     - `x != y` implies `hash_stable(x) != hash_stable(y)`.
183 ///
184 ///   That second condition is usually not required for hash functions
185 ///   (e.g. `Hash`). In practice this means that `hash_stable` must feed any
186 ///   information into the hasher that a `PartialEq` comparison takes into
187 ///   account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
188 ///   for an example where violating this invariant has caused trouble in the
189 ///   past.
190 ///
191 /// - `hash_stable()` must be independent of the current
192 ///    compilation session. E.g. they must not hash memory addresses or other
193 ///    things that are "randomly" assigned per compilation session.
194 ///
195 /// - `hash_stable()` must be independent of the host architecture. The
196 ///   `StableHasher` takes care of endianness and `isize`/`usize` platform
197 ///   differences.
198 pub trait HashStable<CTX> {
199     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
200 }
201
202 /// Implement this for types that can be turned into stable keys like, for
203 /// example, for DefId that can be converted to a DefPathHash. This is used for
204 /// bringing maps into a predictable order before hashing them.
205 pub trait ToStableHashKey<HCX> {
206     type KeyType: Ord + Sized + HashStable<HCX>;
207     fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
208 }
209
210 /// Implement HashStable by just calling `Hash::hash()`.
211 ///
212 /// **WARNING** This is only valid for types that *really* don't need any context for fingerprinting.
213 /// But it is easy to misuse this macro (see [#96013](https://github.com/rust-lang/rust/issues/96013)
214 /// for examples). Therefore this macro is not exported and should only be used in the limited cases
215 /// here in this module.
216 ///
217 /// Use `#[derive(HashStable_Generic)]` instead.
218 macro_rules! impl_stable_hash_via_hash {
219     ($t:ty) => {
220         impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
221             #[inline]
222             fn hash_stable(&self, _: &mut CTX, hasher: &mut $crate::stable_hasher::StableHasher) {
223                 ::std::hash::Hash::hash(self, hasher);
224             }
225         }
226     };
227 }
228
229 impl_stable_hash_via_hash!(i8);
230 impl_stable_hash_via_hash!(i16);
231 impl_stable_hash_via_hash!(i32);
232 impl_stable_hash_via_hash!(i64);
233 impl_stable_hash_via_hash!(isize);
234
235 impl_stable_hash_via_hash!(u8);
236 impl_stable_hash_via_hash!(u16);
237 impl_stable_hash_via_hash!(u32);
238 impl_stable_hash_via_hash!(u64);
239 impl_stable_hash_via_hash!(usize);
240
241 impl_stable_hash_via_hash!(u128);
242 impl_stable_hash_via_hash!(i128);
243
244 impl_stable_hash_via_hash!(char);
245 impl_stable_hash_via_hash!(());
246
247 impl<CTX> HashStable<CTX> for ! {
248     fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {
249         unreachable!()
250     }
251 }
252
253 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
254     #[inline]
255     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
256         self.get().hash_stable(ctx, hasher)
257     }
258 }
259
260 impl<CTX> HashStable<CTX> for ::std::num::NonZeroUsize {
261     #[inline]
262     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
263         self.get().hash_stable(ctx, hasher)
264     }
265 }
266
267 impl<CTX> HashStable<CTX> for f32 {
268     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
269         let val: u32 = unsafe { ::std::mem::transmute(*self) };
270         val.hash_stable(ctx, hasher);
271     }
272 }
273
274 impl<CTX> HashStable<CTX> for f64 {
275     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
276         let val: u64 = unsafe { ::std::mem::transmute(*self) };
277         val.hash_stable(ctx, hasher);
278     }
279 }
280
281 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
282     #[inline]
283     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
284         (*self as i8).hash_stable(ctx, hasher);
285     }
286 }
287
288 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
289     #[inline]
290     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
291         let (ref _0,) = *self;
292         _0.hash_stable(ctx, hasher);
293     }
294 }
295
296 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
297     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
298         let (ref _0, ref _1) = *self;
299         _0.hash_stable(ctx, hasher);
300         _1.hash_stable(ctx, hasher);
301     }
302 }
303
304 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
305 where
306     T1: HashStable<CTX>,
307     T2: HashStable<CTX>,
308     T3: HashStable<CTX>,
309 {
310     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
311         let (ref _0, ref _1, ref _2) = *self;
312         _0.hash_stable(ctx, hasher);
313         _1.hash_stable(ctx, hasher);
314         _2.hash_stable(ctx, hasher);
315     }
316 }
317
318 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
319 where
320     T1: HashStable<CTX>,
321     T2: HashStable<CTX>,
322     T3: HashStable<CTX>,
323     T4: HashStable<CTX>,
324 {
325     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
326         let (ref _0, ref _1, ref _2, ref _3) = *self;
327         _0.hash_stable(ctx, hasher);
328         _1.hash_stable(ctx, hasher);
329         _2.hash_stable(ctx, hasher);
330         _3.hash_stable(ctx, hasher);
331     }
332 }
333
334 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
335     default fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
336         self.len().hash_stable(ctx, hasher);
337         for item in self {
338             item.hash_stable(ctx, hasher);
339         }
340     }
341 }
342
343 impl<CTX> HashStable<CTX> for [u8] {
344     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
345         self.len().hash_stable(ctx, hasher);
346         hasher.write(self);
347     }
348 }
349
350 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
351     #[inline]
352     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
353         (&self[..]).hash_stable(ctx, hasher);
354     }
355 }
356
357 impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
358 where
359     K: HashStable<CTX> + Eq + Hash,
360     V: HashStable<CTX>,
361     R: BuildHasher,
362 {
363     #[inline]
364     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
365         self.len().hash_stable(ctx, hasher);
366         for kv in self {
367             kv.hash_stable(ctx, hasher);
368         }
369     }
370 }
371
372 impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
373 where
374     K: HashStable<CTX> + Eq + Hash,
375     R: BuildHasher,
376 {
377     #[inline]
378     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
379         self.len().hash_stable(ctx, hasher);
380         for key in self {
381             key.hash_stable(ctx, hasher);
382         }
383     }
384 }
385
386 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]>
387 where
388     A: HashStable<CTX>,
389 {
390     #[inline]
391     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
392         (&self[..]).hash_stable(ctx, hasher);
393     }
394 }
395
396 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
397     #[inline]
398     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
399         (**self).hash_stable(ctx, hasher);
400     }
401 }
402
403 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
404     #[inline]
405     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
406         (**self).hash_stable(ctx, hasher);
407     }
408 }
409
410 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
411     #[inline]
412     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
413         (**self).hash_stable(ctx, hasher);
414     }
415 }
416
417 impl<CTX> HashStable<CTX> for str {
418     #[inline]
419     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
420         self.as_bytes().hash_stable(ctx, hasher);
421     }
422 }
423
424 impl<CTX> HashStable<CTX> for String {
425     #[inline]
426     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
427         (&self[..]).hash_stable(hcx, hasher);
428     }
429 }
430
431 impl<HCX> ToStableHashKey<HCX> for String {
432     type KeyType = String;
433     #[inline]
434     fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
435         self.clone()
436     }
437 }
438
439 impl<CTX> HashStable<CTX> for bool {
440     #[inline]
441     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
442         (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
443     }
444 }
445
446 impl<T, CTX> HashStable<CTX> for Option<T>
447 where
448     T: HashStable<CTX>,
449 {
450     #[inline]
451     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
452         if let Some(ref value) = *self {
453             1u8.hash_stable(ctx, hasher);
454             value.hash_stable(ctx, hasher);
455         } else {
456             0u8.hash_stable(ctx, hasher);
457         }
458     }
459 }
460
461 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
462 where
463     T1: HashStable<CTX>,
464     T2: HashStable<CTX>,
465 {
466     #[inline]
467     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
468         mem::discriminant(self).hash_stable(ctx, hasher);
469         match *self {
470             Ok(ref x) => x.hash_stable(ctx, hasher),
471             Err(ref x) => x.hash_stable(ctx, hasher),
472         }
473     }
474 }
475
476 impl<'a, T, CTX> HashStable<CTX> for &'a T
477 where
478     T: HashStable<CTX> + ?Sized,
479 {
480     #[inline]
481     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
482         (**self).hash_stable(ctx, hasher);
483     }
484 }
485
486 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
487     #[inline]
488     fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
489         ::std::hash::Hash::hash(self, hasher);
490     }
491 }
492
493 impl<T, CTX> HashStable<CTX> for ::std::ops::RangeInclusive<T>
494 where
495     T: HashStable<CTX>,
496 {
497     #[inline]
498     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
499         self.start().hash_stable(ctx, hasher);
500         self.end().hash_stable(ctx, hasher);
501     }
502 }
503
504 impl<I: vec::Idx, T, CTX> HashStable<CTX> for vec::IndexVec<I, T>
505 where
506     T: HashStable<CTX>,
507 {
508     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
509         self.len().hash_stable(ctx, hasher);
510         for v in &self.raw {
511             v.hash_stable(ctx, hasher);
512         }
513     }
514 }
515
516 impl<I: vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I> {
517     fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
518         ::std::hash::Hash::hash(self, hasher);
519     }
520 }
521
522 impl<R: vec::Idx, C: vec::Idx, CTX> HashStable<CTX> for bit_set::BitMatrix<R, C> {
523     fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
524         ::std::hash::Hash::hash(self, hasher);
525     }
526 }
527
528 impl<T, CTX> HashStable<CTX> for bit_set::FiniteBitSet<T>
529 where
530     T: HashStable<CTX> + bit_set::FiniteBitSetTy,
531 {
532     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
533         self.0.hash_stable(hcx, hasher);
534     }
535 }
536
537 impl_stable_hash_via_hash!(::std::path::Path);
538 impl_stable_hash_via_hash!(::std::path::PathBuf);
539
540 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
541 where
542     K: ToStableHashKey<HCX> + Eq,
543     V: HashStable<HCX>,
544     R: BuildHasher,
545 {
546     #[inline]
547     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
548         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, (key, value)| {
549             let key = key.to_stable_hash_key(hcx);
550             key.hash_stable(hcx, hasher);
551             value.hash_stable(hcx, hasher);
552         });
553     }
554 }
555
556 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
557 where
558     K: ToStableHashKey<HCX> + Eq,
559     R: BuildHasher,
560 {
561     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
562         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, key| {
563             let key = key.to_stable_hash_key(hcx);
564             key.hash_stable(hcx, hasher);
565         });
566     }
567 }
568
569 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
570 where
571     K: ToStableHashKey<HCX>,
572     V: HashStable<HCX>,
573 {
574     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
575         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, (key, value)| {
576             let key = key.to_stable_hash_key(hcx);
577             key.hash_stable(hcx, hasher);
578             value.hash_stable(hcx, hasher);
579         });
580     }
581 }
582
583 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
584 where
585     K: ToStableHashKey<HCX>,
586 {
587     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
588         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, key| {
589             let key = key.to_stable_hash_key(hcx);
590             key.hash_stable(hcx, hasher);
591         });
592     }
593 }
594
595 fn stable_hash_reduce<HCX, I, C, F>(
596     hcx: &mut HCX,
597     hasher: &mut StableHasher,
598     mut collection: C,
599     length: usize,
600     hash_function: F,
601 ) where
602     C: Iterator<Item = I>,
603     F: Fn(&mut StableHasher, &mut HCX, I),
604 {
605     length.hash_stable(hcx, hasher);
606
607     match length {
608         1 => {
609             hash_function(hasher, hcx, collection.next().unwrap());
610         }
611         _ => {
612             let hash = collection
613                 .map(|value| {
614                     let mut hasher = StableHasher::new();
615                     hash_function(&mut hasher, hcx, value);
616                     hasher.finish::<u128>()
617                 })
618                 .reduce(|accum, value| accum.wrapping_add(value));
619             hash.hash_stable(hcx, hasher);
620         }
621     }
622 }
623
624 /// Controls what data we do or not not hash.
625 /// Whenever a `HashStable` implementation caches its
626 /// result, it needs to include `HashingControls` as part
627 /// of the key, to ensure that is does not produce an incorrect
628 /// result (for example, using a `Fingerprint` produced while
629 /// hashing `Span`s when a `Fingerprint` without `Span`s is
630 /// being requested)
631 #[derive(Clone, Hash, Eq, PartialEq, Debug)]
632 pub struct HashingControls {
633     pub hash_spans: bool,
634 }