Skip to content

Commit 6ba4b12

Browse files
Fix failure in unsafe-checker on invalid UTF-8
1 parent 9e0322e commit 6ba4b12

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

src/unsafe_checker.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ use anyhow::Result;
88
use std::path::Path;
99

1010
pub(crate) fn scan_path(path: &Path) -> Result<Option<UnsafeUsage>> {
11-
let source = std::fs::read_to_string(path)
12-
.with_context(|| format!("Failed to read `{}`", path.display()))?;
13-
Ok(scan_string(&source, path))
11+
let bytes =
12+
std::fs::read(path).with_context(|| format!("Failed to read `{}`", path.display()))?;
13+
let Ok(source) = std::str::from_utf8(&bytes) else {
14+
// If the file isn't valid UTF-8 then we don't need to check it for the unsafe keyword,
15+
// since it can't be a source file that the rust compiler would accept.
16+
return Ok(None);
17+
};
18+
Ok(scan_string(source, path))
1419
}
1520

1621
fn scan_string(source: &str, path: &Path) -> Option<UnsafeUsage> {

test_crates/crab2/src/lib.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1+
// Make sure that we don't add any unsafe to this crate. We want this crate to have no unsafe since
2+
// it has an include_bytes! below and we want to make sure that include_bytes! of invalid UTF-8
3+
// doesn't cause the unsafe token-based checker any problems. If we had some actual unsafe in this
4+
// crate, then we'd need to allow it and then the unsafe-checker wouldn't run.
5+
#![forbid(unsafe_code)]
6+
17
use bar::write as woozle;
28
use fob::fs as bar;
39
use std as fob;
410

11+
const DATA: &[u8] = include_bytes!("../../data/random.data");
12+
513
pub mod stuff {
614
#[link(
715
name = "nothing",
@@ -16,5 +24,8 @@ pub mod stuff {
1624
true
1725
});
1826
crab3::do_stuff();
27+
28+
let total: u32 = crate::DATA.iter().cloned().map(|byte| byte as u32).sum();
29+
println!("{}", total);
1930
}
2031
}

test_crates/data/random.data

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
�� %��r���^nV��5�\b��� �B�I�O@�M���S>��O�>Jr��@�x����!�T8\_X�u ���ߡ*��o�y�'�f��S��h��ca�
2+
*hx�-V}�$_��S�lY��rlKž,��ZA�F�� �?plmn��-� \b����` �&���ܞʝ<��zl�)6��Ha�`��q6�-�&P���2��I�)"� s΅��+���7��Q�˦�����bE�i�� Ӟ'�Q�

0 commit comments

Comments
 (0)