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::{IncrCompSession, WorkProduct};
111use rustc_session::output::OutputType;
112use rustc_session::{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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:230",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:234",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:252",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:264",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:267",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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::new(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    mut incr_comp_session: IncrCompSession,
280    svh: 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    sess.time("serialize_work_products", || {
285        crate::persist::save::save_work_product_index(sess, &incr_comp_session)
286    });
287
288    let _timer = sess.timer("incr_comp_finalize_session_directory");
289
290    let incr_comp_session_dir = &*incr_comp_session.new_session_directory;
291
292    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:292",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(292u32),
                        ::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());
293
294    let mut sub_dir_name = incr_comp_session_dir
295        .file_name()
296        .unwrap()
297        .to_str()
298        .expect("malformed session dir name: contains non-Unicode characters")
299        .to_string();
300
301    // Keep the 's-{timestamp}-{random-number}' prefix, but replace "working" with the SVH of the crate
302    sub_dir_name.truncate(sub_dir_name.len() - "working".len());
303    // Double-check that we kept this: "s-{timestamp}-{random-number}-"
304    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);
305    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);
306
307    // Append the SVH
308    sub_dir_name.push_str(&svh.as_u128().to_base_fixed_len(CASE_INSENSITIVE));
309
310    // Create the full path
311    let new_path = incr_comp_session_dir.parent().unwrap().join(&*sub_dir_name);
312    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:312",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(312u32),
                        ::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());
313
314    let result = std_fs::rename(incr_comp_session_dir, &new_path).or_else(|e| {
315        if !falsecfg!(windows) || e.kind() != ErrorKind::PermissionDenied {
316            return Err(e);
317        }
318
319        // On ReFS, renaming a directory that contains a hard link to the metadata workproduct file
320        // can fail if it is being used by another process (such as another rustc instance).
321        // As a fallback, we try to replace the hard link with a copy, which should allow the
322        // rename to succeed.
323        // See https://github.com/rust-lang/rust/issues/151181
324        if let Err(err) = replace_hard_link_with_copy(&in_incr_comp_dir_sess(
325            &incr_comp_session,
326            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}",
                WorkProduct::METADATA_WORKPRODUCT_CGU_NAME,
                OutputType::Metadata.extension()))
    })format!(
327                "{}.{}",
328                WorkProduct::METADATA_WORKPRODUCT_CGU_NAME,
329                OutputType::Metadata.extension()
330            ),
331        )) {
332            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:332",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(332u32),
                        ::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);
333        }
334
335        rename_path_with_retry(incr_comp_session_dir, &new_path, 3)
336    });
337
338    match result {
339        Ok(_) => {
340            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:340",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(340u32),
                        ::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");
341        }
342        Err(e) => {
343            // Warn about the error. However, no need to abort compilation now.
344            sess.dcx().emit_note(diagnostics::Finalize { path: incr_comp_session_dir, err: e });
345
346            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:346",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(346u32),
                        ::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");
347        }
348    }
349
350    // Unlock the old session directory now that we will no longer read from it.
351    incr_comp_session.old_session_directory = None;
352
353    let _ = garbage_collect_session_directories(sess, &incr_comp_session);
354}
355
356pub(crate) fn invalidate_old_session_dir(sess: &Session, incr_comp_session: &mut IncrCompSession) {
357    if let Some(old_incr_comp_session_dir) = incr_comp_session.old_session_directory.take() {
358        let res = try {
359            let sess_dir_iterator = old_incr_comp_session_dir.read_dir()?;
360            for entry in sess_dir_iterator {
361                let entry = entry?;
362                safe_remove_file(&entry.path())?
363            }
364        };
365        if let Err(err) = res {
366            sess.dcx().emit_err(diagnostics::DeleteIncompatible {
367                path: (*old_incr_comp_session_dir).to_owned(),
368                err,
369            });
370        }
371    }
372}
373
374/// Generates unique directory path of the form:
375/// {crate_dir}/s-{timestamp}-{random-number}-working
376fn generate_session_dir_path(crate_dir: &Path) -> PathBuf {
377    let timestamp = timestamp_to_string(SystemTime::now());
378    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:378",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(378u32),
                        ::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);
