xref: /aosp_15_r20/external/cronet/net/disk_cache/blockfile/mapped_file_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #include "net/disk_cache/blockfile/mapped_file.h"
6 
7 #include <windows.h>
8 
9 #include <memory>
10 
11 #include "base/check.h"
12 #include "base/files/file_path.h"
13 #include "net/disk_cache/disk_cache.h"
14 
15 namespace disk_cache {
16 
Init(const base::FilePath & name,size_t size)17 void* MappedFile::Init(const base::FilePath& name, size_t size) {
18   DCHECK(!init_);
19   if (init_ || !File::Init(name))
20     return nullptr;
21 
22   buffer_ = nullptr;
23   init_ = true;
24   section_ = CreateFileMapping(platform_file(), nullptr, PAGE_READWRITE, 0,
25                                static_cast<DWORD>(size), nullptr);
26   if (!section_)
27     return nullptr;
28 
29   buffer_ = MapViewOfFile(section_, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size);
30   DCHECK(buffer_);
31   view_size_ = size;
32 
33   // Make sure we detect hardware failures reading the headers.
34   size_t temp_len = size ? size : 4096;
35   auto temp = std::make_unique<char[]>(temp_len);
36   if (!Read(temp.get(), temp_len, 0))
37     return nullptr;
38 
39   return buffer_;
40 }
41 
~MappedFile()42 MappedFile::~MappedFile() {
43   if (!init_)
44     return;
45 
46   if (buffer_) {
47     BOOL ret = UnmapViewOfFile(buffer_);
48     DCHECK(ret);
49   }
50 
51   if (section_)
52     CloseHandle(section_);
53 }
54 
Flush()55 void MappedFile::Flush() {
56 }
57 
58 }  // namespace disk_cache
59