]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/persist/fs.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / librustc_incremental / persist / fs.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 //! This module manages how the incremental compilation cache is represented in
13 //! the file system.
14 //!
15 //! Incremental compilation caches are managed according to a copy-on-write
16 //! strategy: Once a complete, consistent cache version is finalized, it is
17 //! never modified. Instead, when a subsequent compilation session is started,
18 //! the compiler will allocate a new version of the cache that starts out as
19 //! a copy of the previous version. Then only this new copy is modified and it
20 //! will not be visible to other processes until it is finalized. This ensures
21 //! that multiple compiler processes can be executed concurrently for the same
22 //! crate without interfering with each other or blocking each other.
23 //!
24 //! More concretely this is implemented via the following protocol:
25 //!
26 //! 1. For a newly started compilation session, the compiler allocates a
27 //!    new `session` directory within the incremental compilation directory.
28 //!    This session directory will have a unique name that ends with the suffix
29 //!    "-working" and that contains a creation timestamp.
30 //! 2. Next, the compiler looks for the newest finalized session directory,
31 //!    that is, a session directory from a previous compilation session that
32 //!    has been marked as valid and consistent. A session directory is
33 //!    considered finalized if the "-working" suffix in the directory name has
34 //!    been replaced by the SVH of the crate.
35 //! 3. Once the compiler has found a valid, finalized session directory, it will
36 //!    hard-link/copy its contents into the new "-working" directory. If all
37 //!    goes well, it will have its own, private copy of the source directory and
38 //!    subsequently not have to worry about synchronizing with other compiler
39 //!    processes.
40 //! 4. Now the compiler can do its normal compilation process, which involves
41 //!    reading and updating its private session directory.
42 //! 5. When compilation finishes without errors, the private session directory
43 //!    will be in a state where it can be used as input for other compilation
44 //!    sessions. That is, it will contain a dependency graph and cache artifacts
45 //!    that are consistent with the state of the source code it was compiled
46 //!    from, with no need to change them ever again. At this point, the compiler
47 //!    finalizes and "publishes" its private session directory by renaming it
48 //!    from "s-{timestamp}-{random}-working" to "s-{timestamp}-{SVH}".
49 //! 6. At this point the "old" session directory that we copied our data from
50 //!    at the beginning of the session has become obsolete because we have just
51 //!    published a more current version. Thus the compiler will delete it.
52 //!
53 //! ## Garbage Collection
54 //!
55 //! Naively following the above protocol might lead to old session directories
56 //! piling up if a compiler instance crashes for some reason before its able to
57 //! remove its private session directory. In order to avoid wasting disk space,
58 //! the compiler also does some garbage collection each time it is started in
59 //! incremental compilation mode. Specifically, it will scan the incremental
60 //! compilation directory for private session directories that are not in use
61 //! any more and will delete those. It will also delete any finalized session
62 //! directories for a given crate except for the most recent one.
63 //!
64 //! ## Synchronization
65 //!
66 //! There is some synchronization needed in order for the compiler to be able to
67 //! determine whether a given private session directory is not in used any more.
68 //! This is done by creating a lock file for each session directory and
69 //! locking it while the directory is still being used. Since file locks have
70 //! operating system support, we can rely on the lock being released if the
71 //! compiler process dies for some unexpected reason. Thus, when garbage
72 //! collecting private session directories, the collecting process can determine
73 //! whether the directory is still in use by trying to acquire a lock on the
74 //! file. If locking the file fails, the original process must still be alive.
75 //! If locking the file succeeds, we know that the owning process is not alive
76 //! any more and we can safely delete the directory.
77 //! There is still a small time window between the original process creating the
78 //! lock file and actually locking it. In order to minimize the chance that
79 //! another process tries to acquire the lock in just that instance, only
80 //! session directories that are older than a few seconds are considered for
81 //! garbage collection.
82 //!
83 //! Another case that has to be considered is what happens if one process
84 //! deletes a finalized session directory that another process is currently
85 //! trying to copy from. This case is also handled via the lock file. Before
86 //! a process starts copying a finalized session directory, it will acquire a
87 //! shared lock on the directory's lock file. Any garbage collecting process,
88 //! on the other hand, will acquire an exclusive lock on the lock file.
89 //! Thus, if a directory is being collected, any reader process will fail
90 //! acquiring the shared lock and will leave the directory alone. Conversely,
91 //! if a collecting process can't acquire the exclusive lock because the
92 //! directory is currently being read from, it will leave collecting that
93 //! directory to another process at a later point in time.
94 //! The exact same scheme is also used when reading the metadata hashes file
95 //! from an extern crate. When a crate is compiled, the hash values of its
96 //! metadata are stored in a file in its session directory. When the
97 //! compilation session of another crate imports the first crate's metadata,
98 //! it also has to read in the accompanying metadata hashes. It thus will access
99 //! the finalized session directory of all crates it links to and while doing
100 //! so, it will also place a read lock on that the respective session directory
101 //! so that it won't be deleted while the metadata hashes are loaded.
102 //!
103 //! ## Preconditions
104 //!
105 //! This system relies on two features being available in the file system in
106 //! order to work really well: file locking and hard linking.
107 //! If hard linking is not available (like on FAT) the data in the cache
108 //! actually has to be copied at the beginning of each session.
109 //! If file locking does not work reliably (like on NFS), some of the
110 //! synchronization will go haywire.
111 //! In both cases we recommend to locate the incremental compilation directory
112 //! on a file system that supports these things.
113 //! It might be a good idea though to try and detect whether we are on an
114 //! unsupported file system and emit a warning in that case. This is not yet
115 //! implemented.
116
117 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
118 use rustc::hir::svh::Svh;
119 use rustc::session::Session;
120 use rustc::ty::TyCtxt;
121 use rustc::util::fs as fs_util;
122 use rustc_data_structures::{flock, base_n};
123 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
124
125 use std::ffi::OsString;
126 use std::fs as std_fs;
127 use std::io;
128 use std::mem;
129 use std::path::{Path, PathBuf};
130 use std::time::{UNIX_EPOCH, SystemTime, Duration};
131 use std::__rand::{thread_rng, Rng};
132
133 const LOCK_FILE_EXT: &'static str = ".lock";
134 const DEP_GRAPH_FILENAME: &'static str = "dep-graph.bin";
135 const WORK_PRODUCTS_FILENAME: &'static str = "work-products.bin";
136 const METADATA_HASHES_FILENAME: &'static str = "metadata.bin";
137
138 // We encode integers using the following base, so they are shorter than decimal
139 // or hexadecimal numbers (we want short file and directory names). Since these
140 // numbers will be used in file names, we choose an encoding that is not
141 // case-sensitive (as opposed to base64, for example).
142 const INT_ENCODE_BASE: u64 = 36;
143
144 pub fn dep_graph_path(sess: &Session) -> PathBuf {
145     in_incr_comp_dir_sess(sess, DEP_GRAPH_FILENAME)
146 }
147
148 pub fn work_products_path(sess: &Session) -> PathBuf {
149     in_incr_comp_dir_sess(sess, WORK_PRODUCTS_FILENAME)
150 }
151
152 pub fn metadata_hash_export_path(sess: &Session) -> PathBuf {
153     in_incr_comp_dir_sess(sess, METADATA_HASHES_FILENAME)
154 }
155
156 pub fn metadata_hash_import_path(import_session_dir: &Path) -> PathBuf {
157     import_session_dir.join(METADATA_HASHES_FILENAME)
158 }
159
160 pub fn lock_file_path(session_dir: &Path) -> PathBuf {
161     let crate_dir = session_dir.parent().unwrap();
162
163     let directory_name = session_dir.file_name().unwrap().to_string_lossy();
164     assert_no_characters_lost(&directory_name);
165
166     let dash_indices: Vec<_> = directory_name.match_indices("-")
167                                              .map(|(idx, _)| idx)
168                                              .collect();
169     if dash_indices.len() != 3 {
170         bug!("Encountered incremental compilation session directory with \
171               malformed name: {}",
172              session_dir.display())
173     }
174
175     crate_dir.join(&directory_name[0 .. dash_indices[2]])
176              .with_extension(&LOCK_FILE_EXT[1..])
177 }
178
179 pub fn in_incr_comp_dir_sess(sess: &Session, file_name: &str) -> PathBuf {
180     in_incr_comp_dir(&sess.incr_comp_session_dir(), file_name)
181 }
182
183 pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBuf {
184     incr_comp_session_dir.join(file_name)
185 }
186
187 /// Allocates the private session directory. The boolean in the Ok() result
188 /// indicates whether we should try loading a dep graph from the successfully
189 /// initialized directory, or not.
190 /// The post-condition of this fn is that we have a valid incremental
191 /// compilation session directory, if the result is `Ok`. A valid session
192 /// directory is one that contains a locked lock file. It may or may not contain
193 /// a dep-graph and work products from a previous session.
194 /// If the call fails, the fn may leave behind an invalid session directory.
195 /// The garbage collection will take care of it.
196 pub fn prepare_session_directory(tcx: TyCtxt) -> Result<bool, ()> {
197     debug!("prepare_session_directory");
198
199     // {incr-comp-dir}/{crate-name-and-disambiguator}
200     let crate_dir = crate_path_tcx(tcx, LOCAL_CRATE);
201     debug!("crate-dir: {}", crate_dir.display());
202     try!(create_dir(tcx.sess, &crate_dir, "crate"));
203
204     // Hack: canonicalize the path *after creating the directory*
205     // because, on windows, long paths can cause problems;
206     // canonicalization inserts this weird prefix that makes windows
207     // tolerate long paths.
208     let crate_dir = match crate_dir.canonicalize() {
209         Ok(v) => v,
210         Err(err) => {
211             tcx.sess.err(&format!("incremental compilation: error canonicalizing path `{}`: {}",
212                                   crate_dir.display(), err));
213             return Err(());
214         }
215     };
216
217     let mut source_directories_already_tried = FxHashSet();
218
219     loop {
220         // Generate a session directory of the form:
221         //
222         // {incr-comp-dir}/{crate-name-and-disambiguator}/s-{timestamp}-{random}-working
223         let session_dir = generate_session_dir_path(&crate_dir);
224         debug!("session-dir: {}", session_dir.display());
225
226         // Lock the new session directory. If this fails, return an
227         // error without retrying
228         let (directory_lock, lock_file_path) = try!(lock_directory(tcx.sess, &session_dir));
229
230         // Now that we have the lock, we can actually create the session
231         // directory
232         try!(create_dir(tcx.sess, &session_dir, "session"));
233
234         // Find a suitable source directory to copy from. Ignore those that we
235         // have already tried before.
236         let source_directory = find_source_directory(&crate_dir,
237                                                      &source_directories_already_tried);
238
239         let source_directory = if let Some(dir) = source_directory {
240             dir
241         } else {
242             // There's nowhere to copy from, we're done
243             debug!("no source directory found. Continuing with empty session \
244                     directory.");
245
246             tcx.sess.init_incr_comp_session(session_dir, directory_lock);
247             return Ok(false)
248         };
249
250         debug!("attempting to copy data from source: {}",
251                source_directory.display());
252
253         let print_file_copy_stats = tcx.sess.opts.debugging_opts.incremental_info;
254
255         // Try copying over all files from the source directory
256         if let Ok(allows_links) = copy_files(&session_dir, &source_directory,
257                                              print_file_copy_stats) {
258             debug!("successfully copied data from: {}",
259                    source_directory.display());
260
261             if !allows_links {
262                 tcx.sess.warn(&format!("Hard linking files in the incremental \
263                                         compilation cache failed. Copying files \
264                                         instead. Consider moving the cache \
265                                         directory to a file system which supports \
266                                         hard linking in session dir `{}`",
267                                         session_dir.display())
268                     );
269             }
270
271             tcx.sess.init_incr_comp_session(session_dir, directory_lock);
272             return Ok(true)
273         } else {
274              debug!("copying failed - trying next directory");
275
276             // Something went wrong while trying to copy/link files from the
277             // source directory. Try again with a different one.
278             source_directories_already_tried.insert(source_directory);
279
280             // Try to remove the session directory we just allocated. We don't
281             // know if there's any garbage in it from the failed copy action.
282             if let Err(err) = safe_remove_dir_all(&session_dir) {
283                 tcx.sess.warn(&format!("Failed to delete partly initialized \
284                                         session dir `{}`: {}",
285                                        session_dir.display(),
286                                        err));
287             }
288
289             delete_session_dir_lock_file(tcx.sess, &lock_file_path);
290             mem::drop(directory_lock);
291         }
292     }
293 }
294
295
296 /// This function finalizes and thus 'publishes' the session directory by
297 /// renaming it to `s-{timestamp}-{svh}` and releasing the file lock.
298 /// If there have been compilation errors, however, this function will just
299 /// delete the presumably invalid session directory.
300 pub fn finalize_session_directory(sess: &Session, svh: Svh) {
301     if sess.opts.incremental.is_none() {
302         return;
303     }
304
305     let incr_comp_session_dir: PathBuf = sess.incr_comp_session_dir().clone();
306
307     if sess.has_errors() {
308         // If there have been any errors during compilation, we don't want to
309         // publish this session directory. Rather, we'll just delete it.
310
311         debug!("finalize_session_directory() - invalidating session directory: {}",
312                 incr_comp_session_dir.display());
313
314         if let Err(err) = safe_remove_dir_all(&*incr_comp_session_dir) {
315             sess.warn(&format!("Error deleting incremental compilation \
316                                 session directory `{}`: {}",
317                                incr_comp_session_dir.display(),
318                                err));
319         }
320
321         let lock_file_path = lock_file_path(&*incr_comp_session_dir);
322         delete_session_dir_lock_file(sess, &lock_file_path);
323         sess.mark_incr_comp_session_as_invalid();
324     }
325
326     debug!("finalize_session_directory() - session directory: {}",
327             incr_comp_session_dir.display());
328
329     let old_sub_dir_name = incr_comp_session_dir.file_name()
330                                                 .unwrap()
331                                                 .to_string_lossy();
332     assert_no_characters_lost(&old_sub_dir_name);
333
334     // Keep the 's-{timestamp}-{random-number}' prefix, but replace the
335     // '-working' part with the SVH of the crate
336     let dash_indices: Vec<_> = old_sub_dir_name.match_indices("-")
337                                                .map(|(idx, _)| idx)
338                                                .collect();
339     if dash_indices.len() != 3 {
340         bug!("Encountered incremental compilation session directory with \
341               malformed name: {}",
342              incr_comp_session_dir.display())
343     }
344
345     // State: "s-{timestamp}-{random-number}-"
346     let mut new_sub_dir_name = String::from(&old_sub_dir_name[.. dash_indices[2] + 1]);
347
348     // Append the svh
349     base_n::push_str(svh.as_u64(), INT_ENCODE_BASE, &mut new_sub_dir_name);
350
351     // Create the full path
352     let new_path = incr_comp_session_dir.parent().unwrap().join(new_sub_dir_name);
353     debug!("finalize_session_directory() - new path: {}", new_path.display());
354
355     match std_fs::rename(&*incr_comp_session_dir, &new_path) {
356         Ok(_) => {
357             debug!("finalize_session_directory() - directory renamed successfully");
358
359             // This unlocks the directory
360             sess.finalize_incr_comp_session(new_path);
361         }
362         Err(e) => {
363             // Warn about the error. However, no need to abort compilation now.
364             sess.warn(&format!("Error finalizing incremental compilation \
365                                session directory `{}`: {}",
366                                incr_comp_session_dir.display(),
367                                e));
368
369             debug!("finalize_session_directory() - error, marking as invalid");
370             // Drop the file lock, so we can garage collect
371             sess.mark_incr_comp_session_as_invalid();
372         }
373     }
374
375     let _ = garbage_collect_session_directories(sess);
376 }
377
378 pub fn delete_all_session_dir_contents(sess: &Session) -> io::Result<()> {
379     let sess_dir_iterator = sess.incr_comp_session_dir().read_dir()?;
380     for entry in sess_dir_iterator {
381         let entry = entry?;
382         safe_remove_file(&entry.path())?
383     }
384     Ok(())
385 }
386
387 fn copy_files(target_dir: &Path,
388               source_dir: &Path,
389               print_stats_on_success: bool)
390               -> Result<bool, ()> {
391     // We acquire a shared lock on the lock file of the directory, so that
392     // nobody deletes it out from under us while we are reading from it.
393     let lock_file_path = lock_file_path(source_dir);
394     let _lock = if let Ok(lock) = flock::Lock::new(&lock_file_path,
395                                                    false,   // don't wait,
396                                                    false,   // don't create
397                                                    false) { // not exclusive
398         lock
399     } else {
400         // Could not acquire the lock, don't try to copy from here
401         return Err(())
402     };
403
404     let source_dir_iterator = match source_dir.read_dir() {
405         Ok(it) => it,
406         Err(_) => return Err(())
407     };
408
409     let mut files_linked = 0;
410     let mut files_copied = 0;
411
412     for entry in source_dir_iterator {
413         match entry {
414             Ok(entry) => {
415                 let file_name = entry.file_name();
416
417                 let target_file_path = target_dir.join(file_name);
418                 let source_path = entry.path();
419
420                 debug!("copying into session dir: {}", source_path.display());
421                 match fs_util::link_or_copy(source_path, target_file_path) {
422                     Ok(fs_util::LinkOrCopy::Link) => {
423                         files_linked += 1
424                     }
425                     Ok(fs_util::LinkOrCopy::Copy) => {
426                         files_copied += 1
427                     }
428                     Err(_) => return Err(())
429                 }
430             }
431             Err(_) => {
432                 return Err(())
433             }
434         }
435     }
436
437     if print_stats_on_success {
438         println!("incremental: session directory: {} files hard-linked", files_linked);
439         println!("incremental: session directory: {} files copied", files_copied);
440     }
441
442     Ok(files_linked > 0 || files_copied == 0)
443 }
444
445 /// Generate unique directory path of the form:
446 /// {crate_dir}/s-{timestamp}-{random-number}-working
447 fn generate_session_dir_path(crate_dir: &Path) -> PathBuf {
448     let timestamp = timestamp_to_string(SystemTime::now());
449     debug!("generate_session_dir_path: timestamp = {}", timestamp);
450     let random_number = thread_rng().next_u32();
451     debug!("generate_session_dir_path: random_number = {}", random_number);
452
453     let directory_name = format!("s-{}-{}-working",
454                                   timestamp,
455                                   base_n::encode(random_number as u64,
456                                                  INT_ENCODE_BASE));
457     debug!("generate_session_dir_path: directory_name = {}", directory_name);
458     let directory_path = crate_dir.join(directory_name);
459     debug!("generate_session_dir_path: directory_path = {}", directory_path.display());
460     directory_path
461 }
462
463 fn create_dir(sess: &Session, path: &Path, dir_tag: &str) -> Result<(),()> {
464     match std_fs::create_dir_all(path) {
465         Ok(()) => {
466             debug!("{} directory created successfully", dir_tag);
467             Ok(())
468         }
469         Err(err) => {
470             sess.err(&format!("Could not create incremental compilation {} \
471                                directory `{}`: {}",
472                               dir_tag,
473                               path.display(),
474                               err));
475             Err(())
476         }
477     }
478 }
479
480 /// Allocate a the lock-file and lock it.
481 fn lock_directory(sess: &Session,
482                   session_dir: &Path)
483                   -> Result<(flock::Lock, PathBuf), ()> {
484     let lock_file_path = lock_file_path(session_dir);
485     debug!("lock_directory() - lock_file: {}", lock_file_path.display());
486
487     match flock::Lock::new(&lock_file_path,
488                            false, // don't wait
489                            true,  // create the lock file
490                            true) { // the lock should be exclusive
491         Ok(lock) => Ok((lock, lock_file_path)),
492         Err(err) => {
493             sess.err(&format!("incremental compilation: could not create \
494                                session directory lock file: {}", err));
495             Err(())
496         }
497     }
498 }
499
500 fn delete_session_dir_lock_file(sess: &Session,
501                                 lock_file_path: &Path) {
502     if let Err(err) = safe_remove_file(&lock_file_path) {
503         sess.warn(&format!("Error deleting lock file for incremental \
504                             compilation session directory `{}`: {}",
505                            lock_file_path.display(),
506                            err));
507     }
508 }
509
510 /// Find the most recent published session directory that is not in the
511 /// ignore-list.
512 fn find_source_directory(crate_dir: &Path,
513                          source_directories_already_tried: &FxHashSet<PathBuf>)
514                          -> Option<PathBuf> {
515     let iter = crate_dir.read_dir()
516                         .unwrap() // FIXME
517                         .filter_map(|e| e.ok().map(|e| e.path()));
518
519     find_source_directory_in_iter(iter, source_directories_already_tried)
520 }
521
522 fn find_source_directory_in_iter<I>(iter: I,
523                                     source_directories_already_tried: &FxHashSet<PathBuf>)
524                                     -> Option<PathBuf>
525     where I: Iterator<Item=PathBuf>
526 {
527     let mut best_candidate = (UNIX_EPOCH, None);
528
529     for session_dir in iter {
530         debug!("find_source_directory_in_iter - inspecting `{}`",
531                session_dir.display());
532
533         let directory_name = session_dir.file_name().unwrap().to_string_lossy();
534         assert_no_characters_lost(&directory_name);
535
536         if source_directories_already_tried.contains(&session_dir) ||
537            !is_session_directory(&directory_name) ||
538            !is_finalized(&directory_name) {
539             debug!("find_source_directory_in_iter - ignoring.");
540             continue
541         }
542
543         let timestamp = extract_timestamp_from_session_dir(&directory_name)
544             .unwrap_or_else(|_| {
545                 bug!("unexpected incr-comp session dir: {}", session_dir.display())
546             });
547
548         if timestamp > best_candidate.0 {
549             best_candidate = (timestamp, Some(session_dir.clone()));
550         }
551     }
552
553     best_candidate.1
554 }
555
556 fn is_finalized(directory_name: &str) -> bool {
557     !directory_name.ends_with("-working")
558 }
559
560 fn is_session_directory(directory_name: &str) -> bool {
561     directory_name.starts_with("s-") &&
562     !directory_name.ends_with(LOCK_FILE_EXT)
563 }
564
565 fn is_session_directory_lock_file(file_name: &str) -> bool {
566     file_name.starts_with("s-") && file_name.ends_with(LOCK_FILE_EXT)
567 }
568
569 fn extract_timestamp_from_session_dir(directory_name: &str)
570                                       -> Result<SystemTime, ()> {
571     if !is_session_directory(directory_name) {
572         return Err(())
573     }
574
575     let dash_indices: Vec<_> = directory_name.match_indices("-")
576                                              .map(|(idx, _)| idx)
577                                              .collect();
578     if dash_indices.len() != 3 {
579         return Err(())
580     }
581
582     string_to_timestamp(&directory_name[dash_indices[0]+1 .. dash_indices[1]])
583 }
584
585 fn timestamp_to_string(timestamp: SystemTime) -> String {
586     let duration = timestamp.duration_since(UNIX_EPOCH).unwrap();
587     let micros = duration.as_secs() * 1_000_000 +
588                 (duration.subsec_nanos() as u64) / 1000;
589     base_n::encode(micros, INT_ENCODE_BASE)
590 }
591
592 fn string_to_timestamp(s: &str) -> Result<SystemTime, ()> {
593     let micros_since_unix_epoch = u64::from_str_radix(s, 36);
594
595     if micros_since_unix_epoch.is_err() {
596         return Err(())
597     }
598
599     let micros_since_unix_epoch = micros_since_unix_epoch.unwrap();
600
601     let duration = Duration::new(micros_since_unix_epoch / 1_000_000,
602                                  1000 * (micros_since_unix_epoch % 1_000_000) as u32);
603     Ok(UNIX_EPOCH + duration)
604 }
605
606 fn crate_path_tcx(tcx: TyCtxt, cnum: CrateNum) -> PathBuf {
607     crate_path(tcx.sess, &tcx.crate_name(cnum).as_str(), &tcx.crate_disambiguator(cnum).as_str())
608 }
609
610 /// Finds the session directory containing the correct metadata hashes file for
611 /// the given crate. In order to do that it has to compute the crate directory
612 /// of the given crate, and in there, look for the session directory with the
613 /// correct SVH in it.
614 /// Note that we have to match on the exact SVH here, not just the
615 /// crate's (name, disambiguator) pair. The metadata hashes are only valid for
616 /// the exact version of the binary we are reading from now (i.e. the hashes
617 /// are part of the dependency graph of a specific compilation session).
618 pub fn find_metadata_hashes_for(tcx: TyCtxt, cnum: CrateNum) -> Option<PathBuf> {
619     let crate_directory = crate_path_tcx(tcx, cnum);
620
621     if !crate_directory.exists() {
622         return None
623     }
624
625     let dir_entries = match crate_directory.read_dir() {
626         Ok(dir_entries) => dir_entries,
627         Err(e) => {
628             tcx.sess
629                .err(&format!("incremental compilation: Could not read crate directory `{}`: {}",
630                              crate_directory.display(), e));
631             return None
632         }
633     };
634
635     let target_svh = tcx.sess.cstore.crate_hash(cnum);
636     let target_svh = base_n::encode(target_svh.as_u64(), INT_ENCODE_BASE);
637
638     let sub_dir = find_metadata_hashes_iter(&target_svh, dir_entries.filter_map(|e| {
639         e.ok().map(|e| e.file_name().to_string_lossy().into_owned())
640     }));
641
642     sub_dir.map(|sub_dir_name| crate_directory.join(&sub_dir_name))
643 }
644
645 fn find_metadata_hashes_iter<'a, I>(target_svh: &str, iter: I) -> Option<OsString>
646     where I: Iterator<Item=String>
647 {
648     for sub_dir_name in iter {
649         if !is_session_directory(&sub_dir_name) || !is_finalized(&sub_dir_name) {
650             // This is not a usable session directory
651             continue
652         }
653
654         let is_match = if let Some(last_dash_pos) = sub_dir_name.rfind("-") {
655             let candidate_svh = &sub_dir_name[last_dash_pos + 1 .. ];
656             target_svh == candidate_svh
657         } else {
658             // some kind of invalid directory name
659             continue
660         };
661
662         if is_match {
663             return Some(OsString::from(sub_dir_name))
664         }
665     }
666
667     None
668 }
669
670 fn crate_path(sess: &Session,
671               crate_name: &str,
672               crate_disambiguator: &str)
673               -> PathBuf {
674     use std::hash::{Hasher, Hash};
675     use std::collections::hash_map::DefaultHasher;
676
677     let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
678
679     // The full crate disambiguator is really long. A hash of it should be
680     // sufficient.
681     let mut hasher = DefaultHasher::new();
682     crate_disambiguator.hash(&mut hasher);
683
684     let crate_name = format!("{}-{}",
685                              crate_name,
686                              base_n::encode(hasher.finish(), INT_ENCODE_BASE));
687     incr_dir.join(crate_name)
688 }
689
690 fn assert_no_characters_lost(s: &str) {
691     if s.contains('\u{FFFD}') {
692         bug!("Could not losslessly convert '{}'.", s)
693     }
694 }
695
696 fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool {
697     timestamp < SystemTime::now() - Duration::from_secs(10)
698 }
699
700 pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> {
701     debug!("garbage_collect_session_directories() - begin");
702
703     let session_directory = sess.incr_comp_session_dir();
704     debug!("garbage_collect_session_directories() - session directory: {}",
705         session_directory.display());
706
707     let crate_directory = session_directory.parent().unwrap();
708     debug!("garbage_collect_session_directories() - crate directory: {}",
709         crate_directory.display());
710
711     // First do a pass over the crate directory, collecting lock files and
712     // session directories
713     let mut session_directories = FxHashSet();
714     let mut lock_files = FxHashSet();
715
716     for dir_entry in try!(crate_directory.read_dir()) {
717         let dir_entry = match dir_entry {
718             Ok(dir_entry) => dir_entry,
719             _ => {
720                 // Ignore any errors
721                 continue
722             }
723         };
724
725         let entry_name = dir_entry.file_name();
726         let entry_name = entry_name.to_string_lossy();
727
728         if is_session_directory_lock_file(&entry_name) {
729             assert_no_characters_lost(&entry_name);
730             lock_files.insert(entry_name.into_owned());
731         } else if is_session_directory(&entry_name) {
732             assert_no_characters_lost(&entry_name);
733             session_directories.insert(entry_name.into_owned());
734         } else {
735             // This is something we don't know, leave it alone
736         }
737     }
738
739     // Now map from lock files to session directories
740     let lock_file_to_session_dir: FxHashMap<String, Option<String>> =
741         lock_files.into_iter()
742                   .map(|lock_file_name| {
743                         assert!(lock_file_name.ends_with(LOCK_FILE_EXT));
744                         let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
745                         let session_dir = {
746                             let dir_prefix = &lock_file_name[0 .. dir_prefix_end];
747                             session_directories.iter()
748                                                .find(|dir_name| dir_name.starts_with(dir_prefix))
749                         };
750                         (lock_file_name, session_dir.map(String::clone))
751                     })
752                   .collect();
753
754     // Delete all lock files, that don't have an associated directory. They must
755     // be some kind of leftover
756     for (lock_file_name, directory_name) in &lock_file_to_session_dir {
757         if directory_name.is_none() {
758             let timestamp = match extract_timestamp_from_session_dir(lock_file_name) {
759                 Ok(timestamp) => timestamp,
760                 Err(()) => {
761                     debug!("Found lock-file with malformed timestamp: {}",
762                         crate_directory.join(&lock_file_name).display());
763                     // Ignore it
764                     continue
765                 }
766             };
767
768             let lock_file_path = crate_directory.join(&**lock_file_name);
769
770             if is_old_enough_to_be_collected(timestamp) {
771                 debug!("garbage_collect_session_directories() - deleting \
772                         garbage lock file: {}", lock_file_path.display());
773                 delete_session_dir_lock_file(sess, &lock_file_path);
774             } else {
775                 debug!("garbage_collect_session_directories() - lock file with \
776                         no session dir not old enough to be collected: {}",
777                        lock_file_path.display());
778             }
779         }
780     }
781
782     // Filter out `None` directories
783     let lock_file_to_session_dir: FxHashMap<String, String> =
784         lock_file_to_session_dir.into_iter()
785                                 .filter_map(|(lock_file_name, directory_name)| {
786                                     directory_name.map(|n| (lock_file_name, n))
787                                 })
788                                 .collect();
789
790     let mut deletion_candidates = vec![];
791     let mut definitely_delete = vec![];
792
793     for (lock_file_name, directory_name) in &lock_file_to_session_dir {
794         debug!("garbage_collect_session_directories() - inspecting: {}",
795                 directory_name);
796
797         let timestamp = match extract_timestamp_from_session_dir(directory_name) {
798             Ok(timestamp) => timestamp,
799             Err(()) => {
800                 debug!("Found session-dir with malformed timestamp: {}",
801                         crate_directory.join(directory_name).display());
802                 // Ignore it
803                 continue
804             }
805         };
806
807         if is_finalized(directory_name) {
808             let lock_file_path = crate_directory.join(lock_file_name);
809             match flock::Lock::new(&lock_file_path,
810                                    false,  // don't wait
811                                    false,  // don't create the lock-file
812                                    true) { // get an exclusive lock
813                 Ok(lock) => {
814                     debug!("garbage_collect_session_directories() - \
815                             successfully acquired lock");
816                     debug!("garbage_collect_session_directories() - adding \
817                             deletion candidate: {}", directory_name);
818
819                     // Note that we are holding on to the lock
820                     deletion_candidates.push((timestamp,
821                                               crate_directory.join(directory_name),
822                                               Some(lock)));
823                 }
824                 Err(_) => {
825                     debug!("garbage_collect_session_directories() - \
826                             not collecting, still in use");
827                 }
828             }
829         } else if is_old_enough_to_be_collected(timestamp) {
830             // When cleaning out "-working" session directories, i.e.
831             // session directories that might still be in use by another
832             // compiler instance, we only look a directories that are
833             // at least ten seconds old. This is supposed to reduce the
834             // chance of deleting a directory in the time window where
835             // the process has allocated the directory but has not yet
836             // acquired the file-lock on it.
837
838             // Try to acquire the directory lock. If we can't, it
839             // means that the owning process is still alive and we
840             // leave this directory alone.
841             let lock_file_path = crate_directory.join(lock_file_name);
842             match flock::Lock::new(&lock_file_path,
843                                    false,  // don't wait
844                                    false,  // don't create the lock-file
845                                    true) { // get an exclusive lock
846                 Ok(lock) => {
847                     debug!("garbage_collect_session_directories() - \
848                             successfully acquired lock");
849
850                     // Note that we are holding on to the lock
851                     definitely_delete.push((crate_directory.join(directory_name),
852                                             Some(lock)));
853                 }
854                 Err(_) => {
855                     debug!("garbage_collect_session_directories() - \
856                             not collecting, still in use");
857                 }
858             }
859         } else {
860             debug!("garbage_collect_session_directories() - not finalized, not \
861                     old enough");
862         }
863     }
864
865     // Delete all but the most recent of the candidates
866     for (path, lock) in all_except_most_recent(deletion_candidates) {
867         debug!("garbage_collect_session_directories() - deleting `{}`",
868                 path.display());
869
870         if let Err(err) = safe_remove_dir_all(&path) {
871             sess.warn(&format!("Failed to garbage collect finalized incremental \
872                                 compilation session directory `{}`: {}",
873                                path.display(),
874                                err));
875         } else {
876             delete_session_dir_lock_file(sess, &lock_file_path(&path));
877         }
878
879
880         // Let's make it explicit that the file lock is released at this point,
881         // or rather, that we held on to it until here
882         mem::drop(lock);
883     }
884
885     for (path, lock) in definitely_delete {
886         debug!("garbage_collect_session_directories() - deleting `{}`",
887                 path.display());
888
889         if let Err(err) = safe_remove_dir_all(&path) {
890             sess.warn(&format!("Failed to garbage collect incremental \
891                                 compilation session directory `{}`: {}",
892                                path.display(),
893                                err));
894         } else {
895             delete_session_dir_lock_file(sess, &lock_file_path(&path));
896         }
897
898         // Let's make it explicit that the file lock is released at this point,
899         // or rather, that we held on to it until here
900         mem::drop(lock);
901     }
902
903     Ok(())
904 }
905
906 fn all_except_most_recent(deletion_candidates: Vec<(SystemTime, PathBuf, Option<flock::Lock>)>)
907                           -> FxHashMap<PathBuf, Option<flock::Lock>> {
908     let most_recent = deletion_candidates.iter()
909                                          .map(|&(timestamp, ..)| timestamp)
910                                          .max();
911
912     if let Some(most_recent) = most_recent {
913         deletion_candidates.into_iter()
914                            .filter(|&(timestamp, ..)| timestamp != most_recent)
915                            .map(|(_, path, lock)| (path, lock))
916                            .collect()
917     } else {
918         FxHashMap()
919     }
920 }
921
922 /// Since paths of artifacts within session directories can get quite long, we
923 /// need to support deleting files with very long paths. The regular
924 /// WinApi functions only support paths up to 260 characters, however. In order
925 /// to circumvent this limitation, we canonicalize the path of the directory
926 /// before passing it to std::fs::remove_dir_all(). This will convert the path
927 /// into the '\\?\' format, which supports much longer paths.
928 fn safe_remove_dir_all(p: &Path) -> io::Result<()> {
929     if p.exists() {
930         let canonicalized = try!(p.canonicalize());
931         std_fs::remove_dir_all(canonicalized)
932     } else {
933         Ok(())
934     }
935 }
936
937 fn safe_remove_file(p: &Path) -> io::Result<()> {
938     if p.exists() {
939         let canonicalized = try!(p.canonicalize());
940         std_fs::remove_file(canonicalized)
941     } else {
942         Ok(())
943     }
944 }
945
946 #[test]
947 fn test_all_except_most_recent() {
948     assert_eq!(all_except_most_recent(
949         vec![
950             (UNIX_EPOCH + Duration::new(4, 0), PathBuf::from("4"), None),
951             (UNIX_EPOCH + Duration::new(1, 0), PathBuf::from("1"), None),
952             (UNIX_EPOCH + Duration::new(5, 0), PathBuf::from("5"), None),
953             (UNIX_EPOCH + Duration::new(3, 0), PathBuf::from("3"), None),
954             (UNIX_EPOCH + Duration::new(2, 0), PathBuf::from("2"), None),
955         ]).keys().cloned().collect::<FxHashSet<PathBuf>>(),
956         vec![
957             PathBuf::from("1"),
958             PathBuf::from("2"),
959             PathBuf::from("3"),
960             PathBuf::from("4"),
961         ].into_iter().collect::<FxHashSet<PathBuf>>()
962     );
963
964     assert_eq!(all_except_most_recent(
965         vec![
966         ]).keys().cloned().collect::<FxHashSet<PathBuf>>(),
967         FxHashSet()
968     );
969 }
970
971 #[test]
972 fn test_timestamp_serialization() {
973     for i in 0 .. 1_000u64 {
974         let time = UNIX_EPOCH + Duration::new(i * 1_434_578, (i as u32) * 239_000);
975         let s = timestamp_to_string(time);
976         assert_eq!(Ok(time), string_to_timestamp(&s));
977     }
978 }
979
980 #[test]
981 fn test_find_source_directory_in_iter() {
982     let already_visited = FxHashSet();
983
984     // Find newest
985     assert_eq!(find_source_directory_in_iter(
986         vec![PathBuf::from("crate-dir/s-3234-0000-svh"),
987              PathBuf::from("crate-dir/s-2234-0000-svh"),
988              PathBuf::from("crate-dir/s-1234-0000-svh")].into_iter(), &already_visited),
989         Some(PathBuf::from("crate-dir/s-3234-0000-svh")));
990
991     // Filter out "-working"
992     assert_eq!(find_source_directory_in_iter(
993         vec![PathBuf::from("crate-dir/s-3234-0000-working"),
994              PathBuf::from("crate-dir/s-2234-0000-svh"),
995              PathBuf::from("crate-dir/s-1234-0000-svh")].into_iter(), &already_visited),
996         Some(PathBuf::from("crate-dir/s-2234-0000-svh")));
997
998     // Handle empty
999     assert_eq!(find_source_directory_in_iter(vec![].into_iter(), &already_visited),
1000                None);
1001
1002     // Handle only working
1003     assert_eq!(find_source_directory_in_iter(
1004         vec![PathBuf::from("crate-dir/s-3234-0000-working"),
1005              PathBuf::from("crate-dir/s-2234-0000-working"),
1006              PathBuf::from("crate-dir/s-1234-0000-working")].into_iter(), &already_visited),
1007         None);
1008 }
1009
1010 #[test]
1011 fn test_find_metadata_hashes_iter()
1012 {
1013     assert_eq!(find_metadata_hashes_iter("testsvh2",
1014         vec![
1015             String::from("s-timestamp1-testsvh1"),
1016             String::from("s-timestamp2-testsvh2"),
1017             String::from("s-timestamp3-testsvh3"),
1018         ].into_iter()),
1019         Some(OsString::from("s-timestamp2-testsvh2"))
1020     );
1021
1022     assert_eq!(find_metadata_hashes_iter("testsvh2",
1023         vec![
1024             String::from("s-timestamp1-testsvh1"),
1025             String::from("s-timestamp2-testsvh2"),
1026             String::from("invalid-name"),
1027         ].into_iter()),
1028         Some(OsString::from("s-timestamp2-testsvh2"))
1029     );
1030
1031     assert_eq!(find_metadata_hashes_iter("testsvh2",
1032         vec![
1033             String::from("s-timestamp1-testsvh1"),
1034             String::from("s-timestamp2-testsvh2-working"),
1035             String::from("s-timestamp3-testsvh3"),
1036         ].into_iter()),
1037         None
1038     );
1039
1040     assert_eq!(find_metadata_hashes_iter("testsvh1",
1041         vec![
1042             String::from("s-timestamp1-random1-working"),
1043             String::from("s-timestamp2-random2-working"),
1044             String::from("s-timestamp3-random3-working"),
1045         ].into_iter()),
1046         None
1047     );
1048
1049     assert_eq!(find_metadata_hashes_iter("testsvh2",
1050         vec![
1051             String::from("timestamp1-testsvh2"),
1052             String::from("timestamp2-testsvh2"),
1053             String::from("timestamp3-testsvh2"),
1054         ].into_iter()),
1055         None
1056     );
1057 }