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