]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/fs.rs
Auto merge of #100845 - timvermeulen:iter_compare, r=scottmcm
[rust.git] / compiler / rustc_metadata / src / fs.rs
1 use crate::errors::{
2     FailedCreateEncodedMetadata, FailedCreateFile, FailedCreateTempdir, FailedWriteError,
3 };
4 use crate::{encode_metadata, EncodedMetadata};
5
6 use rustc_data_structures::temp_dir::MaybeTempDir;
7 use rustc_hir::def_id::LOCAL_CRATE;
8 use rustc_middle::ty::TyCtxt;
9 use rustc_session::config::{CrateType, OutputFilenames, OutputType};
10 use rustc_session::output::filename_for_metadata;
11 use rustc_session::Session;
12 use tempfile::Builder as TempFileBuilder;
13
14 use std::fs;
15 use std::path::{Path, PathBuf};
16
17 // FIXME(eddyb) maybe include the crate name in this?
18 pub const METADATA_FILENAME: &str = "lib.rmeta";
19
20 /// We use a temp directory here to avoid races between concurrent rustc processes,
21 /// such as builds in the same directory using the same filename for metadata while
22 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
23 /// directory being searched for `extern crate` (observing an incomplete file).
24 /// The returned path is the temporary file containing the complete metadata.
25 pub fn emit_metadata(sess: &Session, metadata: &[u8], tmpdir: &MaybeTempDir) -> PathBuf {
26     let out_filename = tmpdir.as_ref().join(METADATA_FILENAME);
27     let result = fs::write(&out_filename, metadata);
28
29     if let Err(err) = result {
30         sess.emit_fatal(FailedWriteError { filename: out_filename, err });
31     }
32
33     out_filename
34 }
35
36 pub fn encode_and_write_metadata(
37     tcx: TyCtxt<'_>,
38     outputs: &OutputFilenames,
39 ) -> (EncodedMetadata, bool) {
40     #[derive(PartialEq, Eq, PartialOrd, Ord)]
41     enum MetadataKind {
42         None,
43         Uncompressed,
44         Compressed,
45     }
46
47     let metadata_kind = tcx
48         .sess
49         .crate_types()
50         .iter()
51         .map(|ty| match *ty {
52             CrateType::Executable | CrateType::Staticlib | CrateType::Cdylib => MetadataKind::None,
53
54             CrateType::Rlib => MetadataKind::Uncompressed,
55
56             CrateType::Dylib | CrateType::ProcMacro => MetadataKind::Compressed,
57         })
58         .max()
59         .unwrap_or(MetadataKind::None);
60
61     let crate_name = tcx.crate_name(LOCAL_CRATE);
62     let out_filename = filename_for_metadata(tcx.sess, crate_name.as_str(), outputs);
63     // To avoid races with another rustc process scanning the output directory,
64     // we need to write the file somewhere else and atomically move it to its
65     // final destination, with an `fs::rename` call. In order for the rename to
66     // always succeed, the temporary file needs to be on the same filesystem,
67     // which is why we create it inside the output directory specifically.
68     let metadata_tmpdir = TempFileBuilder::new()
69         .prefix("rmeta")
70         .tempdir_in(out_filename.parent().unwrap_or_else(|| Path::new("")))
71         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailedCreateTempdir { err }));
72     let metadata_tmpdir = MaybeTempDir::new(metadata_tmpdir, tcx.sess.opts.cg.save_temps);
73     let metadata_filename = metadata_tmpdir.as_ref().join(METADATA_FILENAME);
74
75     // Always create a file at `metadata_filename`, even if we have nothing to write to it.
76     // This simplifies the creation of the output `out_filename` when requested.
77     match metadata_kind {
78         MetadataKind::None => {
79             std::fs::File::create(&metadata_filename).unwrap_or_else(|err| {
80                 tcx.sess.emit_fatal(FailedCreateFile { filename: &metadata_filename, err });
81             });
82         }
83         MetadataKind::Uncompressed | MetadataKind::Compressed => {
84             encode_metadata(tcx, &metadata_filename);
85         }
86     };
87
88     let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
89
90     // If the user requests metadata as output, rename `metadata_filename`
91     // to the expected output `out_filename`.  The match above should ensure
92     // this file always exists.
93     let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
94     let (metadata_filename, metadata_tmpdir) = if need_metadata_file {
95         if let Err(err) = non_durable_rename(&metadata_filename, &out_filename) {
96             tcx.sess.emit_fatal(FailedWriteError { filename: out_filename, err });
97         }
98         if tcx.sess.opts.json_artifact_notifications {
99             tcx.sess
100                 .parse_sess
101                 .span_diagnostic
102                 .emit_artifact_notification(&out_filename, "metadata");
103         }
104         (out_filename, None)
105     } else {
106         (metadata_filename, Some(metadata_tmpdir))
107     };
108
109     // Load metadata back to memory: codegen may need to include it in object files.
110     let metadata =
111         EncodedMetadata::from_path(metadata_filename, metadata_tmpdir).unwrap_or_else(|err| {
112             tcx.sess.emit_fatal(FailedCreateEncodedMetadata { err });
113         });
114
115     let need_metadata_module = metadata_kind == MetadataKind::Compressed;
116
117     (metadata, need_metadata_module)
118 }
119
120 #[cfg(not(target_os = "linux"))]
121 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
122     std::fs::rename(src, dst)
123 }
124
125 /// This function attempts to bypass the auto_da_alloc heuristic implemented by some filesystems
126 /// such as btrfs and ext4. When renaming over a file that already exists then they will "helpfully"
127 /// write back the source file before committing the rename in case a developer forgot some of
128 /// the fsyncs in the open/write/fsync(file)/rename/fsync(dir) dance for atomic file updates.
129 ///
130 /// To avoid triggering this heuristic we delete the destination first, if it exists.
131 /// The cost of an extra syscall is much lower than getting descheduled for the sync IO.
132 #[cfg(target_os = "linux")]
133 pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
134     let _ = std::fs::remove_file(dst);
135     std::fs::rename(src, dst)
136 }