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