summaryrefslogtreecommitdiffstats
path: root/chromium/base/files/memory_mapped_file.h
blob: 6df1bad63591974fa18f5ed876cacd5a0b45948f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_FILES_MEMORY_MAPPED_FILE_H_
#define BASE_FILES_MEMORY_MAPPED_FILE_H_

#include "base/base_export.h"
#include "base/basictypes.h"
#include "base/platform_file.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

namespace base {

class FilePath;

class BASE_EXPORT MemoryMappedFile {
 public:
  // The default constructor sets all members to invalid/null values.
  MemoryMappedFile();
  ~MemoryMappedFile();

  // Opens an existing file and maps it into memory. Access is restricted to
  // read only. If this object already points to a valid memory mapped file
  // then this method will fail and return false. If it cannot open the file,
  // the file does not exist, or the memory mapping fails, it will return false.
  // Later we may want to allow the user to specify access.
  bool Initialize(const FilePath& file_name);
  // As above, but works with an already-opened file. MemoryMappedFile will take
  // ownership of |file| and close it when done.
  bool Initialize(PlatformFile file);

#if defined(OS_WIN)
  // Opens an existing file and maps it as an image section. Please refer to
  // the Initialize function above for additional information.
  bool InitializeAsImageSection(const FilePath& file_name);
#endif  // OS_WIN

  const uint8* data() const { return data_; }
  size_t length() const { return length_; }

  // Is file_ a valid file handle that points to an open, memory mapped file?
  bool IsValid() const;

 private:
  // Open the given file and pass it to MapFileToMemoryInternal().
  bool MapFileToMemory(const FilePath& file_name);

  // Map the file to memory, set data_ to that memory address. Return true on
  // success, false on any kind of failure. This is a helper for Initialize().
  bool MapFileToMemoryInternal();

  // Closes all open handles. Later we may want to make this public.
  void CloseHandles();

#if defined(OS_WIN)
  // MapFileToMemoryInternal calls this function. It provides the ability to
  // pass in flags which control the mapped section.
  bool MapFileToMemoryInternalEx(int flags);

  HANDLE file_mapping_;
#endif
  PlatformFile file_;
  uint8* data_;
  size_t length_;

  DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile);
};

}  // namespace base

#endif  // BASE_FILES_MEMORY_MAPPED_FILE_H_