Skip to main content

rustc_incremental/persist/
fs.rs

1//! This module manages how the incremental compilation cache is represented in
2//! the file system.
3//!
4//! Incremental compilation caches are managed according to a rebuild from
5//! scratch strategy: Once a complete, consistent cache version is finalized, it
6//! is never modified. Instead, when a subsequent compilation session is started,
7//! the compiler will allocate a new version of the cache that starts out empty.
8//! Then only this new directory is written to and it will not be visible to
9//! other processes until it is finalized. This ensures that multiple compiler
10//! processes can be executed concurrently for the same crate without
11//! interfering with each other or blocking each other.
12//!
13//! More concretely this is implemented via the following protocol:
14//!
15//! 1. For a newly started compilation session, the compiler allocates a
16//!    new `session` directory within the incremental compilation directory.
17//!    This session directory will have a unique name that ends with the suffix
18//!    "-working" and that contains a creation timestamp.
19//! 2. Next, the compiler looks for the newest finalized session directory,
20//!    that is, a session directory from a previous compilation session that
21//!    has been marked as valid and consistent. A session directory is
22//!    considered finalized if the "-working" suffix in the directory name has
23//!    been replaced by the SVH of the crate.
24//! 3. Once the compiler has found a valid, finalized session directory, it will
25//!    obtain a shared lock on the directory. If this succeeds, it will have
26//!    read-only access to the old session directory without having to worry
27//!    about synchronizing with other compiler processes.
28//! 4. Now the compiler can do its normal compilation process, which involves
29//!    writing to its private session directory. Possibly by hardlinking
30//!    existing files from the old session directory if they haven't changed.
31//! 5. When compilation finishes without errors, the private session directory
32//!    will be in a state where it can be used as input for other compilation
33//!    sessions. That is, it will contain a dependency graph and cache artifacts
34//!    that are consistent with the state of the source code it was compiled
35//!    from, with no need to change them ever again. At this point, the compiler
36//!    finalizes and "publishes" its private session directory by renaming it
37//!    from "s-{timestamp}-{random}-working" to "s-{timestamp}-{SVH}".
38//! 6. At this point the "old" session directory that we copied our data from
39//!    at the beginning of the session has become obsolete because we have just
40//!    published a more current version. Thus the compiler will delete it.
41//!
42//! ## Garbage Collection
43//!
44//! Naively following the above protocol might lead to old session directories
45//! piling up if a compiler instance crashes for some reason before its able to
46//! remove its private session directory. In order to avoid wasting disk space,
47//! the compiler also does some garbage collection each time it is started in
48//! incremental compilation mode. Specifically, it will scan the incremental
49//! compilation directory for private session directories that are not in use
50//! any more and will delete those. It will also delete any finalized session
51//! directories for a given crate except for the most recent one.
52//!
53//! ## Synchronization
54//!
55//! There is some synchronization needed in order for the compiler to be able to
56//! determine whether a given private session directory is not in use any more.
57//! This is done by creating a lock file for each session directory and
58//! locking it while the directory is still being used. Since file locks have
59//! operating system support, we can rely on the lock being released if the
60//! compiler process dies for some unexpected reason. Thus, when garbage
61//! collecting private session directories, the collecting process can determine
62//! whether the directory is still in use by trying to acquire a lock on the
63//! file. If locking the file fails, the original process must still be alive.
64//! If locking the file succeeds, we know that the owning process is not alive
65//! any more and we can safely delete the directory.
66//! There is still a small time window between the original process creating the
67//! lock file and actually locking it. In order to minimize the chance that
68//! another process tries to acquire the lock in just that instance, only
69//! session directories that are older than a few seconds are considered for
70//! garbage collection.
71//!
72//! Another case that has to be considered is what happens if one process
73//! deletes a finalized session directory that another process is currently
74//! reading from. This case is also handled via the lock file. Before a process
75//! starts reading from a finalized session directory, it will acquire a shared
76//! lock on the directory's lock file. Any garbage collecting process, on the
77//! other hand, will acquire an exclusive lock on the lock file. Thus, if a
78//! directory is being collected, any reader process will fail acquiring the
79//! shared lock and will leave the directory alone. Conversely, if a collecting
80//! process can't acquire the exclusive lock because the directory is currently
81//! being read from, it will leave collecting that directory to another process
82//! at a later point in time.
83//!
84//! ## Preconditions
85//!
86//! This system relies on two features being available in the file system in
87//! order to work really well: file locking and hard linking.
88//! If hard linking is not available (like on FAT) the data in the cache
89//! actually has to be copied at the beginning of each session.
90//! If file locking does not work reliably (like on NFS), some of the
91//! synchronization will go haywire.
92//! In both cases we recommend to locate the incremental compilation directory
93//! on a file system that supports these things.
94//! It might be a good idea though to try and detect whether we are on an
95//! unsupported file system and emit a warning in that case. This is not yet
96//! implemented.
97
98use std::fs as std_fs;
99use std::io::{self, ErrorKind};
100use std::path::{Path, PathBuf};
101use std::time::{Duration, SystemTime, UNIX_EPOCH};
102
103use rand::{RngCore, rng};
104use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN};
105use rustc_data_structures::fx::FxIndexSet;
106use rustc_data_structures::svh::Svh;
107use rustc_data_structures::unord::{UnordMap, UnordSet};
108use rustc_data_structures::{base_n, flock};
109use rustc_fs_util::try_canonicalize;
110use rustc_middle::dep_graph::WorkProduct;
111use rustc_session::config::OutputType;
112use rustc_session::{IncrCompSession, Session, StableCrateId};
113use rustc_span::{Symbol, bug};
114use tracing::debug;
115
116use crate::diagnostics;
117
118#[cfg(test)]
119mod tests;
120
121const LOCK_FILE_EXT: &str = ".lock";
122const DEP_GRAPH_FILENAME: &str = "dep-graph.bin";
123const STAGING_DEP_GRAPH_FILENAME: &str = "dep-graph.part.bin";
124const WORK_PRODUCTS_FILENAME: &str = "work-products.bin";
125const QUERY_CACHE_FILENAME: &str = "query-cache.bin";
126
127// We encode integers using the following base, so they are shorter than decimal
128// or hexadecimal numbers (we want short file and directory names). Since these
129// numbers will be used in file names, we choose an encoding that is not
130// case-sensitive (as opposed to base64, for example).
131const INT_ENCODE_BASE: usize = base_n::CASE_INSENSITIVE;
132
133/// Returns the path to a previous session's dependency graph.
134pub(crate) fn old_dep_graph_path(incr_comp_session: &IncrCompSession) -> Option<PathBuf> {
135    in_old_incr_comp_dir_sess(incr_comp_session, DEP_GRAPH_FILENAME)
136}
137
138/// Returns the path to a session's dependency graph.
139pub(crate) fn dep_graph_path(incr_comp_session: &IncrCompSession) -> PathBuf {
140    in_incr_comp_dir_sess(incr_comp_session, DEP_GRAPH_FILENAME)
141}
142
143/// Returns the path to a session's staging dependency graph.
144///
145/// On the difference between dep-graph and staging dep-graph,
146/// see `build_dep_graph`.
147pub(crate) fn staging_dep_graph_path(incr_comp_session: &IncrCompSession) -> PathBuf {
148    in_incr_comp_dir_sess(incr_comp_session, STAGING_DEP_GRAPH_FILENAME)
149}
150
151pub(crate) fn old_work_products_path(incr_comp_session: &IncrCompSession) -> Option<PathBuf> {
152    in_old_incr_comp_dir_sess(incr_comp_session, WORK_PRODUCTS_FILENAME)
153}
154
155pub(crate) fn work_products_path(incr_comp_session: &IncrCompSession) -> PathBuf {
156    in_incr_comp_dir_sess(incr_comp_session, WORK_PRODUCTS_FILENAME)
157}
158
159/// Returns the path to a previous session's query cache.
160pub(crate) fn old_query_cache_path(incr_comp_session: &IncrCompSession) -> Option<PathBuf> {
161    in_old_incr_comp_dir_sess(incr_comp_session, QUERY_CACHE_FILENAME)
162}
163
164/// Returns the path to a session's query cache.
165pub(crate) fn query_cache_path(incr_comp_session: &IncrCompSession) -> PathBuf {
166    in_incr_comp_dir_sess(incr_comp_session, QUERY_CACHE_FILENAME)
167}
168
169/// Locks a given session directory.
170fn lock_file_path(session_dir: &Path) -> PathBuf {
171    let crate_dir = session_dir.parent().unwrap();
172
173    let directory_name = session_dir
174        .file_name()
175        .unwrap()
176        .to_str()
177        .expect("malformed session dir name: contains non-Unicode characters");
178
179    let dash_indices: Vec<_> = directory_name.match_indices('-').map(|(idx, _)| idx).collect();
180    if dash_indices.len() != 3 {
181        ::rustc_span::macros::bug_impl(None,
    format_args!("Encountered incremental compilation session directory with malformed name: {0}",
        session_dir.display()), Location::caller())bug!(
182            "Encountered incremental compilation session directory with \
183              malformed name: {}",
184            session_dir.display()
185        )
186    }
187
188    crate_dir.join(&directory_name[0..dash_indices[2]]).with_extension(&LOCK_FILE_EXT[1..])
189}
190
191/// Returns the path for a given filename within the incremental compilation directory
192/// in the previous session.
193pub fn in_old_incr_comp_dir_sess(
194    incr_comp_session: &IncrCompSession,
195    file_name: &str,
196) -> Option<PathBuf> {
197    incr_comp_session.old_session_directory.as_ref().map(|dir| dir.join(file_name))
198}
199
200/// Returns the path for a given filename within the incremental compilation directory
201/// in the current session.
202pub fn in_incr_comp_dir_sess(incr_comp_session: &IncrCompSession, file_name: &str) -> PathBuf {
203    incr_comp_session.new_session_directory.join(file_name)
204}
205
206/// Allocates the private session directory.
207///
208/// If the result of this function is `Ok`, we have a valid incremental
209/// compilation session directory. A valid session
210/// directory is one that contains a locked lock file. It may or may not contain
211/// a dep-graph and work products from a previous session.
212///
213/// This always attempts to load a dep-graph from the directory.
214/// If loading fails for some reason, we fallback to a disabled `DepGraph`.
215/// See [`rustc_interface::queries::dep_graph`].
216///
217/// If this function returns an error, it may leave behind an invalid session directory.
218/// The garbage collection will take care of it.
219///
220/// [`rustc_interface::queries::dep_graph`]: ../../rustc_interface/struct.Queries.html#structfield.dep_graph
221pub(crate) fn prepare_session_directory(
222    sess: &Session,
223    crate_name: Symbol,
224    stable_crate_id: StableCrateId,
225) -> IncrCompSession {
226    if !sess.opts.incremental.is_some() {
    ::core::panicking::panic("assertion failed: sess.opts.incremental.is_some()")
};assert!(sess.opts.incremental.is_some());
227
228    let _timer = sess.timer("incr_comp_prepare_session_directory");
229
230    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:230",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(230u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("prepare_session_directory")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("prepare_session_directory");
231
232    // {incr-comp-dir}/{crate-name-and-disambiguator}
233    let crate_dir = crate_path(sess, crate_name, stable_crate_id);
234    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:234",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(234u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("crate-dir: {0}",
                                                    crate_dir.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("crate-dir: {}", crate_dir.display());
235    create_dir(sess, &crate_dir, "crate");
236
237    // Hack: canonicalize the path *after creating the directory*
238    // because, on windows, long paths can cause problems;
239    // canonicalization inserts this weird prefix that makes windows
240    // tolerate long paths.
241    let crate_dir = match try_canonicalize(&crate_dir) {
242        Ok(v) => v,
243        Err(err) => {
244            sess.dcx().emit_fatal(diagnostics::CanonicalizePath { path: crate_dir, err });
245        }
246    };
247
248    // Generate a session directory of the form:
249    //
250    // {incr-comp-dir}/{crate-name-and-disambiguator}/s-{timestamp}-{random}-working
251    let new_session_dir = generate_session_dir_path(&crate_dir);
252    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:252",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(252u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("session-dir: {0}",
                                                    new_session_dir.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("session-dir: {}", new_session_dir.display());
253
254    // Lock the new session directory. If this fails, return an
255    // error without retrying
256    let new_session_directory = lock_directory(sess, &new_session_dir, true /* new_session */)
257        .expect("should emit fatal error on lock fail");
258
259    // Find a suitable source directory to copy from. Ignore those that we
260    // have already tried before.
261    let old_source_directory = find_source_directory(sess, &crate_dir);
262
263    let old_session_directory = if let Some(old_source_directory) = old_source_directory {
264        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:264",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(264u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("attempting to use: {0}",
                                                    old_source_directory.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("attempting to use: {}", old_source_directory.display());
265        Some(old_source_directory)
266    } else {
267        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:267",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(267u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no source directory found. Continuing with empty session directory.")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("no source directory found. Continuing with empty session directory.");
268        None
269    };
270
271    IncrCompSession { old_session_directory, new_session_directory }
272}
273
274/// This function finalizes and thus 'publishes' the session directory by
275/// renaming it to `s-{timestamp}-{svh}` and releasing the file lock.
276/// This must not be called if there have been any compilation errors.
277pub fn finalize_session_directory(
278    sess: &Session,
279    incr_comp_session: Option<IncrCompSession>,
280    svh: Option<Svh>,
281) {
282    if !sess.dcx().has_errors_or_delayed_bugs().is_none() {
    ::core::panicking::panic("assertion failed: sess.dcx().has_errors_or_delayed_bugs().is_none()")
};assert!(sess.dcx().has_errors_or_delayed_bugs().is_none());
283
284    if sess.opts.incremental.is_none() {
285        return;
286    }
287    let mut incr_comp_session = incr_comp_session.unwrap();
288    // The svh is always produced when incr. comp. is enabled.
289    let svh = svh.unwrap();
290
291    let _timer = sess.timer("incr_comp_finalize_session_directory");
292
293    let incr_comp_session_dir = &*incr_comp_session.new_session_directory;
294
295    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:295",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(295u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize_session_directory() - session directory: {0}",
                                                    incr_comp_session_dir.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize_session_directory() - session directory: {}", incr_comp_session_dir.display());
296
297    let mut sub_dir_name = incr_comp_session_dir
298        .file_name()
299        .unwrap()
300        .to_str()
301        .expect("malformed session dir name: contains non-Unicode characters")
302        .to_string();
303
304    // Keep the 's-{timestamp}-{random-number}' prefix, but replace "working" with the SVH of the crate
305    sub_dir_name.truncate(sub_dir_name.len() - "working".len());
306    // Double-check that we kept this: "s-{timestamp}-{random-number}-"
307    if !sub_dir_name.ends_with('-') {
    { ::core::panicking::panic_fmt(format_args!("{0:?}", sub_dir_name)); }
};assert!(sub_dir_name.ends_with('-'), "{:?}", sub_dir_name);
308    if !(sub_dir_name.as_bytes().iter().filter(|b| **b == b'-').count() == 3) {
    ::core::panicking::panic("assertion failed: sub_dir_name.as_bytes().iter().filter(|b| **b == b\'-\').count() == 3")
};assert!(sub_dir_name.as_bytes().iter().filter(|b| **b == b'-').count() == 3);
309
310    // Append the SVH
311    sub_dir_name.push_str(&svh.as_u128().to_base_fixed_len(CASE_INSENSITIVE));
312
313    // Create the full path
314    let new_path = incr_comp_session_dir.parent().unwrap().join(&*sub_dir_name);
315    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:315",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(315u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize_session_directory() - new path: {0}",
                                                    new_path.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize_session_directory() - new path: {}", new_path.display());
316
317    let result = std_fs::rename(incr_comp_session_dir, &new_path).or_else(|e| {
318        if !falsecfg!(windows) || e.kind() != ErrorKind::PermissionDenied {
319            return Err(e);
320        }
321
322        // On ReFS, renaming a directory that contains a hard link to the metadata workproduct file
323        // can fail if it is being used by another process (such as another rustc instance).
324        // As a fallback, we try to replace the hard link with a copy, which should allow the
325        // rename to succeed.
326        // See https://github.com/rust-lang/rust/issues/151181
327        if let Err(err) = replace_hard_link_with_copy(&in_incr_comp_dir_sess(
328            &incr_comp_session,
329            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}",
                WorkProduct::METADATA_WORKPRODUCT_CGU_NAME,
                OutputType::Metadata.extension()))
    })format!(
330                "{}.{}",
331                WorkProduct::METADATA_WORKPRODUCT_CGU_NAME,
332                OutputType::Metadata.extension()
333            ),
334        )) {
335            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:335",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(335u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize_session_directory() - error replacing hard link with copy: {0}",
                                                    err) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize_session_directory() - error replacing hard link with copy: {}", err);
