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 #define LOG_TAG "LargeParcelable"
18 
19 #include "MappedFile.h"
20 
21 #include <utils/Log.h>
22 
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/mman.h>
26 
27 namespace android {
28 namespace automotive {
29 namespace car_binder_lib {
30 
MappedFile(int memoryFd,int32_t fileSize,bool writtable)31 MappedFile::MappedFile(int memoryFd, int32_t fileSize, bool writtable) {
32     mAddr = mmap(/*addr=*/NULL, fileSize, (writtable ? PROT_WRITE : PROT_READ), MAP_SHARED,
33                  memoryFd, /*offset=*/0);
34     if (mAddr == MAP_FAILED) {
35         ALOGE("mmap failed: %s", std::strerror(errno));
36         mErrno = errno;
37     }
38     mReadOnly = !writtable;
39     mSize = fileSize;
40 }
41 
sync() const42 void MappedFile::sync() const {
43     msync(mAddr, mSize, MS_SYNC);
44 }
45 
~MappedFile()46 MappedFile::~MappedFile() {
47     if (isValid()) {
48         munmap(mAddr, mSize);
49     }
50 }
51 
52 }  // namespace car_binder_lib
53 }  // namespace automotive
54 }  // namespace android
55