| OLD | NEW |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "base/files/memory_mapped_file.h" | 5 #include "base/files/memory_mapped_file.h" |
| 6 | 6 |
| 7 #include <sys/mman.h> | 7 #include <sys/mman.h> |
| 8 #include <sys/stat.h> | 8 #include <sys/stat.h> |
| 9 #include <unistd.h> | 9 #include <unistd.h> |
| 10 | 10 |
| 11 #include "base/logging.h" | 11 #include "base/logging.h" |
| 12 #include "base/threading/thread_restrictions.h" | 12 #include "base/threading/thread_restrictions.h" |
| 13 | 13 |
| 14 namespace base { | 14 namespace base { |
| 15 | 15 |
| 16 MemoryMappedFile::MemoryMappedFile() : data_(NULL), length_(0) { | 16 MemoryMappedFile::MemoryMappedFile() : data_(NULL), length_(0) { |
| 17 } | 17 } |
| 18 | 18 |
| 19 bool MemoryMappedFile::MapFileToMemory() { | 19 bool MemoryMappedFile::MapFileToMemory(const base::File::Region& region) { |
| 20 ThreadRestrictions::AssertIOAllowed(); | 20 ThreadRestrictions::AssertIOAllowed(); |
| 21 | 21 |
| 22 struct stat file_stat; | 22 int64 file_len = file_.GetLength(); |
| 23 if (fstat(file_.GetPlatformFile(), &file_stat) == -1 ) { | 23 |
| 24 if (file_len == -1) { |
| 24 DPLOG(ERROR) << "fstat " << file_.GetPlatformFile(); | 25 DPLOG(ERROR) << "fstat " << file_.GetPlatformFile(); |
| 25 return false; | 26 return false; |
| 26 } | 27 } |
| 27 length_ = file_stat.st_size; | |
| 28 | 28 |
| 29 data_ = static_cast<uint8*>( | 29 if (region.offset + region.size > file_.GetLength()) { |
| 30 mmap(NULL, length_, PROT_READ, MAP_SHARED, file_.GetPlatformFile(), 0)); | 30 DLOG(ERROR) << "Region bounds invalid"; |
| 31 return false; |
| 32 } |
| 33 |
| 34 length_ = static_cast<size_t>(region.size); |
| 35 data_ = static_cast<uint8*>(mmap(NULL, |
| 36 length_, |
| 37 PROT_READ, |
| 38 MAP_SHARED, |
| 39 file_.GetPlatformFile(), |
| 40 region.offset)); |
| 31 if (data_ == MAP_FAILED) | 41 if (data_ == MAP_FAILED) |
| 32 DPLOG(ERROR) << "mmap " << file_.GetPlatformFile(); | 42 DPLOG(ERROR) << "mmap " << file_.GetPlatformFile(); |
| 33 | 43 |
| 34 return data_ != MAP_FAILED; | 44 return data_ != MAP_FAILED; |
| 35 } | 45 } |
| 36 | 46 |
| 37 void MemoryMappedFile::CloseHandles() { | 47 void MemoryMappedFile::CloseHandles() { |
| 38 ThreadRestrictions::AssertIOAllowed(); | 48 ThreadRestrictions::AssertIOAllowed(); |
| 39 | 49 |
| 40 if (data_ != NULL) | 50 if (data_ != NULL) |
| 41 munmap(data_, length_); | 51 munmap(data_, length_); |
| 42 file_.Close(); | 52 file_.Close(); |
| 43 | 53 |
| 44 data_ = NULL; | 54 data_ = NULL; |
| 45 length_ = 0; | 55 length_ = 0; |
| 46 } | 56 } |
| 47 | 57 |
| 48 } // namespace base | 58 } // namespace base |
| OLD | NEW |