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 #define LOG_TAG "libhidlmemory"
17 
18 #include <map>
19 #include <mutex>
20 #include <string>
21 
22 #include <hidlmemory/mapping.h>
23 
24 #include <android-base/logging.h>
25 #include <android/hidl/memory/1.0/IMapper.h>
26 #include <hidl/HidlSupport.h>
27 #include <log/log.h>
28 
29 using android::sp;
30 using android::hidl::memory::V1_0::IMemory;
31 using android::hidl::memory::V1_0::IMapper;
32 
33 namespace android {
34 namespace hardware {
35 
36 static std::map<std::string, sp<IMapper>> gMappersByName;
37 static std::mutex gMutex;
38 
39 static inline sp<IMapper> getMapperService(const std::string& name) {
40     std::unique_lock<std::mutex> _lock(gMutex);
41     auto iter = gMappersByName.find(name);
42     if (iter != gMappersByName.end()) {
43         return iter->second;
44     }
45 
46     sp<IMapper> mapper = IMapper::getService(name, true /* getStub */);
47     if (mapper != nullptr) {
48         gMappersByName[name] = mapper;
49     }
50     return mapper;
51 }
52 
53 sp<IMemory> mapMemory(const hidl_memory& memory) {
54 
55     sp<IMapper> mapper = getMapperService(memory.name());
56 
57     if (mapper == nullptr) {
58         LOG(ERROR) << "Could not fetch mapper for " << memory.name() << " shared memory";
59         return nullptr;
60     }
61 
62     if (mapper->isRemote()) {
63         LOG(ERROR) << "IMapper must be a passthrough service.";
64         return nullptr;
65     }
66 
67     // hidl_memory's size is stored in uint64_t, but mapMemory's mmap will map
68     // size in size_t. If size is over SIZE_MAX, mapMemory could succeed
69     // but the mapped memory's actual size will be smaller than the reported size.
70     if (memory.size() > SIZE_MAX) {
71         LOG(ERROR) << "Cannot map " << memory.size() << " bytes of memory because it is too large.";
72         android_errorWriteLog(0x534e4554, "79376389");
73         return nullptr;
74     }
75 
76     Return<sp<IMemory>> ret = mapper->mapMemory(memory);
77 
78     if (!ret.isOk()) {
79         LOG(ERROR) << "hidl_memory map returned transport error.";
80         return nullptr;
81     }
82 
83     return ret;
84 }
85 
86 }  // namespace hardware
87 }  // namespace android
88