Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / base / files / memory_mapped_file.cc
blob745a5ff1f4524f944823c244249836b6b52bf9a3
1 // Copyright 2013 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.
5 #include "base/files/memory_mapped_file.h"
7 #include "base/files/file_path.h"
8 #include "base/logging.h"
9 #include "base/sys_info.h"
11 namespace base {
13 const MemoryMappedFile::Region MemoryMappedFile::Region::kWholeFile(
14 base::LINKER_INITIALIZED);
16 MemoryMappedFile::Region::Region(base::LinkerInitialized) : offset(0), size(0) {
19 MemoryMappedFile::Region::Region(int64 offset, int64 size)
20 : offset(offset), size(size) {
21 DCHECK_GE(offset, 0);
22 DCHECK_GT(size, 0);
25 bool MemoryMappedFile::Region::operator==(
26 const MemoryMappedFile::Region& other) const {
27 return other.offset == offset && other.size == size;
30 MemoryMappedFile::~MemoryMappedFile() {
31 CloseHandles();
34 bool MemoryMappedFile::Initialize(const FilePath& file_name) {
35 if (IsValid())
36 return false;
38 file_.Initialize(file_name, File::FLAG_OPEN | File::FLAG_READ);
40 if (!file_.IsValid()) {
41 DLOG(ERROR) << "Couldn't open " << file_name.AsUTF8Unsafe();
42 return false;
45 if (!MapFileRegionToMemory(Region::kWholeFile)) {
46 CloseHandles();
47 return false;
50 return true;
53 bool MemoryMappedFile::Initialize(File file) {
54 return Initialize(file.Pass(), Region::kWholeFile);
57 bool MemoryMappedFile::Initialize(File file, const Region& region) {
58 if (IsValid())
59 return false;
61 file_ = file.Pass();
63 if (!MapFileRegionToMemory(region)) {
64 CloseHandles();
65 return false;
68 return true;
71 bool MemoryMappedFile::IsValid() const {
72 return data_ != NULL;
75 // static
76 void MemoryMappedFile::CalculateVMAlignedBoundaries(int64 start,
77 int64 size,
78 int64* aligned_start,
79 int64* aligned_size,
80 int32* offset) {
81 // Sadly, on Windows, the mmap alignment is not just equal to the page size.
82 const int64 mask = static_cast<int64>(SysInfo::VMAllocationGranularity()) - 1;
83 DCHECK_LT(mask, std::numeric_limits<int32>::max());
84 *offset = start & mask;
85 *aligned_start = start & ~mask;
86 *aligned_size = (size + *offset + mask) & ~mask;
89 } // namespace base