379    let random_number = rng().next_u32();
380    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:380",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(380u32),
                        ::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);
381
382    // Chop the first 3 characters off the timestamp. Those 3 bytes will be zero for a while.
383    let (zeroes, timestamp) = timestamp.split_at(3);
384    {
    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");
385    let directory_name =
386        ::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));
387    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:387",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(387u32),
                        ::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);
388    let directory_path = crate_dir.join(directory_name);
389    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:389",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(389u32),
                        ::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());
390    directory_path
391}
392
393fn create_dir(sess: &Session, path: &Path, dir_tag: &str) {
394    match std_fs::create_dir_all(path) {
395        Ok(()) => {
396            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:396",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(396u32),
                        ::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);
397        }
398        Err(err) => {
399            sess.dcx().emit_fatal(diagnostics::CreateIncrCompDir { tag: dir_tag, path, err })
400        }
401    }
402}
403
404/// Allocate the lock-file, lock it and create the session directory if requested.
405fn lock_directory(
406    sess: &Session,
407    session_dir: &Path,
408    new_session: bool,
409) -> Option<flock::LockedDir> {
410    let lock_file_path = lock_file_path(session_dir);
411    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:411",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(411u32),
                        ::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());
412
413    match flock::LockedDir::try_lock(
414        session_dir.to_owned(),
415        &lock_file_path,
416        new_session, // create
417        new_session, // exclusive
418    ) {
419        Ok(lock) => {
420            // Now that we have the lock, we can actually create the session
421            // directory
422            if new_session {
423                create_dir(sess, &session_dir, "session");
424            }
425
426            Some(lock)
427        }
428        Err(lock_err) => {
429            let is_unsupported_lock = flock::Lock::error_unsupported(&lock_err);
430            let diag = diagnostics::CreateLock {
431                lock_err,
432                session_dir,
433                is_unsupported_lock,
434                is_cargo: rustc_session::utils::was_invoked_from_cargo(),
435            };
436            if new_session {
437                sess.dcx().emit_fatal(diag);
438            } else {
439                sess.dcx().emit_warn(diag);
440                None
441            }
442        }
443    }
444}
445
446fn delete_session_dir_lock_file(sess: &Session, lock_file_path: &Path) {
447    if let Err(err) = safe_remove_file(lock_file_path) {
448        sess.dcx().emit_warn(diagnostics::DeleteLock { path: lock_file_path, err });
449    }
450}
451
452/// Finds the most recent published session directory.
453fn find_source_directory(sess: &Session, crate_dir: &Path) -> Option<flock::LockedDir> {
454    let iter = crate_dir
455        .read_dir()
456        .unwrap() // FIXME
457        .filter_map(|e| e.ok().map(|e| e.path()));
458
459    find_source_directory_in_iter(iter)
460        .and_then(|session_dir| lock_directory(sess, &session_dir, false /* new_session */))
461}
462
463fn find_source_directory_in_iter<I>(iter: I) -> Option<PathBuf>
464where
465    I: Iterator<Item = PathBuf>,
466{
467    let mut best_candidate = (UNIX_EPOCH, None);
468
469    for session_dir in iter {
470        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:470",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(470u32),
                        ::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());
471
472        let Some(directory_name) = session_dir.file_name().unwrap().to_str() else {
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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:473",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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 - ignoring")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("find_source_directory_in_iter - ignoring");
474            continue;
475        };
476
477        if !is_session_directory(&directory_name) || !is_finalized(&directory_name) {
478            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:478",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(478u32),
                        ::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");
479            continue;
480        }
481
482        let timestamp = match extract_timestamp_from_session_dir(&directory_name) {
483            Ok(timestamp) => timestamp,
484            Err(e) => {
485                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:485",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(485u32),
                        ::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);
486                continue;
487            }
488        };
489
490        if timestamp > best_candidate.0 {
491            best_candidate = (timestamp, Some(session_dir.clone()));
492        }
493    }
494
495    best_candidate.1
496}
497
498fn is_finalized(directory_name: &str) -> bool {
499    !directory_name.ends_with("-working")
500}
501
502fn is_session_directory(directory_name: &str) -> bool {
503    directory_name.starts_with("s-") && !directory_name.ends_with(LOCK_FILE_EXT)
504}
505
506fn is_session_directory_lock_file(file_name: &str) -> bool {
507    file_name.starts_with("s-") && file_name.ends_with(LOCK_FILE_EXT)
508}
509
510fn extract_timestamp_from_session_dir(directory_name: &str) -> Result<SystemTime, &'static str> {
511    if !is_session_directory(directory_name) {
512        return Err("not a directory");
513    }
514
515    let dash_indices: Vec<_> = directory_name.match_indices('-').map(|(idx, _)| idx).collect();
516    if dash_indices.len() != 3 {
517        return Err("not three dashes in name");
518    }
519
520    string_to_timestamp(&directory_name[dash_indices[0] + 1..dash_indices[1]])
521}
522
523fn timestamp_to_string(timestamp: SystemTime) -> BaseNString {
524    let duration = timestamp.duration_since(UNIX_EPOCH).unwrap();
525    let micros: u64 = duration.as_micros().try_into().unwrap();
526    micros.to_base_fixed_len(CASE_INSENSITIVE)
527}
528
529fn string_to_timestamp(s: &str) -> Result<SystemTime, &'static str> {
530    let micros_since_unix_epoch = match u64::from_str_radix(s, INT_ENCODE_BASE as u32) {
531        Ok(micros) => micros,
532        Err(_) => return Err("timestamp not an int"),
533    };
534
535    let duration = Duration::from_micros(micros_since_unix_epoch);
536    Ok(UNIX_EPOCH + duration)
537}
538
539fn crate_path(sess: &Session, crate_name: Symbol, stable_crate_id: StableCrateId) -> PathBuf {
540    let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
541
542    let crate_name =
543        ::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));
544    incr_dir.join(crate_name)
545}
546
547fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool {
548    timestamp < SystemTime::now() - Duration::from_secs(10)
549}
550
551/// Runs garbage collection for the current session.
552pub(crate) fn garbage_collect_session_directories(
553    sess: &Session,
554    incr_comp_session: &IncrCompSession,
555) -> io::Result<()> {
556    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:556",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(556u32),
                        ::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");
557
558    let session_directory = &*incr_comp_session.new_session_directory;
559
560    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:560",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(560u32),
                        ::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!(
561        "garbage_collect_session_directories() - session directory: {}",
562        session_directory.display()
563    );
564
565    let crate_directory = session_directory.parent().unwrap();
566    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:566",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(566u32),
                        ::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!(
567        "garbage_collect_session_directories() - crate directory: {}",
568        crate_directory.display()
569    );
570
571    // First do a pass over the crate directory, collecting lock files and
572    // session directories
573    let mut session_directories = FxIndexSet::default();
574    let mut lock_files = UnordSet::default();
575
576    for dir_entry in crate_directory.read_dir()? {
577        let Ok(dir_entry) = dir_entry else {
578            // Ignore any errors
579            continue;
580        };
581
582        let entry_name = dir_entry.file_name();
583        let Some(entry_name) = entry_name.to_str() else {
584            continue;
585        };
586
587        if is_session_directory_lock_file(&entry_name) {
588            lock_files.insert(entry_name.to_string());
589        } else if is_session_directory(&entry_name) {
590            session_directories.insert(entry_name.to_string());
591        } else {
592            // This is something we don't know, leave it alone
593        }
594    }
595    session_directories.sort();
596
597    // Now map from lock files to session directories
598    let lock_file_to_session_dir: UnordMap<String, Option<String>> = lock_files
599        .into_items()
600        .map(|lock_file_name| {
601            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));
602            let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
603            let session_dir = {
604                let dir_prefix = &lock_file_name[0..dir_prefix_end];
605                session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix))
606            };
607            (lock_file_name, session_dir.map(String::clone))
608        })
609        .into();
610
611    // Delete all lock files, that don't have an associated directory. They must
612    // be some kind of leftover
613    for (lock_file_name, directory_name) in
614        lock_file_to_session_dir.items().into_sorted_stable_ord()
615    {
616        if directory_name.is_none() {
617            let Ok(timestamp) = extract_timestamp_from_session_dir(lock_file_name) else {
618                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:618",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(618u32),
                        ::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!(
619                    "found lock-file with malformed timestamp: {}",
620                    crate_directory.join(&lock_file_name).display()
621                );
622                // Ignore it
623                continue;
624            };
625
626            let lock_file_path = crate_directory.join(&*lock_file_name);
627
628            if is_old_enough_to_be_collected(timestamp) {
629                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:629",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(629u32),
                        ::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!(
630                    "garbage_collect_session_directories() - deleting \
631                    garbage lock file: {}",
632                    lock_file_path.display()
633                );
634                delete_session_dir_lock_file(sess, &lock_file_path);
635            } else {
636                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:636",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(636u32),
                        ::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!(
637                    "garbage_collect_session_directories() - lock file with \
638                    no session dir not old enough to be collected: {}",
639                    lock_file_path.display()
640                );
641            }
642        }
643    }
644
645    // Filter out `None` directories
646    let lock_file_to_session_dir: UnordMap<String, String> = lock_file_to_session_dir
647        .into_items()
648        .filter_map(|(lock_file_name, directory_name)| directory_name.map(|n| (lock_file_name, n)))
649        .into();
650
651    // Delete all session directories that don't have a lock file.
652    for directory_name in session_directories {
653        if !lock_file_to_session_dir.items().any(|(_, dir)| *dir == directory_name) {
654            let path = crate_directory.join(directory_name);
655            if let Err(err) = std_fs::remove_dir_all(&path) {
656                sess.dcx().emit_warn(diagnostics::InvalidGcFailed { path: &path, err });
657            }
658        }
659    }
660
661    // Now garbage collect the valid session directories.
662    let deletion_candidates =
663        lock_file_to_session_dir.items().filter_map(|(lock_file_name, directory_name)| {
664            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:664",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(664u32),
                        ::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);
665
666            let Ok(timestamp) = extract_timestamp_from_session_dir(directory_name) else {
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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:667",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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!("found session-dir with malformed timestamp: {0}",
                                                    crate_directory.join(directory_name).display()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
668                    "found session-dir with malformed timestamp: {}",
669                    crate_directory.join(directory_name).display()
670                );
671                // Ignore it
672                return None;
673            };
674
675            if is_finalized(directory_name) {
676                let lock_file_path = crate_directory.join(lock_file_name);
677                match flock::Lock::try_lock(
678                    &lock_file_path,
679                    false, // don't create the lock-file
680                    true,
681                ) {
682                    // get an exclusive lock
683                    Ok(lock) => {
684                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:684",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(684u32),
                        ::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!(
685                            "garbage_collect_session_directories() - \
686                            successfully acquired lock"
687                        );
688                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:688",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(688u32),
                        ::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!(
689                            "garbage_collect_session_directories() - adding \
690                            deletion candidate: {}",
691                            directory_name
692                        );
693
694                        // Note that we are holding on to the lock
695                        return Some((crate_directory.join(directory_name), lock));
696                    }
697                    Err(_) => {
698                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:698",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(698u32),
                        ::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!(
699                            "garbage_collect_session_directories() - \
700                            not collecting, still in use"
701                        );
702                    }
703                }
704            } else if is_old_enough_to_be_collected(timestamp) {
705                // When cleaning out "-working" session directories, i.e.
706                // session directories that might still be in use by another
707                // compiler instance, we only look a directories that are
708                // at least ten seconds old. This is supposed to reduce the
709                // chance of deleting a directory in the time window where
710                // the process has allocated the directory but has not yet
711                // acquired the file-lock on it.
712
713                // Try to acquire the directory lock. If we can't, it
714                // means that the owning process is still alive and we
715                // leave this directory alone.
716                let lock_file_path = crate_directory.join(lock_file_name);
717                match flock::Lock::try_lock(
718                    &lock_file_path,
719                    false, // don't create the lock-file
720                    true,
721                ) {
722                    // get an exclusive lock
723                    Ok(lock) => {
724                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:724",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(724u32),
                        ::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!(
725                            "garbage_collect_session_directories() - \
726                            successfully acquired lock"
727                        );
728
729                        delete_old(sess, &crate_directory.join(directory_name));
730
731                        // Let's make it explicit that the file lock is released at this point,
732                        // or rather, that we held on to it until here
733                        drop(lock);
734                    }
735                    Err(_) => {
736                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:736",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(736u32),
                        ::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!(
737                            "garbage_collect_session_directories() - \
738                            not collecting, still in use"
739                        );
740                    }
741                }
742            } else {
743                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:743",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(743u32),
                        ::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!(
744                    "garbage_collect_session_directories() - not finalized, not \
745                    old enough"
746                );
747            }
748            None
749        });
750
751    // Delete all but the most recent of the candidates
752    deletion_candidates.all(|(path, lock)| {
753        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:753",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(753u32),
                        ::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());
754
755        if let Err(err) = std_fs::remove_dir_all(&path) {
756            sess.dcx().emit_warn(diagnostics::FinalizedGcFailed { path: &path, err });
757        } else {
758            delete_session_dir_lock_file(sess, &lock_file_path(&path));
759        }
760
761        // Let's make it explicit that the file lock is released at this point,
762        // or rather, that we held on to it until here
763        drop(lock);
764        true
765    });
766
767    Ok(())
768}
769
770fn delete_old(sess: &Session, path: &Path) {
771    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs:771",
                        "rustc_incremental::persist::fs", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_incremental/src/persist/fs.rs"),
                        ::tracing_core::__macro_support::Option::Some(771u32),
                        ::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());
