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
14namespace base {
15
16MemoryMappedFile::MemoryMappedFile()
17    : file_(kInvalidPlatformFileValue),
18      data_(NULL),
19      length_(0) {
20}
21
22bool MemoryMappedFile::MapFileToMemoryInternal() {
23  ThreadRestrictions::AssertIOAllowed();
24
25  struct stat file_stat;
26  if (fstat(file_, &file_stat) == kInvalidPlatformFileValue) {
27    DPLOG(ERROR) << "fstat " << file_;
28    return false;
29  }
30  length_ = file_stat.st_size;
31
32  data_ = static_cast<uint8*>(
33      mmap(NULL, length_, PROT_READ, MAP_SHARED, file_, 0));
34  if (data_ == MAP_FAILED)
35    DPLOG(ERROR) << "mmap " << file_;
36
37  return data_ != MAP_FAILED;
38}
39
40void MemoryMappedFile::CloseHandles() {
41  ThreadRestrictions::AssertIOAllowed();
42
43  if (data_ != NULL)
44    munmap(data_, length_);
45  if (file_ != kInvalidPlatformFileValue)
46    close(file_);
47
48  data_ = NULL;
49  length_ = 0;
50  file_ = kInvalidPlatformFileValue;
51}
52
53}  // namespace base
54