xref: /aosp_15_r20/external/cronet/net/disk_cache/blockfile/mapped_file_posix.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 <errno.h>
8 #include <sys/mman.h>
9 
10 #include "base/files/file_path.h"
11 #include "base/logging.h"
12 #include "net/disk_cache/disk_cache.h"
13 
14 namespace disk_cache {
15 
Init(const base::FilePath & name,size_t size)16 void* MappedFile::Init(const base::FilePath& name, size_t size) {
17   DCHECK(!init_);
18   if (init_ || !File::Init(name))
19     return nullptr;
20 
21   size_t temp_len = size ? size : 4096;
22   if (!size)
23     size = GetLength();
24 
25   buffer_ = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED,
26                  platform_file(), 0);
27   init_ = true;
28   view_size_ = size;
29   DPLOG_IF(ERROR, buffer_ == MAP_FAILED) << "Failed to mmap " << name.value();
30   if (buffer_ == MAP_FAILED)
31     buffer_ = nullptr;
32 
33   // Make sure we detect hardware failures reading the headers.
34   auto temp = std::make_unique<char[]>(temp_len);
35   if (!Read(temp.get(), temp_len, 0))
36     return nullptr;
37 
38   return buffer_;
39 }
40 
Flush()41 void MappedFile::Flush() {
42 }
43 
~MappedFile()44 MappedFile::~MappedFile() {
45   if (!init_)
46     return;
47 
48   if (buffer_) {
49     int ret = munmap(buffer_, view_size_);
50     DCHECK_EQ(0, ret);
51   }
52 }
53 
54 }  // namespace disk_cache
55