From 5caf516cd087af9b6b8349e12709b2e77b054f39 Mon Sep 17 00:00:00 2001 From: Asger Hautop Drewsen Date: Fri, 8 Nov 2024 22:51:49 +0100 Subject: [PATCH] rustc: Fail fast when compiling a source file larger than 4 GiB - 1 B Fixes #132862 --- compiler/rustc_span/src/lib.rs | 5 +++++ compiler/rustc_span/src/source_map.rs | 11 ++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 5b1be5bca0593..74fe587207af8 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1843,6 +1843,8 @@ impl StableSourceFileId { } impl SourceFile { + const MAX_FILE_SIZE: u32 = u32::MAX - 1; + pub fn new( name: FileName, mut src: String, @@ -1863,6 +1865,9 @@ impl SourceFile { let stable_id = StableSourceFileId::from_filename_in_current_crate(&name); let source_len = src.len(); let source_len = u32::try_from(source_len).map_err(|_| OffsetOverflowError)?; + if source_len > Self::MAX_FILE_SIZE { + return Err(OffsetOverflowError); + } let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src); diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index f36bb38623e5d..eb26f72adc091 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -115,6 +115,12 @@ impl FileLoader for RealFileLoader { } fn read_file(&self, path: &Path) -> io::Result { + if path.metadata().is_ok_and(|metadata| metadata.len() > SourceFile::MAX_FILE_SIZE.into()) { + return Err(io::Error::other(format!( + "text files larger than {} bytes are unsupported", + SourceFile::MAX_FILE_SIZE + ))); + } fs::read_to_string(path) } @@ -297,7 +303,10 @@ impl SourceMap { /// unmodified. pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| { - eprintln!("fatal error: rustc does not support files larger than 4GB"); + eprintln!( + "fatal error: rustc does not support text files larger than {} bytes", + SourceFile::MAX_FILE_SIZE + ); crate::fatal_error::FatalError.raise() }) }