Skip to content

Commit bc1bca7

Browse files
committed
Fix download hash check on big-endian systems
Ensure the hash_file and hash_dir routines give identical results on big- and little-endian systems. The default hash routines for integer types are endian-dependent, so all such hash inputs need to be byte-swapped. This applies in particular to the file hashes used as input when computing directory hashes. In addition, the default hash routines for composite types use a length prefix, which it itself an integer type (usize). In order to be able to byte-swap that prefix, we have to re-implement those bits of the standard library ourselves.
1 parent e4584e8 commit bc1bca7

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

build_system/prepare.rs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::ffi::OsStr;
22
use std::fs;
3+
use std::hash::{Hash, Hasher};
34
use std::path::{Path, PathBuf};
45
use std::process::Command;
56

@@ -71,7 +72,11 @@ fn hash_file(file: &std::path::Path) -> u64 {
7172
let contents = std::fs::read(file).unwrap();
7273
#[allow(deprecated)]
7374
let mut hasher = std::hash::SipHasher::new();
74-
std::hash::Hash::hash(&contents, &mut hasher);
75+
// The following is equivalent to
76+
// std::hash::Hash::hash(&contents, &mut hasher);
77+
// but gives the same result independent of host byte order.
78+
hasher.write_usize(contents.len().to_le());
79+
Hash::hash_slice(&contents, &mut hasher);
7580
std::hash::Hasher::finish(&hasher)
7681
}
7782

@@ -80,16 +85,26 @@ fn hash_dir(dir: &std::path::Path) -> u64 {
8085
for entry in std::fs::read_dir(dir).unwrap() {
8186
let entry = entry.unwrap();
8287
if entry.file_type().unwrap().is_dir() {
83-
sub_hashes
84-
.insert(entry.file_name().to_str().unwrap().to_owned(), hash_dir(&entry.path()));
88+
sub_hashes.insert(
89+
entry.file_name().to_str().unwrap().to_owned(),
90+
hash_dir(&entry.path()).to_le(),
91+
);
8592
} else {
86-
sub_hashes
87-
.insert(entry.file_name().to_str().unwrap().to_owned(), hash_file(&entry.path()));
93+
sub_hashes.insert(
94+
entry.file_name().to_str().unwrap().to_owned(),
95+
hash_file(&entry.path()).to_le(),
96+
);
8897
}
8998
}
9099
#[allow(deprecated)]
91100
let mut hasher = std::hash::SipHasher::new();
92-
std::hash::Hash::hash(&sub_hashes, &mut hasher);
101+
// The following is equivalent to
102+
// std::hash::Hash::hash(&sub_hashes, &mut hasher);
103+
// but gives the same result independent of host byte order.
104+
hasher.write_usize(sub_hashes.len().to_le());
105+
for elt in sub_hashes {
106+
elt.hash(&mut hasher);
107+
}
93108
std::hash::Hasher::finish(&hasher)
94109
}
95110

0 commit comments

Comments
 (0)