1 /*
2 * Copyright (C) 2025 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 #include <string>
18
19 #include "testdlopen.h"
20 #include "c-lib.h"
21
22 namespace testdlopen {
23 typedef int (*clibGetVer_t)();
24 typedef void (*clibPrintf_t)(const char *);
25 typedef int (*clibMax_t)(int, int);
26
27 // open library
openLib(const char * filename)28 static void *openLib(const char *filename) {
29 printf("\tLoading library %s\n", filename);
30 void *handle = dlopen(filename, RTLD_LAZY);
31 if (!handle) {
32 printf("Error loading library!\n");
33 dlerror();
34 }
35
36 return handle;
37 }
38
39 // close library
closeLib(void * handle)40 static void closeLib(void *handle) {
41 printf("\tClosing library\n");
42 dlclose(handle);
43 }
44
testVer(const char * filename)45 int testVer(const char *filename) {
46 printf("Testing clibGetVer\n");
47 void *handle = openLib(filename);
48 if (!handle) {
49 printf("Exiting!\n");
50 return -1;
51 }
52
53 printf("\tLoading symbol clibGetVer\n");
54 clibGetVer_t getVer = (clibGetVer_t) dlsym(handle, "clibGetVer");
55
56 printf("\tCalling clibGetVer\n");
57 int ver = getVer();
58
59 closeLib(handle);
60
61 printf("Exiting clibGetVer test\n");
62 return ver;
63 }
64
testPrintf(const char * filename,const char * text)65 int testPrintf(const char *filename, const char *text) {
66 printf("Testing clibPrintf\n");
67 void *handle = openLib(filename);
68 if (!handle) {
69 printf("Exiting!\n");
70 return -1;
71 }
72
73 printf("\tLoading symbol clibPrintf\n");
74 clibPrintf_t libPrintf = (clibPrintf_t) dlsym(handle, "clibPrintf");
75
76 printf("\tCalling clibPrintf\n");
77 libPrintf(text);
78
79 closeLib(handle);
80
81 printf("Exiting clibGetVet test\n");
82 return 0;
83 }
84
testMax(const char * filename,int a,int b)85 int testMax(const char *filename, int a, int b) {
86 printf("Testing clibMax\n");
87 void *handle = openLib(filename);
88 if (!handle) {
89 printf("Exiting!\n");
90 return -1;
91 }
92
93 printf("\tLoading symbol clibMax\n");
94 clibMax_t libMax = (clibMax_t) dlsym(handle, "clibMax");
95
96 printf("\tCalling clibMax\n");
97 int max = libMax(a, b);
98
99 closeLib(handle);
100
101 printf("Exiting clibMax test\n");
102 return max;
103 }
104 } // namespace testdlopen