Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / base / files / memory_mapped_file_posix.cc
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.
4
5 #include "base/files/memory_mapped_file.h"
6
7 #include <sys/mman.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 #include "base/logging.h"
12 #include "base/threading/thread_restrictions.h"
13
14 namespace base {
15
16 MemoryMappedFile::MemoryMappedFile() : data_(NULL), length_(0) {
17 }
18
19 bool MemoryMappedFile::MapFileToMemory() {
20   ThreadRestrictions::AssertIOAllowed();
21
22   struct stat file_stat;
23   if (fstat(file_.GetPlatformFile(), &file_stat) == -1 ) {
24     DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
25     return false;
26   }
27   length_ = file_stat.st_size;
28
29   data_ = static_cast<uint8*>(
30       mmap(NULL, length_, PROT_READ, MAP_SHARED, file_.GetPlatformFile(), 0));
31   if (data_ == MAP_FAILED)
32     DPLOG(ERROR) << "mmap " << file_.GetPlatformFile();
33
34   return data_ != MAP_FAILED;
35 }
36
37 void MemoryMappedFile::CloseHandles() {
38   ThreadRestrictions::AssertIOAllowed();
39
40   if (data_ != NULL)
41     munmap(data_, length_);
42   file_.Close();
43
44   data_ = NULL;
45   length_ = 0;
46 }
47
48 }  // namespace base