1 /* 2 * Copyright (C) 2021 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 #ifndef CPP_CAR_BINDER_LIB_LARGEPARCELABLE_INCLUDE_MAPPEDFILE_H_ 18 #define CPP_CAR_BINDER_LIB_LARGEPARCELABLE_INCLUDE_MAPPEDFILE_H_ 19 20 #include <utils/Errors.h> 21 22 #include <assert.h> 23 #include <sys/mman.h> 24 25 namespace android { 26 namespace automotive { 27 namespace car_binder_lib { 28 29 using ::android::status_t; 30 31 // MappedFile represents a memory area mapped from a file. This class owns this area and would 32 // unmap it during destruction. 33 class MappedFile { 34 public: 35 // Create a new mapped memory area from 'memoryFd' with size 'fileSize'. If 'write' is true, the 36 // area would be mapped with read/write permission, otherwise, read only. Caller should use 37 // isValid() to check whether the initialization succeed and use getErr() to read err if 38 // isValid() is not true. 39 MappedFile(int memoryFd, int32_t fileSize, bool writtable); 40 isValid()41 inline bool isValid() const { return (mAddr != MAP_FAILED); } 42 getErr()43 inline status_t getErr() const { return -mErrno; } 44 getAddr()45 inline const void* getAddr() const { return mAddr; } 46 getWriteAddr()47 inline void* getWriteAddr() const { 48 assert(!mReadOnly); 49 return mAddr; 50 } 51 getSize()52 inline size_t getSize() const { return mSize; } 53 54 void sync() const; 55 56 ~MappedFile(); 57 58 private: 59 size_t mSize = 0; 60 void* mAddr = MAP_FAILED; 61 int mErrno = 0; 62 bool mReadOnly; 63 }; 64 65 } // namespace car_binder_lib 66 } // namespace automotive 67 } // namespace android 68 69 #endif // CPP_CAR_BINDER_LIB_LARGEPARCELABLE_INCLUDE_MAPPEDFILE_H_ 70