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
28using android::sp;
29using android::hidl::memory::V1_0::IMemory;
30using android::hidl::memory::V1_0::IMapper;
31
32namespace android {
33namespace hardware {
34
35static std::map<std::string, sp<IMapper>> gMappersByName;
36static std::mutex gMutex;
37
38static inline sp<IMapper> getMapperService(const std::string& name) {
39    std::unique_lock<std::mutex> _lock(gMutex);
40    auto iter = gMappersByName.find(name);
41    if (iter != gMappersByName.end()) {
42        return iter->second;
43    }
44
45    sp<IMapper> mapper = IMapper::getService(name, true /* getStub */);
46    if (mapper != nullptr) {
47        gMappersByName[name] = mapper;
48    }
49    return mapper;
50}
51
52sp<IMemory> mapMemory(const hidl_memory& memory) {
53
54    sp<IMapper> mapper = getMapperService(memory.name());
55
56    if (mapper == nullptr) {
57        LOG(FATAL) << "Could not fetch mapper for " << memory.name() << " shared memory";
58    }
59
60    if (mapper->isRemote()) {
61        LOG(FATAL) << "IMapper must be a passthrough service.";
62    }
63
64    Return<sp<IMemory>> ret = mapper->mapMemory(memory);
65
66    if (!ret.isOk()) {
67        LOG(FATAL) << "hidl_memory map returned transport error.";
68    }
69
70    return ret;
71}
72
73}  // namespace hardware
74}  // namespace android
75