test_file_util_mac.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/test/test_file_util.h"
  5. #include <sys/mman.h>
  6. #include <errno.h>
  7. #include <stdint.h>
  8. #include "base/files/file_util.h"
  9. #include "base/files/memory_mapped_file.h"
  10. #include "base/logging.h"
  11. namespace base {
  12. bool EvictFileFromSystemCache(const FilePath& file) {
  13. // There aren't any really direct ways to purge a file from the UBC. From
  14. // talking with Amit Singh, the safest is to mmap the file with MAP_FILE (the
  15. // default) + MAP_SHARED, then do an msync to invalidate the memory. The next
  16. // open should then have to load the file from disk.
  17. int64_t length;
  18. if (!GetFileSize(file, &length)) {
  19. DLOG(ERROR) << "failed to get size of " << file.value();
  20. return false;
  21. }
  22. // When a file is empty, we do not need to evict it from cache.
  23. // In fact, an attempt to map it to memory will result in error.
  24. if (length == 0) {
  25. DLOG(WARNING) << "file size is zero, will not attempt to map to memory";
  26. return true;
  27. }
  28. MemoryMappedFile mapped_file;
  29. if (!mapped_file.Initialize(file)) {
  30. DLOG(WARNING) << "failed to memory map " << file.value();
  31. return false;
  32. }
  33. if (msync(const_cast<uint8_t*>(mapped_file.data()), mapped_file.length(),
  34. MS_INVALIDATE) != 0) {
  35. DLOG(WARNING) << "failed to invalidate memory map of " << file.value()
  36. << ", errno: " << errno;
  37. return false;
  38. }
  39. return true;
  40. }
  41. } // namespace base