• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/guest_loader/guest_loader.h"
18 
19 #include <link.h>
20 
21 #include "berberis/base/macros.h"
22 #include "berberis/base/tracing.h"
23 #include "berberis/instrument/loader.h"
24 
25 #include "guest_loader_impl.h"  // MakeElfSymbolTrampolineCallable
26 
27 namespace berberis {
28 
29 namespace {
30 
DoCustomTrampoline_rtld_db_dlactivity(HostCode callee,ThreadState * state)31 void DoCustomTrampoline_rtld_db_dlactivity(HostCode callee, ThreadState* state) {
32   UNUSED(callee, state);
33 
34   // It would be also tempting to bind r_debug to callee, but then we need to know r_debug when
35   // creating the trampoline. Also, it seems r_debug might still be 0 when rtld_db_dlactivity is
36   // called first couple of times.
37   // Thus, search and check.
38   const auto* debug = GuestLoader::GetInstance()->FindRDebug();
39   if (debug == nullptr) {
40     return;
41   }
42 
43   // ATTENTION: assume struct r_debug and struct link_map are compatible!
44   if (debug->r_state == r_debug::RT_CONSISTENT) {
45     OnConsistentLinkMap(debug->r_map);
46   }
47 }
48 
49 }  // namespace
50 
InitLinkerDebug(const LoadedElfFile & linker_elf_file)51 void InitLinkerDebug(const LoadedElfFile& linker_elf_file) {
52   if (!kInstrumentLoader) {
53     return;
54   }
55 
56   // The correct way to hook linker rtld_db_dlactivity would be to read struct r_debug pointer from
57   // main executable's DT_DEBUG and get breakpoint address from there.
58   // Unfortunately, DT_DEBUG gets initialized by guest linker, which didn't yet run at this point.
59   // Instead, hope breakpoint symbol is exported.
60   std::string error_msg;
61   if (!MakeElfSymbolTrampolineCallable(linker_elf_file,
62                                        "linker",
63                                        "rtld_db_dlactivity",
64                                        DoCustomTrampoline_rtld_db_dlactivity,
65                                        nullptr,
66                                        &error_msg)) {
67     TRACE("failed to hook rtld_db_dlactivity: %s", error_msg.c_str());
68   }
69 }
70 
71 }  // namespace berberis