336        }
337
338        rename_path_with_retry(incr_comp_session_dir, &new_path, 3)
339    });
340
341    match result {
342        Ok(_) => {
343            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:343",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(343u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize_session_directory() - directory renamed successfully")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize_session_directory() - directory renamed successfully");
344        }
345        Err(e) => {
346            // Warn about the error. However, no need to abort compilation now.
347            sess.dcx().emit_note(diagnostics::Finalize { path: incr_comp_session_dir, err: e });
348
349            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:349",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(349u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize_session_directory() - error")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize_session_directory() - error");
350        }
351    }
352
353    // Unlock the old session directory now that we will no longer read from it.
354    incr_comp_session.old_session_directory = None;
355
356    let _ = garbage_collect_session_directories(sess, &incr_comp_session);
357}
358
359pub(crate) fn invalidate_old_session_dir(sess: &Session, incr_comp_session: &mut IncrCompSession) {
360    if let Some(old_incr_comp_session_dir) = incr_comp_session.old_session_directory.take() {
361        let res = try {
362            let sess_dir_iterator = old_incr_comp_session_dir.read_dir()?;
363            for entry in sess_dir_iterator {
364                let entry = entry?;
365                safe_remove_file(&entry.path())?
366            }
367        };
368        if let Err(err) = res {
369            sess.dcx().emit_err(diagnostics::DeleteIncompatible {
370                path: (*old_incr_comp_session_dir).to_owned(),
371                err,
372            });
373        }
374    }
375}
376
377/// Generates unique directory path of the form:
378/// {crate_dir}/s-{timestamp}-{random-number}-working
379fn generate_session_dir_path(crate_dir: &Path) -> PathBuf {
380    let timestamp = timestamp_to_string(SystemTime::now());
381    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:381",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(381u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("generate_session_dir_path: timestamp = {0}",
                                                    timestamp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("generate_session_dir_path: timestamp = {}", timestamp);
382    let random_number = rng().next_u32();
383    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:383",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(383u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("generate_session_dir_path: random_number = {0}",
                                                    random_number) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("generate_session_dir_path: random_number = {}", random_number);
