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 = if !tcx.sess.opts.unstable_opts.embed_metadata
52        && !tcx.crate_types().contains(&CrateType::ProcMacro)
53    {
54        Some(metadata_tmpdir.as_ref().join("stub.rmeta"))
55    } else {
56        None
57    };
58
59    if tcx.needs_metadata() {
60        encode_metadata(tcx, &metadata_filename, metadata_stub_filename.as_deref());
61    } else {
62        // Always create a file at `metadata_filename`, even if we have nothing to write to it.
63        // This simplifies the creation of the output `out_filename` when requested.
64        std::fs::File::create(&metadata_filename).unwrap_or_else(|err| {
65            tcx.dcx().emit_fatal(FailedCreateFile { filename: &metadata_filename, err });
66        });
67        if let Some(metadata_stub_filename) = &metadata_stub_filename {
68            std::fs::File::create(metadata_stub_filename).unwrap_or_else(|err| {
69                tcx.dcx().emit_fatal(FailedCreateFile { filename: &metadata_stub_filename, err });
70            });
71        }
72    }
73
74    if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
75        return Err(guar);
76    }
77
78    let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
79
80    // If the user requests metadata as output, rename `metadata_filename`
81    // to the expected output `out_filename`. The match above should ensure
82    // this file always exists.
83    let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
84    let (metadata_filename, metadata_tmpdir) = if need_metadata_file {
85        let filename = match out_filename {
86            OutFileName::Real(ref path) => {
87                if let Err(err) = non_durable_rename(&metadata_filename, path) {
88                    tcx.dcx().emit_fatal(FailedWriteError { filename: path.to_path_buf(), err });
89                }
90                path.clone()
91            }
92            OutFileName::Stdout => {
93                if out_filename.is_tty() {
94                    tcx.dcx().emit_err(BinaryOutputToTty);
95                } else if let Err(err) = copy_to_stdout(&metadata_filename) {
96                    tcx.dcx()
97                        .emit_err(FailedCopyToStdout { filename: metadata_filename.clone(), err });
98                }
99                metadata_filename
100            }
101        };
102        if tcx.sess.opts.json_artifact_notifications {
103            tcx.dcx().emit_artifact_notification(out_filename.as_path(), "metadata");
104        }
105        (filename, Some(metadata_tmpdir))
106    } else {
107        (metadata_filename, Some(metadata_tmpdir))
108    };
109
110    // Load metadata back to memory: codegen may need to include it in object files.
111    let metadata =
112        EncodedMetadata::from_path(metadata_filename, metadata_stub_filename, metadata_tmpdir)
113            .unwrap_or_else(|err| {
114                tcx.dcx().emit_fatal(FailedCreateEncodedMetadata { err });
115            });
116
117    Ok(metadata)
118}
119
120#[cfg(not(target_os = "linux"))]
121pub 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")]
133pub 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}
137
138pub fn copy_to_stdout(from: &Path) -> io::Result<()> {
139    let mut reader = fs::File::open_buffered(from)?;
140    let mut stdout = io::stdout();
141    io::copy(&mut reader, &mut stdout)?;
142    Ok(())
143}