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