384
385    // Chop the first 3 characters off the timestamp. Those 3 bytes will be zero for a while.
386    let (zeroes, timestamp) = timestamp.split_at(3);
387    {
    match (&zeroes, &"000") {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(zeroes, "000");
388    let directory_name =
389        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s-{0}-{1}-working", timestamp,
                random_number.to_base_fixed_len(CASE_INSENSITIVE)))
    })format!("s-{}-{}-working", timestamp, random_number.to_base_fixed_len(CASE_INSENSITIVE));
390    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:390",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(390u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("generate_session_dir_path: directory_name = {0}",
                                                    directory_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("generate_session_dir_path: directory_name = {}", directory_name);
391    let directory_path = crate_dir.join(directory_name);
392    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:392",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(392u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("generate_session_dir_path: directory_path = {0}",
                                                    directory_path.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("generate_session_dir_path: directory_path = {}", directory_path.display());
393    directory_path
394}
395
396fn create_dir(sess: &Session, path: &Path, dir_tag: &str) {
397    match std_fs::create_dir_all(path) {
398        Ok(()) => {
399            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:399",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(399u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} directory created successfully",
                                                    dir_tag) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("{} directory created successfully", dir_tag);
400        }
401        Err(err) => {
402            sess.dcx().emit_fatal(diagnostics::CreateIncrCompDir { tag: dir_tag, path, err })
403        }
404    }
405}
406
407/// Allocate the lock-file, lock it and create the session directory if requested.
408fn lock_directory(
409    sess: &Session,
410    session_dir: &Path,
411    new_session: bool,
412) -> Option<flock::LockedDir> {
413    let lock_file_path = lock_file_path(session_dir);
414    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:414",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(414u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lock_directory() - lock_file: {0}",
                                                    lock_file_path.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("lock_directory() - lock_file: {}", lock_file_path.display());
415
416    match flock::LockedDir::try_lock(
417        session_dir.to_owned(),
418        &lock_file_path,
419        new_session, // create
420        new_session, // exclusive
421    ) {
422        Ok(lock) => {
423            // Now that we have the lock, we can actually create the session
424            // directory
425            if new_session {
426                create_dir(sess, &session_dir, "session");
427            }
428
429            Some(lock)
430        }
431        Err(lock_err) => {
432            let is_unsupported_lock = flock::Lock::error_unsupported(&lock_err);
433            let diag = diagnostics::CreateLock {
434                lock_err,
435                session_dir,
436                is_unsupported_lock,
437                is_cargo: rustc_session::utils::was_invoked_from_cargo(),
438            };
439            if new_session {
440                sess.dcx().emit_fatal(diag);
441            } else {
442                sess.dcx().emit_warn(diag);
443                None
444            }
445        }
446    }
447}
448
449fn delete_session_dir_lock_file(sess: &Session, lock_file_path: &Path) {
450    if let Err(err) = safe_remove_file(lock_file_path) {
451        sess.dcx().emit_warn(diagnostics::DeleteLock { path: lock_file_path, err });
452    }
453}
454
455/// Finds the most recent published session directory.
456fn find_source_directory(sess: &Session, crate_dir: &Path) -> Option<flock::LockedDir> {
457    let iter = crate_dir
458        .read_dir()
459        .unwrap() // FIXME
460        .filter_map(|e| e.ok().map(|e| e.path()));
461
462    find_source_directory_in_iter(iter)
463        .and_then(|session_dir| lock_directory(sess, &session_dir, false /* new_session */))
464}
465
466fn find_source_directory_in_iter<I>(iter: I) -> Option<PathBuf>
467where
468    I: Iterator<Item = PathBuf>,
469{
470    let mut best_candidate = (UNIX_EPOCH, None);
471
472    for session_dir in iter {
473        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:473",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(473u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_source_directory_in_iter - inspecting `{0}`",
                                                    session_dir.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_source_directory_in_iter - inspecting `{}`", session_dir.display());
474
475        let Some(directory_name) = session_dir.file_name().unwrap().to_str() else {
476            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:476",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(476u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_source_directory_in_iter - ignoring")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_source_directory_in_iter - ignoring");
477            continue;
478        };
479
480        if !is_session_directory(&directory_name) || !is_finalized(&directory_name) {
481            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:481",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(481u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_source_directory_in_iter - ignoring")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_source_directory_in_iter - ignoring");
482            continue;
483        }
484
485        let timestamp = match extract_timestamp_from_session_dir(&directory_name) {
486            Ok(timestamp) => timestamp,
487            Err(e) => {
488                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:488",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(488u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unexpected incr-comp session dir: {0}: {1}",
                                                    session_dir.display(), e) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("unexpected incr-comp session dir: {}: {}", session_dir.display(), e);
489                continue;
490            }
491        };
492
493        if timestamp > best_candidate.0 {
494            best_candidate = (timestamp, Some(session_dir.clone()));
495        }
496    }
497
498    best_candidate.1
499}
500
501fn is_finalized(directory_name: &str) -> bool {
502    !directory_name.ends_with("-working")
503}
504
505fn is_session_directory(directory_name: &str) -> bool {
506    directory_name.starts_with("s-") && !directory_name.ends_with(LOCK_FILE_EXT)
507}
508
509fn is_session_directory_lock_file(file_name: &str) -> bool {
510    file_name.starts_with("s-") && file_name.ends_with(LOCK_FILE_EXT)
511}
512
513fn extract_timestamp_from_session_dir(directory_name: &str) -> Result<SystemTime, &'static str> {
514    if !is_session_directory(directory_name) {
515        return Err("not a directory");
516    }
517
518    let dash_indices: Vec<_> = directory_name.match_indices('-').map(|(idx, _)| idx).collect();
519    if dash_indices.len() != 3 {
520        return Err("not three dashes in name");
521    }
522
523    string_to_timestamp(&directory_name[dash_indices[0] + 1..dash_indices[1]])
524}
525
526fn timestamp_to_string(timestamp: SystemTime) -> BaseNString {
527    let duration = timestamp.duration_since(UNIX_EPOCH).unwrap();
528    let micros: u64 = duration.as_micros().try_into().unwrap();
529    micros.to_base_fixed_len(CASE_INSENSITIVE)
530}
531
532fn string_to_timestamp(s: &str) -> Result<SystemTime, &'static str> {
533    let micros_since_unix_epoch = match u64::from_str_radix(s, INT_ENCODE_BASE as u32) {
534        Ok(micros) => micros,
535        Err(_) => return Err("timestamp not an int"),
536    };
537
538    let duration = Duration::from_micros(micros_since_unix_epoch);
539    Ok(UNIX_EPOCH + duration)
540}
541
542fn crate_path(sess: &Session, crate_name: Symbol, stable_crate_id: StableCrateId) -> PathBuf {
543    let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
544
545    let crate_name =
546        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}-{0}",
                stable_crate_id.as_u64().to_base_fixed_len(CASE_INSENSITIVE),
                crate_name))
    })format!("{crate_name}-{}", stable_crate_id.as_u64().to_base_fixed_len(CASE_INSENSITIVE));
