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