1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <cstdio>
16 #include <dlfcn.h>
17
18 #include "hilog_wrapper.h"
19 #include "napi/native_api.h"
20
21 using namespace OHOS::USB;
22
23 /*
24 * Module definition
25 */
26 static napi_module g_module = {.nm_version = 1,
27 .nm_flags = 0,
28 .nm_filename = "usb",
29 .nm_register_func = nullptr,
30 .nm_modname = "usb",
31 .nm_priv = nullptr,
32 .reserved = {nullptr}};
33
34 static void *g_libHandle = nullptr;
35
36 /*
37 * Module registration
38 */
RegisterModule(void)39 extern "C" __attribute__((constructor)) void RegisterModule(void)
40 {
41 g_libHandle = dlopen("libusbmanager.z.so", RTLD_LAZY);
42 if (g_libHandle == nullptr) {
43 USB_HILOGE(MODULE_JS_NAPI, "open libusbmanager.z.so failed, %{public}s", dlerror());
44 return;
45 }
46 void *funcPtr = dlsym(g_libHandle, "UsbInit");
47 if (funcPtr == nullptr) {
48 USB_HILOGE(MODULE_JS_NAPI, "UsbInit not found, %{public}s", dlerror());
49 return;
50 }
51 g_module.nm_register_func = reinterpret_cast<napi_addon_register_func>(funcPtr);
52 napi_module_register(&g_module);
53 }
54
ReleaseModule(void)55 extern "C" __attribute__((destructor)) void ReleaseModule(void)
56 {
57 if (g_libHandle == nullptr) {
58 return;
59 }
60 int ret = dlclose(g_libHandle);
61 USB_HILOGI(MODULE_JS_NAPI, "release module: %{public}d", ret);
62 g_libHandle = nullptr;
63 }