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