772
773    if let Err(err) = std_fs::remove_dir_all(path) {
774        sess.dcx().emit_warn(diagnostics::SessionGcFailed { path, err });
775    } else {
776        delete_session_dir_lock_file(sess, &lock_file_path(path));
777    }
778}
779
780fn safe_remove_file(p: &Path) -> io::Result<()> {
781    match std_fs::remove_file(p) {
782        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
783        result => result,
784    }
785}
786
787// On Windows the compiler would sometimes fail to rename the session directory because
788// the OS thought something was still being accessed in it. So we retry a few times to give
789// the OS time to catch up.
790// See https://github.com/rust-lang/rust/issues/86929.
791fn rename_path_with_retry(from: &Path, to: &Path, mut retries_left: usize) -> std::io::Result<()> {
792    loop {
793        match std_fs::rename(from, to) {
794            Ok(()) => return Ok(()),
795            Err(e) => {
796                if retries_left > 0 && e.kind() == ErrorKind::PermissionDenied {
797                    // Try again after a short waiting period.
798                    std::thread::sleep(Duration::from_millis(50));
799                    retries_left -= 1;
800                } else {
801                    return Err(e);
802                }
803            }
804        }
805    }
806}
807
808/// Turns a hard link of the file at `path` into a copy.
809fn replace_hard_link_with_copy(path: &Path) -> std::io::Result<()> {
810    let tmp_name = path.with_added_extension("tmp");
811
812    // In case a stale temporary file was linked from a previous failed attempt.
813    safe_remove_file(&tmp_name)?;
814
815    std_fs::copy(path, &tmp_name).and_then(|_| std_fs::rename(&tmp_name, path)).inspect_err(|_| {
816        let _ = safe_remove_file(&tmp_name);
817    })
818}