1 /*
2 * Copyright (C) 2019 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 #include "src/android_internal/lazy_library_loader.h"
18
19 #include "perfetto/base/build_config.h"
20 #include "perfetto/base/logging.h"
21
22 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
23 namespace perfetto {
24 namespace android_internal {
LazyLoadFunction(const char *)25 void* LazyLoadFunction(const char*) {
26 PERFETTO_CHECK(false);
27 }
28 } // namespace android_internal
29 } // namespace perfetto
30 #else
31
32 #include <dlfcn.h>
33 #include <stdlib.h>
34
35 namespace perfetto {
36 namespace android_internal {
37
38 namespace {
39
40 const char kLibName[] = "libperfetto_android_internal.so";
41
LoadLibraryOnce()42 void* LoadLibraryOnce() {
43 #if !PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
44 // For testing only. Allows to use the version of the .so shipped in the
45 // system (if any) with the standalone builds of perfetto. This is really
46 // crash-prone and should not be used in production. The .so doesn't have a
47 // stable ABI, hence the version of the library in the system and the code in
48 // ToT can diverge.
49 const char* env_var = getenv("PERFETTO_ENABLE_ANDROID_INTERNAL_LIB");
50 if (!env_var || strcmp(env_var, "1")) {
51 PERFETTO_ELOG(
52 "android_internal functions can be used only with in-tree builds of "
53 "perfetto.");
54 return nullptr;
55 }
56 #endif
57 void* handle = dlopen(kLibName, RTLD_NOW);
58 if (!handle)
59 PERFETTO_PLOG("dlopen(%s) failed", kLibName);
60 return handle;
61 }
62
63 } // namespace
64
LazyLoadFunction(const char * name)65 void* LazyLoadFunction(const char* name) {
66 // Strip the namespace qualification from the full symbol name.
67 const char* sep = strrchr(name, ':');
68 const char* function_name = sep ? sep + 1 : name;
69 static void* handle = LoadLibraryOnce();
70 if (!handle)
71 return nullptr;
72 void* fn = dlsym(handle, function_name);
73 if (!fn)
74 PERFETTO_PLOG("dlsym(%s) failed", function_name);
75 return fn;
76 }
77
78 } // namespace android_internal
79 } // namespace perfetto
80
81 #endif // !OS_WIN
82