1 // Copyright 2012 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 // See net/disk_cache/disk_cache.h for the public interface of the cache. 6 7 #ifndef NET_DISK_CACHE_BLOCKFILE_MAPPED_FILE_H_ 8 #define NET_DISK_CACHE_BLOCKFILE_MAPPED_FILE_H_ 9 10 #include <stddef.h> 11 12 #include "base/memory/raw_ptr.h" 13 #include "base/memory/raw_ptr_exclusion.h" 14 #include "build/build_config.h" 15 #include "net/base/net_export.h" 16 #include "net/disk_cache/blockfile/file.h" 17 #include "net/disk_cache/blockfile/file_block.h" 18 #include "net/net_buildflags.h" 19 20 namespace base { 21 class FilePath; 22 } 23 24 namespace disk_cache { 25 26 // This class implements a memory mapped file used to access block-files. The 27 // idea is that the header and bitmap will be memory mapped all the time, and 28 // the actual data for the blocks will be access asynchronously (most of the 29 // time). 30 class NET_EXPORT_PRIVATE MappedFile : public File { 31 public: MappedFile()32 MappedFile() : File(true) {} 33 34 MappedFile(const MappedFile&) = delete; 35 MappedFile& operator=(const MappedFile&) = delete; 36 37 // Performs object initialization. name is the file to use, and size is the 38 // amount of data to memory map from the file. If size is 0, the whole file 39 // will be mapped in memory. 40 void* Init(const base::FilePath& name, size_t size); 41 buffer()42 void* buffer() const { 43 return buffer_; 44 } 45 46 // Loads or stores a given block from the backing file (synchronously). 47 bool Load(const FileBlock* block); 48 bool Store(const FileBlock* block); 49 50 // Flush the memory-mapped section to disk (synchronously). 51 void Flush(); 52 53 // Heats up the file system cache and make sure the file is fully 54 // readable (synchronously). 55 bool Preload(); 56 57 private: 58 ~MappedFile() override; 59 60 bool init_ = false; 61 #if BUILDFLAG(IS_WIN) 62 HANDLE section_; 63 #endif 64 // This field is not a raw_ptr<> because it is using mmap, MapViewOfFile or 65 // base::AllocPages directly. 66 // TODO(bartekn): This one has a malloc() path, consider rewriting after all. 67 RAW_PTR_EXCLUSION void* buffer_; // Address of the memory mapped buffer. 68 size_t view_size_; // Size of the memory pointed by buffer_. 69 #if BUILDFLAG(POSIX_BYPASS_MMAP) 70 raw_ptr<void> 71 snapshot_; // Copy of the buffer taken when it was last flushed. 72 #endif 73 }; 74 75 // Helper class for calling Flush() on exit from the current scope. 76 class ScopedFlush { 77 public: ScopedFlush(MappedFile * file)78 explicit ScopedFlush(MappedFile* file) : file_(file) {} ~ScopedFlush()79 ~ScopedFlush() { 80 file_->Flush(); 81 } 82 private: 83 raw_ptr<MappedFile> file_; 84 }; 85 86 } // namespace disk_cache 87 88 #endif // NET_DISK_CACHE_BLOCKFILE_MAPPED_FILE_H_ 89