1 /*
2 * Copyright (C) 2023 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 "berberis/proxy_loader/proxy_loader.h"
18
19 #include <dlfcn.h>
20
21 #include <map>
22 #include <mutex>
23 #include <string>
24
25 #include "berberis/base/checks.h"
26 #include "berberis/base/forever_alloc.h"
27 #include "berberis/base/tracing.h"
28 #include "berberis/proxy_loader/proxy_library_builder.h"
29
30 namespace berberis {
31
32 namespace {
33
LoadProxyLibrary(ProxyLibraryBuilder * builder,const char * library_name,const char * proxy_prefix)34 bool LoadProxyLibrary(ProxyLibraryBuilder* builder,
35 const char* library_name,
36 const char* proxy_prefix) {
37 // library_name is the soname of original library
38 std::string proxy_name = proxy_prefix;
39 proxy_name += library_name;
40
41 void* proxy = dlopen(proxy_name.c_str(), RTLD_NOW | RTLD_LOCAL);
42 if (!proxy) {
43 TRACE("proxy library \"%s\" not found", proxy_name.c_str());
44 return false;
45 }
46
47 using InitProxyLibraryFunc = void (*)(ProxyLibraryBuilder*);
48 InitProxyLibraryFunc init =
49 reinterpret_cast<InitProxyLibraryFunc>(dlsym(proxy, "InitProxyLibrary"));
50 if (!init) {
51 TRACE("failed to initialize proxy library \"%s\"", proxy_name.c_str());
52 return false;
53 }
54
55 init(builder);
56
57 TRACE("loaded proxy library \"%s\"", proxy_name.c_str());
58 return true;
59 }
60
61 } // namespace
62
InterceptGuestSymbol(GuestAddr addr,const char * library_name,const char * name,const char * proxy_prefix)63 void InterceptGuestSymbol(GuestAddr addr,
64 const char* library_name,
65 const char* name,
66 const char* proxy_prefix) {
67 static auto* g_mutex = NewForever<std::mutex>();
68 std::lock_guard<std::mutex> guard(*g_mutex);
69
70 using Libraries = std::map<std::string, ProxyLibraryBuilder>;
71 static auto* g_libraries = NewForever<Libraries>();
72
73 auto res = g_libraries->insert({library_name, {}});
74 if (res.second && !LoadProxyLibrary(&res.first->second, library_name, proxy_prefix)) {
75 FATAL("Unable to load library \"%s\" (upon using symbol \"%s\")", library_name, name);
76 }
77
78 res.first->second.InterceptSymbol(addr, name);
79 }
80
81 } // namespace berberis
82