1 /* 2 * Copyright (C) 2016 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 #include "AshmemMapper.h" 18 19 #include <inttypes.h> 20 21 #include <log/log.h> 22 #include <sys/mman.h> 23 24 #include "AshmemMemory.h" 25 26 namespace android { 27 namespace hidl { 28 namespace memory { 29 namespace V1_0 { 30 namespace implementation { 31 32 // Methods from ::android::hidl::memory::V1_0::IMapper follow. 33 Return<sp<IMemory>> AshmemMapper::mapMemory(const hidl_memory& mem) { 34 if (mem.handle()->numFds == 0) { 35 return nullptr; 36 } 37 38 // If ashmem service runs in 32-bit (size_t is uint32_t) and a 64-bit 39 // client process requests a memory > 2^32 bytes, the size would be 40 // converted to a 32-bit number in mmap. mmap could succeed but the 41 // mapped memory's actual size would be smaller than the reported size. 42 if (mem.size() > SIZE_MAX) { 43 ALOGE("Cannot map %" PRIu64 " bytes of memory because it is too large.", mem.size()); 44 android_errorWriteLog(0x534e4554, "79376389"); 45 return nullptr; 46 } 47 48 int fd = mem.handle()->data[0]; 49 void* data = mmap(0, mem.size(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 50 if (data == MAP_FAILED) { 51 // mmap never maps at address zero without MAP_FIXED, so we can avoid 52 // exposing clients to MAP_FAILED. 53 return nullptr; 54 } 55 56 return new AshmemMemory(mem, data); 57 } 58 59 } // namespace implementation 60 } // namespace V1_0 61 } // namespace memory 62 } // namespace hidl 63 } // namespace android 64