Skip to content

Commit f815d74

Browse files
committed
Fix ICE when include_str! reads binary files
1 parent 42ec52b commit f815d74

File tree

5 files changed

+43
-0
lines changed

5 files changed

+43
-0
lines changed

compiler/rustc_parse/src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,13 @@ pub fn utf8_error<E: EmissionGuarantee>(
130130
};
131131
let contents = String::from_utf8_lossy(contents).to_string();
132132
let source = sm.new_source_file(PathBuf::from(path).into(), contents);
133+
134+
// Avoid out-of-bounds span from lossy UTF-8 conversion.
135+
if start as u32 > source.normalized_source_len.0 {
136+
err.note(note);
137+
return;
138+
}
139+
133140
let span = Span::with_root_ctxt(
134141
source.normalized_byte_pos(start as u32),
135142
source.normalized_byte_pos(start as u32),
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
//@ only-linux
2+
//@ normalize-stderr: "at byte `\d+`" -> "at byte `$$BYTE`"
3+
// Test ensure reading a binary file with include_str! doesn't cause an ICE
4+
// regression test for issue <https://github.com/rust-lang/rust/issues/149304>
5+
6+
#![doc = include_str!("/bin/id")] //~ ERROR: `/bin/id` wasn't a utf-8 file
7+
8+
fn main() {}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: `/bin/id` wasn't a utf-8 file
2+
--> $DIR/binary-file-linux.rs:6:10
3+
|
4+
LL | #![doc = include_str!("/bin/id")]
5+
| ^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: invalid utf-8 at byte `$BYTE`
8+
9+
error: aborting due to 1 previous error
10+
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
//@ only-windows
2+
//@ normalize-stderr: "at byte `\d+`" -> "at byte `$$BYTE`"
3+
// Test ensure reading a binary file with include_str! doesn't cause an ICE
4+
// regression test for issue <https://github.com/rust-lang/rust/issues/149304>
5+
6+
#![doc = include_str!("C:\\Windows\\System32\\cmd.exe")] //~ ERROR: `C:/Windows/System32/cmd.exe` wasn't a utf-8 file
7+
8+
fn main() {}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: `C:/Windows/System32/cmd.exe` wasn't a utf-8 file
2+
--> $DIR/binary-file-windows.rs:6:10
3+
|
4+
LL | #![doc = include_str!("C:/Windows/System32/cmd.exe")]
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: invalid utf-8 at byte `$BYTE`
8+
9+
error: aborting due to 1 previous error
10+

0 commit comments

Comments
 (0)