1 //! This module defines a generic file format that allows to check if a given
2 //! file generated by incremental compilation was generated by a compatible
3 //! compiler version. This file format is used for the on-disk version of the
4 //! dependency graph and the exported metadata hashes.
6 //! In practice "compatible compiler version" means "exactly the same compiler
7 //! version", since the header encodes the git commit hash of the compiler.
8 //! Since we can always just ignore the incremental compilation cache and
9 //! compiler versions don't change frequently for the typical user, being
10 //! conservative here practically has no downside.
14 use std::io::{self, Read};
15 use std::path::{Path, PathBuf};
17 use rustc_data_structures::memmap::Mmap;
18 use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
19 use rustc_serialize::Encoder;
20 use rustc_session::Session;
22 /// The first few bytes of files generated by incremental compilation.
23 const FILE_MAGIC: &[u8] = b"RSIC";
25 /// Change this if the header format changes.
26 const HEADER_FORMAT_VERSION: u16 = 0;
28 /// A version string that hopefully is always different for compiler versions
29 /// with different encodings of incremental compilation artifacts. Contains
30 /// the Git commit hash.
31 const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");
33 pub(crate) fn write_file_header(stream: &mut FileEncoder, nightly_build: bool) {
34 stream.emit_raw_bytes(FILE_MAGIC);
36 .emit_raw_bytes(&[(HEADER_FORMAT_VERSION >> 0) as u8, (HEADER_FORMAT_VERSION >> 8) as u8]);
38 let rustc_version = rustc_version(nightly_build);
39 assert_eq!(rustc_version.len(), (rustc_version.len() as u8) as usize);
40 stream.emit_raw_bytes(&[rustc_version.len() as u8]);
41 stream.emit_raw_bytes(rustc_version.as_bytes());
44 pub(crate) fn save_in<F>(sess: &Session, path_buf: PathBuf, name: &str, encode: F)
46 F: FnOnce(FileEncoder) -> FileEncodeResult,
48 debug!("save: storing data in {}", path_buf.display());
50 // Delete the old file, if any.
51 // Note: It's important that we actually delete the old file and not just
52 // truncate and overwrite it, since it might be a shared hard-link, the
53 // underlying data of which we don't want to modify.
55 // We have to ensure we have dropped the memory maps to this file
56 // before performing this removal.
57 match fs::remove_file(&path_buf) {
59 debug!("save: remove old file");
61 Err(err) if err.kind() == io::ErrorKind::NotFound => (),
64 "unable to delete old {} at `{}`: {}",
73 let mut encoder = match FileEncoder::new(&path_buf) {
74 Ok(encoder) => encoder,
76 sess.err(&format!("failed to create {} at `{}`: {}", name, path_buf.display(), err));
81 write_file_header(&mut encoder, sess.is_nightly_build());
83 match encode(encoder) {
85 sess.prof.artifact_size(
86 &name.replace(' ', "_"),
87 path_buf.file_name().unwrap().to_string_lossy(),
90 debug!("save: data written to disk successfully");
93 sess.err(&format!("failed to write {} to `{}`: {}", name, path_buf.display(), err));
98 /// Reads the contents of a file with a file header as defined in this module.
100 /// - Returns `Ok(Some(data, pos))` if the file existed and was generated by a
101 /// compatible compiler version. `data` is the entire contents of the file
102 /// and `pos` points to the first byte after the header.
103 /// - Returns `Ok(None)` if the file did not exist or was generated by an
104 /// incompatible version of the compiler.
105 /// - Returns `Err(..)` if some kind of IO error occurred while reading the
108 report_incremental_info: bool,
111 ) -> io::Result<Option<(Mmap, usize)>> {
112 let file = match fs::File::open(path) {
114 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
115 Err(err) => return Err(err),
117 // SAFETY: This process must not modify nor remove the backing file while the memory map lives.
118 // For the dep-graph and the work product index, it is as soon as the decoding is done.
119 // For the query result cache, the memory map is dropped in save_dep_graph before calling
120 // save_in and trying to remove the backing file.
122 // There is no way to prevent another process from modifying this file.
123 let mmap = unsafe { Mmap::map(file) }?;
125 let mut file = io::Cursor::new(&*mmap);
129 debug_assert!(FILE_MAGIC.len() == 4);
130 let mut file_magic = [0u8; 4];
131 file.read_exact(&mut file_magic)?;
132 if file_magic != FILE_MAGIC {
133 report_format_mismatch(report_incremental_info, path, "Wrong FILE_MAGIC");
138 // Check HEADER_FORMAT_VERSION
140 debug_assert!(::std::mem::size_of_val(&HEADER_FORMAT_VERSION) == 2);
141 let mut header_format_version = [0u8; 2];
142 file.read_exact(&mut header_format_version)?;
143 let header_format_version =
144 (header_format_version[0] as u16) | ((header_format_version[1] as u16) << 8);
146 if header_format_version != HEADER_FORMAT_VERSION {
147 report_format_mismatch(report_incremental_info, path, "Wrong HEADER_FORMAT_VERSION");
152 // Check RUSTC_VERSION
154 let mut rustc_version_str_len = [0u8; 1];
155 file.read_exact(&mut rustc_version_str_len)?;
156 let rustc_version_str_len = rustc_version_str_len[0] as usize;
157 let mut buffer = vec![0; rustc_version_str_len];
158 file.read_exact(&mut buffer)?;
160 if buffer != rustc_version(nightly_build).as_bytes() {
161 report_format_mismatch(report_incremental_info, path, "Different compiler version");
166 let post_header_start_pos = file.position() as usize;
167 Ok(Some((mmap, post_header_start_pos)))
170 fn report_format_mismatch(report_incremental_info: bool, file: &Path, message: &str) {
171 debug!("read_file: {}", message);
173 if report_incremental_info {
175 "[incremental] ignoring cache artifact `{}`: {}",
176 file.file_name().unwrap().to_string_lossy(),
182 fn rustc_version(nightly_build: bool) -> String {
184 if let Some(val) = env::var_os("RUSTC_FORCE_RUSTC_VERSION") {
185 return val.to_string_lossy().into_owned();
191 "Cannot use rustc without explicit version for \
192 incremental compilation",