1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <sys/types.h>
20 
21 #include <memory>
22 
23 #include "android-base/macros.h"
24 #include "android-base/off64_t.h"
25 #include "android-base/unique_fd.h"
26 
27 #if defined(_WIN32)
28 #include <windows.h>
29 #define PROT_READ 1
30 #define PROT_WRITE 2
31 using os_handle = HANDLE;
32 #else
33 #include <sys/mman.h>
34 using os_handle = int;
35 #endif
36 
37 namespace android {
38 namespace base {
39 
40 /**
41  * A region of a file mapped into memory (for grepping: also known as MmapFile or file mapping).
42  */
43 class MappedFile {
44  public:
45   /**
46    * Creates a new mapping of the file pointed to by `fd`. Unlike the underlying OS primitives,
47    * `offset` does not need to be page-aligned. If `PROT_WRITE` is set in `prot`, the mapping
48    * will be writable, otherwise it will be read-only. Mappings are always `MAP_SHARED`.
49    */
50   static std::unique_ptr<MappedFile> FromFd(borrowed_fd fd, off64_t offset, size_t length,
51                                             int prot);
52 
53   /**
54    * Same thing, but using the raw OS file handle instead of a CRT wrapper.
55    */
56   static std::unique_ptr<MappedFile> FromOsHandle(os_handle h, off64_t offset, size_t length,
57                                                   int prot);
58 
59   /**
60    * Removes the mapping.
61    */
62   ~MappedFile();
63 
64   /**
65    * Not copyable but movable.
66    */
67   MappedFile(MappedFile&& other);
68   MappedFile& operator=(MappedFile&& other);
69 
data()70   char* data() const { return base_ + offset_; }
size()71   size_t size() const { return size_; }
72 
73  private:
74   DISALLOW_IMPLICIT_CONSTRUCTORS(MappedFile);
75 
76   void Close();
77 
78   char* base_;
79   size_t size_;
80 
81   size_t offset_;
82 
83 #if defined(_WIN32)
MappedFile(char * base,size_t size,size_t offset,HANDLE handle)84   MappedFile(char* base, size_t size, size_t offset, HANDLE handle)
85       : base_(base), size_(size), offset_(offset), handle_(handle) {}
86   HANDLE handle_;
87 #else
MappedFile(char * base,size_t size,size_t offset)88   MappedFile(char* base, size_t size, size_t offset) : base_(base), size_(size), offset_(offset) {}
89 #endif
90 };
91 
92 }  // namespace base
93 }  // namespace android
94