Skip to main content

rustc_metadata/
fs.rs

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