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 "android-base/macros.h" 20 #include "android-base/off64_t.h" 21 22 #include <sys/types.h> 23 24 #include <memory> 25 26 #if defined(_WIN32) 27 #include <windows.h> 28 #define PROT_READ 1 29 #define PROT_WRITE 2 30 #else 31 #include <sys/mman.h> 32 #endif 33 34 namespace android { 35 namespace base { 36 37 /** 38 * A region of a file mapped into memory. 39 */ 40 class MappedFile { 41 public: 42 /** 43 * Creates a new mapping of the file pointed to by `fd`. Unlike the underlying OS primitives, 44 * `offset` does not need to be page-aligned. If `PROT_WRITE` is set in `prot`, the mapping 45 * will be writable, otherwise it will be read-only. Mappings are always `MAP_SHARED`. 46 */ 47 static std::unique_ptr<MappedFile> FromFd(int fd, off64_t offset, size_t length, int prot); 48 49 /** 50 * Removes the mapping. 51 */ 52 ~MappedFile(); 53 data()54 char* data() { return base_ + offset_; } size()55 size_t size() { return size_; } 56 57 private: 58 DISALLOW_IMPLICIT_CONSTRUCTORS(MappedFile); 59 60 char* base_; 61 size_t size_; 62 63 size_t offset_; 64 65 #if defined(_WIN32) MappedFile(char * base,size_t size,size_t offset,HANDLE handle)66 MappedFile(char* base, size_t size, size_t offset, HANDLE handle) 67 : base_(base), size_(size), offset_(offset), handle_(handle) {} 68 HANDLE handle_; 69 #else MappedFile(char * base,size_t size,size_t offset)70 MappedFile(char* base, size_t size, size_t offset) : base_(base), size_(size), offset_(offset) {} 71 #endif 72 }; 73 74 } // namespace base 75 } // namespace android 76