1 /*
2  * Copyright (C) 2024 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 #pragma once
18 
19 #include <dlfcn.h>
20 
21 #include "interface/Event.h"
22 
23 namespace android::hardware::graphics::composer {
24 
25 class ExternalEventHandlerLoader {
26 public:
ExternalEventHandlerLoader(const char * libName,void * interface,void * host,const char * panelName)27     ExternalEventHandlerLoader(const char* libName, void* interface, void* host,
28                                const char* panelName)
29           : mLibHandle(dlopen(libName, RTLD_LAZY | RTLD_LOCAL), &dlclose) {
30         if (!mLibHandle) {
31             ALOGE("Unable to open %s, error = %s", libName, dlerror());
32             return;
33         }
34 
35         createExternalEventHandler_t createExternalEventHandler =
36                 reinterpret_cast<decltype(createExternalEventHandler)>(
37                         dlsym(mLibHandle.get(), "createExternalEventHandler"));
38         if (createExternalEventHandler == nullptr) {
39             ALOGE("Unable to load createExternalEventHandler, error = %s", dlerror());
40             return;
41         }
42 
43         mExternalEventHandlerDestructor =
44                 reinterpret_cast<decltype(mExternalEventHandlerDestructor)>(
45                         dlsym(mLibHandle.get(), "destroyExternalEventHandler"));
46         if (mExternalEventHandlerDestructor == nullptr) {
47             ALOGE("Unable to load destroyExternalEventHandler, error = %s", dlerror());
48             return;
49         }
50 
51         // Assign the event handler only when both the create and destroy functions are successfully
52         // loaded.
53         mExternalEventHandler = createExternalEventHandler(interface, host, panelName);
54     }
55 
~ExternalEventHandlerLoader()56     ~ExternalEventHandlerLoader() { mExternalEventHandlerDestructor(mExternalEventHandler); }
57 
getEventHandler()58     ExternalEventHandler* getEventHandler() { return mExternalEventHandler; }
59 
60 private:
61     using RaiiLibrary = std::unique_ptr<void, decltype(dlclose)*>;
62 
63     RaiiLibrary mLibHandle;
64 
65     destroyExternalEventHandler_t mExternalEventHandlerDestructor = nullptr;
66 
67     ExternalEventHandler* mExternalEventHandler = nullptr;
68 };
69 
70 } // namespace android::hardware::graphics::composer
71