547    incr_dir.join(crate_name)
548}
549
550fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool {
551    timestamp < SystemTime::now() - Duration::from_secs(10)
552}
553
554/// Runs garbage collection for the current session.
555pub(crate) fn garbage_collect_session_directories(
556    sess: &Session,
557    incr_comp_session: &IncrCompSession,
558) -> io::Result<()> {
559    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:559",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(559u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - begin")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("garbage_collect_session_directories() - begin");
560
561    let session_directory = &*incr_comp_session.new_session_directory;
562
563    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:563",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(563u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - session directory: {0}",
                                                    session_directory.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
564        "garbage_collect_session_directories() - session directory: {}",
565        session_directory.display()
566    );
567
568    let crate_directory = session_directory.parent().unwrap();
569    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:569",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(569u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - crate directory: {0}",
                                                    crate_directory.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
570        "garbage_collect_session_directories() - crate directory: {}",
571        crate_directory.display()
572    );
573
574    // First do a pass over the crate directory, collecting lock files and
575    // session directories
576    let mut session_directories = FxIndexSet::default();
577    let mut lock_files = UnordSet::default();
578
579    for dir_entry in crate_directory.read_dir()? {
580        let Ok(dir_entry) = dir_entry else {
581            // Ignore any errors
582            continue;
583        };
584
585        let entry_name = dir_entry.file_name();
586        let Some(entry_name) = entry_name.to_str() else {
587            continue;
588        };
589
590        if is_session_directory_lock_file(&entry_name) {
591            lock_files.insert(entry_name.to_string());
592        } else if is_session_directory(&entry_name) {
593            session_directories.insert(entry_name.to_string());
594        } else {
595            // This is something we don't know, leave it alone
596        }
597    }
598    session_directories.sort();
599
600    // Now map from lock files to session directories
601    let lock_file_to_session_dir: UnordMap<String, Option<String>> = lock_files
602        .into_items()
603        .map(|lock_file_name| {
604            if !lock_file_name.ends_with(LOCK_FILE_EXT) {
    ::core::panicking::panic("assertion failed: lock_file_name.ends_with(LOCK_FILE_EXT)")
};assert!(lock_file_name.ends_with(LOCK_FILE_EXT));
605            let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
606            let session_dir = {
607                let dir_prefix = &lock_file_name[0..dir_prefix_end];
608                session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix))
609            };
610            (lock_file_name, session_dir.map(String::clone))
611        })
612        .into();
613
614    // Delete all lock files, that don't have an associated directory. They must
615    // be some kind of leftover
616    for (lock_file_name, directory_name) in
617        lock_file_to_session_dir.items().into_sorted_stable_ord()
618    {
619        if directory_name.is_none() {
620            let Ok(timestamp) = extract_timestamp_from_session_dir(lock_file_name) else {
621                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:621",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(621u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found lock-file with malformed timestamp: {0}",
                                                    crate_directory.join(&lock_file_name).display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
622                    "found lock-file with malformed timestamp: {}",
623                    crate_directory.join(&lock_file_name).display()
624                );
625                // Ignore it
626                continue;
627            };
628
629            let lock_file_path = crate_directory.join(&*lock_file_name);
630
631            if is_old_enough_to_be_collected(timestamp) {
632                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:632",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(632u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - deleting garbage lock file: {0}",
                                                    lock_file_path.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
633                    "garbage_collect_session_directories() - deleting \
634                    garbage lock file: {}",
635                    lock_file_path.display()
636                );
637                delete_session_dir_lock_file(sess, &lock_file_path);
638            } else {
639                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:639",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(639u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - lock file with no session dir not old enough to be collected: {0}",
                                                    lock_file_path.display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
640                    "garbage_collect_session_directories() - lock file with \
641                    no session dir not old enough to be collected: {}",
642                    lock_file_path.display()
643                );
644            }
645        }
646    }
647
648    // Filter out `None` directories
649    let lock_file_to_session_dir: UnordMap<String, String> = lock_file_to_session_dir
650        .into_items()
651        .filter_map(|(lock_file_name, directory_name)| directory_name.map(|n| (lock_file_name, n)))
652        .into();
653
654    // Delete all session directories that don't have a lock file.
655    for directory_name in session_directories {
656        if !lock_file_to_session_dir.items().any(|(_, dir)| *dir == directory_name) {
657            let path = crate_directory.join(directory_name);
658            if let Err(err) = std_fs::remove_dir_all(&path) {
659                sess.dcx().emit_warn(diagnostics::InvalidGcFailed { path: &path, err });
660            }
661        }
662    }
663
664    // Now garbage collect the valid session directories.
665    let deletion_candidates =
666        lock_file_to_session_dir.items().filter_map(|(lock_file_name, directory_name)| {
667            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:667",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(667u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - inspecting: {0}",
                                                    directory_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("garbage_collect_session_directories() - inspecting: {}", directory_name);
668
669            let Ok(timestamp) = extract_timestamp_from_session_dir(directory_name) else {
670                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:670",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(670u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("found session-dir with malformed timestamp: {0}",
                                                    crate_directory.join(directory_name).display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
671                    "found session-dir with malformed timestamp: {}",
672                    crate_directory.join(directory_name).display()
673                );
674                // Ignore it
675                return None;
676            };
677
678            if is_finalized(directory_name) {
679                let lock_file_path = crate_directory.join(lock_file_name);
680                match flock::Lock::try_lock(
681                    &lock_file_path,
682                    false, // don't create the lock-file
683                    true,
684                ) {
685                    // get an exclusive lock
686                    Ok(lock) => {
687                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:687",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(687u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - successfully acquired lock")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
688                            "garbage_collect_session_directories() - \
689                            successfully acquired lock"
690                        );
691                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:691",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(691u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - adding deletion candidate: {0}",
                                                    directory_name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
692                            "garbage_collect_session_directories() - adding \
693                            deletion candidate: {}",
694                            directory_name
695                        );
696
697                        // Note that we are holding on to the lock
698                        return Some((crate_directory.join(directory_name), lock));
699                    }
700                    Err(_) => {
701                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:701",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(701u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - not collecting, still in use")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
702                            "garbage_collect_session_directories() - \
703                            not collecting, still in use"
704                        );
705                    }
706                }
707            } else if is_old_enough_to_be_collected(timestamp) {
708                // When cleaning out "-working" session directories, i.e.
709                // session directories that might still be in use by another
710                // compiler instance, we only look a directories that are
711                // at least ten seconds old. This is supposed to reduce the
712                // chance of deleting a directory in the time window where
713                // the process has allocated the directory but has not yet
714                // acquired the file-lock on it.
715
716                // Try to acquire the directory lock. If we can't, it
717                // means that the owning process is still alive and we
718                // leave this directory alone.
719                let lock_file_path = crate_directory.join(lock_file_name);
720                match flock::Lock::try_lock(
721                    &lock_file_path,
722                    false, // don't create the lock-file
723                    true,
724                ) {
725                    // get an exclusive lock
726                    Ok(lock) => {
727                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:727",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(727u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - successfully acquired lock")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
728                            "garbage_collect_session_directories() - \
729                            successfully acquired lock"
730                        );
731
732                        delete_old(sess, &crate_directory.join(directory_name));
733
734                        // Let's make it explicit that the file lock is released at this point,
735                        // or rather, that we held on to it until here
736                        drop(lock);
737                    }
738                    Err(_) => {
739                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:739",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(739u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - not collecting, still in use")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
740                            "garbage_collect_session_directories() - \
741                            not collecting, still in use"
742                        );
743                    }
744                }
745            } else {
746                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:746",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(746u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - not finalized, not old enough")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
747                    "garbage_collect_session_directories() - not finalized, not \
748                    old enough"
749                );
750            }
751            None
752        });
753
754    // Delete all but the most recent of the candidates
755    deletion_candidates.all(|(path, lock)| {
756        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:756",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(756u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - deleting `{0}`",
                                                    path.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("garbage_collect_session_directories() - deleting `{}`", path.display());
757
758        if let Err(err) = std_fs::remove_dir_all(&path) {
759            sess.dcx().emit_warn(diagnostics::FinalizedGcFailed { path: &path, err });
760        } else {
761            delete_session_dir_lock_file(sess, &lock_file_path(&path));
762        }
763
764        // Let's make it explicit that the file lock is released at this point,
765        // or rather, that we held on to it until here
766        drop(lock);
767        true
768    });
769
770    Ok(())
771}
772
773fn delete_old(sess: &Session, path: &Path) {
774    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs:774",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(774u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::fs"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("garbage_collect_session_directories() - deleting `{0}`",
                                                    path.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("garbage_collect_session_directories() - deleting `{}`", path.display());
775
776    if let Err(err) = std_fs::remove_dir_all(path) {
777        sess.dcx().emit_warn(diagnostics::SessionGcFailed { path, err });
778    } else {
779        delete_session_dir_lock_file(sess, &lock_file_path(path));
780    }
781}
782
783fn safe_remove_file(p: &Path) -> io::Result<()> {
784    match std_fs::remove_file(p) {
785        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
786        result => result,
787    }
788}
789
790// On Windows the compiler would sometimes fail to rename the session directory because
791// the OS thought something was still being accessed in it. So we retry a few times to give
792// the OS time to catch up.
793// See https://github.com/rust-lang/rust/issues/86929.
794fn rename_path_with_retry(from: &Path, to: &Path, mut retries_left: usize) -> std::io::Result<()> {
795    loop {
796        match std_fs::rename(from, to) {
797            Ok(()) => return Ok(()),
798            Err(e) => {
799                if retries_left > 0 && e.kind() == ErrorKind::PermissionDenied {
800                    // Try again after a short waiting period.
801                    std::thread::sleep(Duration::from_millis(50));
802                    retries_left -= 1;
803                } else {
804                    return Err(e);
805                }
806            }
807        }
808    }
809}
810
811/// Turns a hard link of the file at `path` into a copy.
812fn replace_hard_link_with_copy(path: &Path) -> std::io::Result<()> {
813    let tmp_name = path.with_added_extension("tmp");
814
815    // In case a stale temporary file was linked from a previous failed attempt.
816    safe_remove_file(&tmp_name)?;
817
818    std_fs::copy(path, &tmp_name).and_then(|_| std_fs::rename(&tmp_name, path)).inspect_err(|_| {
819        let _ = safe_remove_file(&tmp_name);
820    })
821}