rustc_metadata/
fs.rs

1use std::path::{Path, PathBuf};
2use std::{fs, io};
3
4use rustc_data_structures::temp_dir::MaybeTempDir;
5use rustc_middle::ty::TyCtxt;
6use rustc_session::config::{OutFileName, OutputType};
7use rustc_session::output::filename_for_metadata;
8use rustc_session::{MetadataKind, Session};
9use tempfile::Builder as TempFileBuilder;
10
11use crate::errors::{
12    BinaryOutputToTty, FailedCopyToStdout, FailedCreateEncodedMetadata, FailedCreateFile,
13    FailedCreateTempdir, FailedWriteError,
14};
15use crate::{EncodedMetadata, encode_metadata};
16
17// FIXME(eddyb) maybe include the crate name in this?
18pub 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.
25pub 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.dcx().emit_fatal(FailedWriteError { filename: out_filename, err });
36    }
37
38    out_filename
39}
40
41pub fn encode_and_write_metadata(tcx: TyCtxt<'_>) -> (EncodedMetadata, bool) {
42    let out_filename = filename_for_metadata(tcx.sess, tcx.output_filenames(()));
43    // To avoid races with another rustc process scanning the output directory,
44    // we need to write the file somewhere else and atomically move it to its
45    // final destination, with an `fs::rename` call. In order for the rename to
46    // always succeed, the temporary file needs to be on the same filesystem,
47    // which is why we create it inside the output directory specifically.
48    let metadata_tmpdir = TempFileBuilder::new()
49        .prefix("rmeta")
50        .tempdir_in(out_filename.parent().unwrap_or_else(|| Path::new("")))
51        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailedCreateTempdir { err }));
52    let metadata_tmpdir = MaybeTempDir::new(metadata_tmpdir, tcx.sess.opts.cg.save_temps);
53    let metadata_filename = metadata_tmpdir.as_ref().join(METADATA_FILENAME);
54
55    // Always create a file at `metadata_filename`, even if we have nothing to write to it.
56    // This simplifies the creation of the output `out_filename` when requested.
57    let metadata_kind = tcx.metadata_kind();
58    match metadata_kind {
59        MetadataKind::None => {
60            std::fs::File::create(&metadata_filename).unwrap_or_else(|err| {
61                tcx.dcx().emit_fatal(FailedCreateFile { filename: &metadata_filename, err });
62            });
63        }
64        MetadataKind::Uncompressed | MetadataKind::Compressed => {
65            encode_metadata(tcx, &metadata_filename);
66        }
67    };
68
69    let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
70
71    // If the user requests metadata as output, rename `metadata_filename`
72    // to the expected output `out_filename`. The match above should ensure
73    // this file always exists.
74    let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
75    let (metadata_filename, metadata_tmpdir) = if need_metadata_file {
76        let filename = match out_filename {
77            OutFileName::Real(ref path) => {
78                if let Err(err) = non_durable_rename(&metadata_filename, path) {
79                    tcx.dcx().emit_fatal(FailedWriteError { filename: path.to_path_buf(), err });
80                }
81                path.clone()
82            }
83            OutFileName::Stdout => {
84                if out_filename.is_tty() {
85                    tcx.dcx().emit_err(BinaryOutputToTty);
86                } else if let Err(err) = copy_to_stdout(&metadata_filename) {
87                    tcx.dcx()
88                        .emit_err(FailedCopyToStdout { filename: metadata_filename.clone(), err });
89                }
90                metadata_filename
91            }
92        };
93        if tcx.sess.opts.json_artifact_notifications {
94            tcx.dcx().emit_artifact_notification(out_filename.as_path(), "metadata");
95        }
96        (filename, None)
97    } else {
98        (metadata_filename, Some(metadata_tmpdir))
99    };
100
101    // Load metadata back to memory: codegen may need to include it in object files.
102    let metadata =
103        EncodedMetadata::from_path(metadata_filename, metadata_tmpdir).unwrap_or_else(|err| {
104            tcx.dcx().emit_fatal(FailedCreateEncodedMetadata { err });
105        });
106
107    let need_metadata_module = metadata_kind == MetadataKind::Compressed;
108
109    (metadata, need_metadata_module)
110}
111
112#[cfg(not(target_os = "linux"))]
113pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
114    std::fs::rename(src, dst)
115}
116
117/// This function attempts to bypass the auto_da_alloc heuristic implemented by some filesystems
118/// such as btrfs and ext4. When renaming over a file that already exists then they will "helpfully"
119/// write back the source file before committing the rename in case a developer forgot some of
120/// the fsyncs in the open/write/fsync(file)/rename/fsync(dir) dance for atomic file updates.
121///
122/// To avoid triggering this heuristic we delete the destination first, if it exists.
123/// The cost of an extra syscall is much lower than getting descheduled for the sync IO.
124#[cfg(target_os = "linux")]
125pub fn non_durable_rename(src: &Path, dst: &Path) -> std::io::Result<()> {
126    let _ = std::fs::remove_file(dst);
127    std::fs::rename(src, dst)
128}
129
130pub fn copy_to_stdout(from: &Path) -> io::Result<()> {
131    let mut reader = fs::File::open_buffered(from)?;
132    let mut stdout = io::stdout();
133    io::copy(&mut reader, &mut stdout)?;
134    Ok(())
135}