Coverage Report

Created: 2023-05-31 04:38

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- DynamicLoaderPOSIXDYLD.cpp ----------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
// Main header include
10
#include "DynamicLoaderPOSIXDYLD.h"
11
12
#include "lldb/Breakpoint/BreakpointLocation.h"
13
#include "lldb/Core/Module.h"
14
#include "lldb/Core/ModuleSpec.h"
15
#include "lldb/Core/PluginManager.h"
16
#include "lldb/Core/Section.h"
17
#include "lldb/Symbol/Function.h"
18
#include "lldb/Symbol/ObjectFile.h"
19
#include "lldb/Target/MemoryRegionInfo.h"
20
#include "lldb/Target/Platform.h"
21
#include "lldb/Target/Target.h"
22
#include "lldb/Target/Thread.h"
23
#include "lldb/Target/ThreadPlanRunToAddress.h"
24
#include "lldb/Utility/LLDBLog.h"
25
#include "lldb/Utility/Log.h"
26
#include "lldb/Utility/ProcessInfo.h"
27
28
#include <memory>
29
#include <optional>
30
31
using namespace lldb;
32
using namespace lldb_private;
33
34
LLDB_PLUGIN_DEFINE_ADV(DynamicLoaderPOSIXDYLD, DynamicLoaderPosixDYLD)
35
36
3.85k
void DynamicLoaderPOSIXDYLD::Initialize() {
37
3.85k
  PluginManager::RegisterPlugin(GetPluginNameStatic(),
38
3.85k
                                GetPluginDescriptionStatic(), CreateInstance);
39
3.85k
}
40
41
3.84k
void DynamicLoaderPOSIXDYLD::Terminate() {}
42
43
3.85k
llvm::StringRef DynamicLoaderPOSIXDYLD::GetPluginDescriptionStatic() {
44
3.85k
  return "Dynamic loader plug-in that watches for shared library "
45
3.85k
         "loads/unloads in POSIX processes.";
46
3.85k
}
47
48
DynamicLoader *DynamicLoaderPOSIXDYLD::CreateInstance(Process *process,
49
163
                                                      bool force) {
50
163
  bool create = force;
51
163
  if (!create) {
52
104
    const llvm::Triple &triple_ref =
53
104
        process->GetTarget().GetArchitecture().GetTriple();
54
104
    if (triple_ref.getOS() == llvm::Triple::FreeBSD ||
55
104
        triple_ref.getOS() == llvm::Triple::Linux ||
56
104
        
triple_ref.getOS() == llvm::Triple::NetBSD96
)
57
8
      create = true;
58
104
  }
59
60
163
  if (create)
61
67
    return new DynamicLoaderPOSIXDYLD(process);
62
96
  return nullptr;
63
163
}
64
65
DynamicLoaderPOSIXDYLD::DynamicLoaderPOSIXDYLD(Process *process)
66
    : DynamicLoader(process), m_rendezvous(process),
67
      m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS),
68
      m_auxv(), m_dyld_bid(LLDB_INVALID_BREAK_ID),
69
      m_vdso_base(LLDB_INVALID_ADDRESS),
70
67
      m_interpreter_base(LLDB_INVALID_ADDRESS), m_initial_modules_added(false) {
71
67
}
72
73
67
DynamicLoaderPOSIXDYLD::~DynamicLoaderPOSIXDYLD() {
74
67
  if (m_dyld_bid != LLDB_INVALID_BREAK_ID) {
75
2
    m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid);
76
2
    m_dyld_bid = LLDB_INVALID_BREAK_ID;
77
2
  }
78
67
}
79
80
67
void DynamicLoaderPOSIXDYLD::DidAttach() {
81
67
  Log *log = GetLog(LLDBLog::DynamicLoader);
82
67
  LLDB_LOGF(log, "DynamicLoaderPOSIXDYLD::%s() pid %" PRIu64, __FUNCTION__,
83
67
            m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
84
67
  m_auxv = std::make_unique<AuxVector>(m_process->GetAuxvData());
85
86
67
  LLDB_LOGF(
87
67
      log, "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " reloaded auxv data",
88
67
      __FUNCTION__, m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
89
90
67
  ModuleSP executable_sp = GetTargetExecutable();
91
67
  ResolveExecutableModule(executable_sp);
92
67
  m_rendezvous.UpdateExecutablePath();
93
94
  // find the main process load offset
95
67
  addr_t load_offset = ComputeLoadOffset();
96
67
  LLDB_LOGF(log,
97
67
            "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
98
67
            " executable '%s', load_offset 0x%" PRIx64,
99
67
            __FUNCTION__,
100
67
            m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID,
101
67
            executable_sp ? executable_sp->GetFileSpec().GetPath().c_str()
102
67
                          : "<null executable>",
103
67
            load_offset);
104
105
67
  EvalSpecialModulesStatus();
106
107
  // if we dont have a load address we cant re-base
108
67
  bool rebase_exec = load_offset != LLDB_INVALID_ADDRESS;
109
110
  // if we have a valid executable
111
67
  if (executable_sp.get()) {
112
21
    lldb_private::ObjectFile *obj = executable_sp->GetObjectFile();
113
21
    if (obj) {
114
      // don't rebase if the module already has a load address
115
21
      Target &target = m_process->GetTarget();
116
21
      Address addr = obj->GetImageInfoAddress(&target);
117
21
      if (addr.GetLoadAddress(&target) != LLDB_INVALID_ADDRESS)
118
0
        rebase_exec = false;
119
21
    }
120
46
  } else {
121
    // no executable, nothing to re-base
122
46
    rebase_exec = false;
123
46
  }
124
125
  // if the target executable should be re-based
126
67
  if (rebase_exec) {
127
20
    ModuleList module_list;
128
129
20
    module_list.Append(executable_sp);
130
20
    LLDB_LOGF(log,
131
20
              "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
132
20
              " added executable '%s' to module load list",
133
20
              __FUNCTION__,
134
20
              m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID,
135
20
              executable_sp->GetFileSpec().GetPath().c_str());
136
137
20
    UpdateLoadedSections(executable_sp, LLDB_INVALID_ADDRESS, load_offset,
138
20
                         true);
139
140
20
    LoadAllCurrentModules();
141
142
20
    m_process->GetTarget().ModulesDidLoad(module_list);
143
20
    if (log) {
144
0
      LLDB_LOGF(log,
145
0
                "DynamicLoaderPOSIXDYLD::%s told the target about the "
146
0
                "modules that loaded:",
147
0
                __FUNCTION__);
148
0
      for (auto module_sp : module_list.Modules()) {
149
0
        LLDB_LOGF(log, "-- [module] %s (pid %" PRIu64 ")",
150
0
                  module_sp ? module_sp->GetFileSpec().GetPath().c_str()
151
0
                            : "<null>",
152
0
                  m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
153
0
      }
154
0
    }
155
20
  }
156
157
67
  if (executable_sp.get()) {
158
21
    if (!SetRendezvousBreakpoint()) {
159
      // If we cannot establish rendezvous breakpoint right now we'll try again
160
      // at entry point.
161
19
      ProbeEntry();
162
19
    }
163
21
  }
164
67
}
165
166
0
void DynamicLoaderPOSIXDYLD::DidLaunch() {
167
0
  Log *log = GetLog(LLDBLog::DynamicLoader);
168
0
  LLDB_LOGF(log, "DynamicLoaderPOSIXDYLD::%s()", __FUNCTION__);
169
170
0
  ModuleSP executable;
171
0
  addr_t load_offset;
172
173
0
  m_auxv = std::make_unique<AuxVector>(m_process->GetAuxvData());
174
175
0
  executable = GetTargetExecutable();
176
0
  load_offset = ComputeLoadOffset();
177
0
  EvalSpecialModulesStatus();
178
179
0
  if (executable.get() && load_offset != LLDB_INVALID_ADDRESS) {
180
0
    ModuleList module_list;
181
0
    module_list.Append(executable);
182
0
    UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
183
184
0
    LLDB_LOGF(log, "DynamicLoaderPOSIXDYLD::%s about to call ProbeEntry()",
185
0
              __FUNCTION__);
186
187
0
    if (!SetRendezvousBreakpoint()) {
188
      // If we cannot establish rendezvous breakpoint right now we'll try again
189
      // at entry point.
190
0
      ProbeEntry();
191
0
    }
192
193
0
    LoadVDSO();
194
0
    m_process->GetTarget().ModulesDidLoad(module_list);
195
0
  }
196
0
}
197
198
0
Status DynamicLoaderPOSIXDYLD::CanLoadImage() { return Status(); }
199
200
void DynamicLoaderPOSIXDYLD::UpdateLoadedSections(ModuleSP module,
201
                                                  addr_t link_map_addr,
202
                                                  addr_t base_addr,
203
37
                                                  bool base_addr_is_offset) {
204
37
  m_loaded_modules[module] = link_map_addr;
205
37
  UpdateLoadedSectionsCommon(module, base_addr, base_addr_is_offset);
206
37
}
207
208
0
void DynamicLoaderPOSIXDYLD::UnloadSections(const ModuleSP module) {
209
0
  m_loaded_modules.erase(module);
210
211
0
  UnloadSectionsCommon(module);
212
0
}
213
214
19
void DynamicLoaderPOSIXDYLD::ProbeEntry() {
215
19
  Log *log = GetLog(LLDBLog::DynamicLoader);
216
217
  // If we have a core file, we don't need any breakpoints.
218
19
  if (IsCoreFile())
219
18
    return;
220
221
1
  const addr_t entry = GetEntryPoint();
222
1
  if (entry == LLDB_INVALID_ADDRESS) {
223
1
    LLDB_LOGF(
224
1
        log,
225
1
        "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
226
1
        " GetEntryPoint() returned no address, not setting entry breakpoint",
227
1
        __FUNCTION__, m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
228
1
    return;
229
1
  }
230
231
0
  LLDB_LOGF(log,
232
0
            "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
233
0
            " GetEntryPoint() returned address 0x%" PRIx64
234
0
            ", setting entry breakpoint",
235
0
            __FUNCTION__,
236
0
            m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID, entry);
237
238
0
  if (m_process) {
239
0
    Breakpoint *const entry_break =
240
0
        m_process->GetTarget().CreateBreakpoint(entry, true, false).get();
241
0
    entry_break->SetCallback(EntryBreakpointHit, this, true);
242
0
    entry_break->SetBreakpointKind("shared-library-event");
243
244
    // Shoudn't hit this more than once.
245
0
    entry_break->SetOneShot(true);
246
0
  }
247
0
}
248
249
// The runtime linker has run and initialized the rendezvous structure once the
250
// process has hit its entry point.  When we hit the corresponding breakpoint
251
// we interrogate the rendezvous structure to get the load addresses of all
252
// dependent modules for the process.  Similarly, we can discover the runtime
253
// linker function and setup a breakpoint to notify us of any dynamically
254
// loaded modules (via dlopen).
255
bool DynamicLoaderPOSIXDYLD::EntryBreakpointHit(
256
    void *baton, StoppointCallbackContext *context, user_id_t break_id,
257
0
    user_id_t break_loc_id) {
258
0
  assert(baton && "null baton");
259
0
  if (!baton)
260
0
    return false;
261
262
0
  Log *log = GetLog(LLDBLog::DynamicLoader);
263
0
  DynamicLoaderPOSIXDYLD *const dyld_instance =
264
0
      static_cast<DynamicLoaderPOSIXDYLD *>(baton);
265
0
  LLDB_LOGF(log, "DynamicLoaderPOSIXDYLD::%s called for pid %" PRIu64,
266
0
            __FUNCTION__,
267
0
            dyld_instance->m_process ? dyld_instance->m_process->GetID()
268
0
                                     : LLDB_INVALID_PROCESS_ID);
269
270
  // Disable the breakpoint --- if a stop happens right after this, which we've
271
  // seen on occasion, we don't want the breakpoint stepping thread-plan logic
272
  // to show a breakpoint instruction at the disassembled entry point to the
273
  // program.  Disabling it prevents it.  (One-shot is not enough - one-shot
274
  // removal logic only happens after the breakpoint goes public, which wasn't
275
  // happening in our scenario).
276
0
  if (dyld_instance->m_process) {
277
0
    BreakpointSP breakpoint_sp =
278
0
        dyld_instance->m_process->GetTarget().GetBreakpointByID(break_id);
279
0
    if (breakpoint_sp) {
280
0
      LLDB_LOGF(log,
281
0
                "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
282
0
                " disabling breakpoint id %" PRIu64,
283
0
                __FUNCTION__, dyld_instance->m_process->GetID(), break_id);
284
0
      breakpoint_sp->SetEnabled(false);
285
0
    } else {
286
0
      LLDB_LOGF(log,
287
0
                "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
288
0
                " failed to find breakpoint for breakpoint id %" PRIu64,
289
0
                __FUNCTION__, dyld_instance->m_process->GetID(), break_id);
290
0
    }
291
0
  } else {
292
0
    LLDB_LOGF(log,
293
0
              "DynamicLoaderPOSIXDYLD::%s breakpoint id %" PRIu64
294
0
              " no Process instance!  Cannot disable breakpoint",
295
0
              __FUNCTION__, break_id);
296
0
  }
297
298
0
  dyld_instance->LoadAllCurrentModules();
299
0
  dyld_instance->SetRendezvousBreakpoint();
300
0
  return false; // Continue running.
301
0
}
302
303
21
bool DynamicLoaderPOSIXDYLD::SetRendezvousBreakpoint() {
304
21
  Log *log = GetLog(LLDBLog::DynamicLoader);
305
306
  // If we have a core file, we don't need any breakpoints.
307
21
  if (IsCoreFile())
308
18
    return false;
309
310
3
  if (m_dyld_bid != LLDB_INVALID_BREAK_ID) {
311
0
    LLDB_LOG(log,
312
0
             "Rendezvous breakpoint breakpoint id {0} for pid {1}"
313
0
             "is already set.",
314
0
             m_dyld_bid,
315
0
             m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
316
0
    return true;
317
0
  }
318
319
3
  addr_t break_addr;
320
3
  Target &target = m_process->GetTarget();
321
3
  BreakpointSP dyld_break;
322
3
  if (m_rendezvous.IsValid() && 
m_rendezvous.GetBreakAddress() != 02
) {
323
2
    break_addr = m_rendezvous.GetBreakAddress();
324
2
    LLDB_LOG(log, "Setting rendezvous break address for pid {0} at {1:x}",
325
2
             m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID,
326
2
             break_addr);
327
2
    dyld_break = target.CreateBreakpoint(break_addr, true, false);
328
2
  } else {
329
1
    LLDB_LOG(log, "Rendezvous structure is not set up yet. "
330
1
                  "Trying to locate rendezvous breakpoint in the interpreter "
331
1
                  "by symbol name.");
332
    // Function names from different dynamic loaders that are known to be
333
    // used as rendezvous between the loader and debuggers.
334
1
    static std::vector<std::string> DebugStateCandidates{
335
1
        "_dl_debug_state", "rtld_db_dlactivity", "__dl_rtld_db_dlactivity",
336
1
        "r_debug_state",   "_r_debug_state",     "_rtld_debug_state",
337
1
    };
338
339
1
    ModuleSP interpreter = LoadInterpreterModule();
340
1
    if (!interpreter) {
341
1
      FileSpecList containingModules;
342
1
      containingModules.Append(
343
1
          m_process->GetTarget().GetExecutableModulePointer()->GetFileSpec());
344
345
1
      dyld_break = target.CreateBreakpoint(
346
1
          &containingModules, /*containingSourceFiles=*/nullptr,
347
1
          DebugStateCandidates, eFunctionNameTypeFull, eLanguageTypeC,
348
1
          /*m_offset=*/0,
349
1
          /*skip_prologue=*/eLazyBoolNo,
350
1
          /*internal=*/true,
351
1
          /*request_hardware=*/false);
352
1
    } else {
353
0
      FileSpecList containingModules;
354
0
      containingModules.Append(interpreter->GetFileSpec());
355
0
      dyld_break = target.CreateBreakpoint(
356
0
          &containingModules, /*containingSourceFiles=*/nullptr,
357
0
          DebugStateCandidates, eFunctionNameTypeFull, eLanguageTypeC,
358
0
          /*m_offset=*/0,
359
0
          /*skip_prologue=*/eLazyBoolNo,
360
0
          /*internal=*/true,
361
0
          /*request_hardware=*/false);
362
0
    }
363
1
  }
364
365
3
  if (dyld_break->GetNumResolvedLocations() != 1) {
366
1
    LLDB_LOG(
367
1
        log,
368
1
        "Rendezvous breakpoint has abnormal number of"
369
1
        " resolved locations ({0}) in pid {1}. It's supposed to be exactly 1.",
370
1
        dyld_break->GetNumResolvedLocations(),
371
1
        m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
372
373
1
    target.RemoveBreakpointByID(dyld_break->GetID());
374
1
    return false;
375
1
  }
376
377
2
  BreakpointLocationSP location = dyld_break->GetLocationAtIndex(0);
378
2
  LLDB_LOG(log,
379
2
           "Successfully set rendezvous breakpoint at address {0:x} "
380
2
           "for pid {1}",
381
2
           location->GetLoadAddress(),
382
2
           m_process ? m_process->GetID() : LLDB_INVALID_PROCESS_ID);
383
384
2
  dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
385
2
  dyld_break->SetBreakpointKind("shared-library-event");
386
2
  m_dyld_bid = dyld_break->GetID();
387
2
  return true;
388
3
}
389
390
bool DynamicLoaderPOSIXDYLD::RendezvousBreakpointHit(
391
    void *baton, StoppointCallbackContext *context, user_id_t break_id,
392
0
    user_id_t break_loc_id) {
393
0
  assert(baton && "null baton");
394
0
  if (!baton)
395
0
    return false;
396
397
0
  Log *log = GetLog(LLDBLog::DynamicLoader);
398
0
  DynamicLoaderPOSIXDYLD *const dyld_instance =
399
0
      static_cast<DynamicLoaderPOSIXDYLD *>(baton);
400
0
  LLDB_LOGF(log, "DynamicLoaderPOSIXDYLD::%s called for pid %" PRIu64,
401
0
            __FUNCTION__,
402
0
            dyld_instance->m_process ? dyld_instance->m_process->GetID()
403
0
                                     : LLDB_INVALID_PROCESS_ID);
404
405
0
  dyld_instance->RefreshModules();
406
407
  // Return true to stop the target, false to just let the target run.
408
0
  const bool stop_when_images_change = dyld_instance->GetStopWhenImagesChange();
409
0
  LLDB_LOGF(log,
410
0
            "DynamicLoaderPOSIXDYLD::%s pid %" PRIu64
411
0
            " stop_when_images_change=%s",
412
0
            __FUNCTION__,
413
0
            dyld_instance->m_process ? dyld_instance->m_process->GetID()
414
0
                                     : LLDB_INVALID_PROCESS_ID,
415
0
            stop_when_images_change ? "true" : "false");
416
0
  return stop_when_images_change;
417
0
}
418
419
0
void DynamicLoaderPOSIXDYLD::RefreshModules() {
420
0
  if (!m_rendezvous.Resolve())
421
0
    return;
422
423
0
  DYLDRendezvous::iterator I;
424
0
  DYLDRendezvous::iterator E;
425
426
0
  ModuleList &loaded_modules = m_process->GetTarget().GetImages();
427
428
0
  if (m_rendezvous.ModulesDidLoad() || !m_initial_modules_added) {
429
0
    ModuleList new_modules;
430
431
    // If this is the first time rendezvous breakpoint fires, we need
432
    // to take care of adding all the initial modules reported by
433
    // the loader.  This is necessary to list ld-linux.so on Linux,
434
    // and all DT_NEEDED entries on *BSD.
435
0
    if (m_initial_modules_added) {
436
0
      I = m_rendezvous.loaded_begin();
437
0
      E = m_rendezvous.loaded_end();
438
0
    } else {
439
0
      I = m_rendezvous.begin();
440
0
      E = m_rendezvous.end();
441
0
      m_initial_modules_added = true;
442
0
    }
443
0
    for (; I != E; ++I) {
444
0
      ModuleSP module_sp =
445
0
          LoadModuleAtAddress(I->file_spec, I->link_addr, I->base_addr, true);
446
0
      if (!module_sp.get())
447
0
        continue;
448
449
0
      if (module_sp->GetObjectFile()->GetBaseAddress().GetLoadAddress(
450
0
              &m_process->GetTarget()) == m_interpreter_base) {
451
0
        ModuleSP interpreter_sp = m_interpreter_module.lock();
452
0
        if (m_interpreter_module.lock() == nullptr) {
453
0
          m_interpreter_module = module_sp;
454
0
        } else if (module_sp == interpreter_sp) {
455
          // Module already loaded.
456
0
          continue;
457
0
        } else {
458
          // If this is a duplicate instance of ld.so, unload it.  We may end
459
          // up with it if we load it via a different path than before
460
          // (symlink vs real path).
461
          // TODO: remove this once we either fix library matching or avoid
462
          // loading the interpreter when setting the rendezvous breakpoint.
463
0
          UnloadSections(module_sp);
464
0
          loaded_modules.Remove(module_sp);
465
0
          continue;
466
0
        }
467
0
      }
468
469
0
      loaded_modules.AppendIfNeeded(module_sp);
470
0
      new_modules.Append(module_sp);
471
0
    }
472
0
    m_process->GetTarget().ModulesDidLoad(new_modules);
473
0
  }
474
475
0
  if (m_rendezvous.ModulesDidUnload()) {
476
0
    ModuleList old_modules;
477
478
0
    E = m_rendezvous.unloaded_end();
479
0
    for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
480
0
      ModuleSpec module_spec{I->file_spec};
481
0
      ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
482
483
0
      if (module_sp.get()) {
484
0
        old_modules.Append(module_sp);
485
0
        UnloadSections(module_sp);
486
0
      }
487
0
    }
488
0
    loaded_modules.Remove(old_modules);
489
0
    m_process->GetTarget().ModulesDidUnload(old_modules, false);
490
0
  }
491
0
}
492
493
ThreadPlanSP
494
DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread,
495
0
                                                     bool stop) {
496
0
  ThreadPlanSP thread_plan_sp;
497
498
0
  StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
499
0
  const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
500
0
  Symbol *sym = context.symbol;
501
502
0
  if (sym == nullptr || !sym->IsTrampoline())
503
0
    return thread_plan_sp;
504
505
0
  ConstString sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
506
0
  if (!sym_name)
507
0
    return thread_plan_sp;
508
509
0
  SymbolContextList target_symbols;
510
0
  Target &target = thread.GetProcess()->GetTarget();
511
0
  const ModuleList &images = target.GetImages();
512
513
0
  images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
514
0
  if (!target_symbols.GetSize())
515
0
    return thread_plan_sp;
516
517
0
  typedef std::vector<lldb::addr_t> AddressVector;
518
0
  AddressVector addrs;
519
0
  for (const SymbolContext &context : target_symbols) {
520
0
    AddressRange range;
521
0
    context.GetAddressRange(eSymbolContextEverything, 0, false, range);
522
0
    lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
523
0
    if (addr != LLDB_INVALID_ADDRESS)
524
0
      addrs.push_back(addr);
525
0
  }
526
527
0
  if (addrs.size() > 0) {
528
0
    AddressVector::iterator start = addrs.begin();
529
0
    AddressVector::iterator end = addrs.end();
530
531
0
    llvm::sort(start, end);
532
0
    addrs.erase(std::unique(start, end), end);
533
0
    thread_plan_sp =
534
0
        std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop);
535
0
  }
536
537
0
  return thread_plan_sp;
538
0
}
539
540
20
void DynamicLoaderPOSIXDYLD::LoadVDSO() {
541
20
  if (m_vdso_base == LLDB_INVALID_ADDRESS)
542
7
    return;
543
544
13
  FileSpec file("[vdso]");
545
546
13
  MemoryRegionInfo info;
547
13
  Status status = m_process->GetMemoryRegionInfo(m_vdso_base, info);
548
13
  if (status.Fail()) {
549
0
    Log *log = GetLog(LLDBLog::DynamicLoader);
550
0
    LLDB_LOG(log, "Failed to get vdso region info: {0}", status);
551
0
    return;
552
0
  }
553
554
13
  if (ModuleSP module_sp = m_process->ReadModuleFromMemory(
555
13
          file, m_vdso_base, info.GetRange().GetByteSize())) {
556
13
    UpdateLoadedSections(module_sp, LLDB_INVALID_ADDRESS, m_vdso_base, false);
557
13
    m_process->GetTarget().GetImages().AppendIfNeeded(module_sp);
558
13
  }
559
13
}
560
561
1
ModuleSP DynamicLoaderPOSIXDYLD::LoadInterpreterModule() {
562
1
  if (m_interpreter_base == LLDB_INVALID_ADDRESS)
563
1
    return nullptr;
564
565
0
  MemoryRegionInfo info;
566
0
  Target &target = m_process->GetTarget();
567
0
  Status status = m_process->GetMemoryRegionInfo(m_interpreter_base, info);
568
0
  if (status.Fail() || info.GetMapped() != MemoryRegionInfo::eYes ||
569
0
      info.GetName().IsEmpty()) {
570
0
    Log *log = GetLog(LLDBLog::DynamicLoader);
571
0
    LLDB_LOG(log, "Failed to get interpreter region info: {0}", status);
572
0
    return nullptr;
573
0
  }
574
575
0
  FileSpec file(info.GetName().GetCString());
576
0
  ModuleSpec module_spec(file, target.GetArchitecture());
577
578
0
  if (ModuleSP module_sp = target.GetOrCreateModule(module_spec,
579
0
                                                    true /* notify */)) {
580
0
    UpdateLoadedSections(module_sp, LLDB_INVALID_ADDRESS, m_interpreter_base,
581
0
                         false);
582
0
    m_interpreter_module = module_sp;
583
0
    return module_sp;
584
0
  }
585
0
  return nullptr;
586
0
}
587
588
ModuleSP DynamicLoaderPOSIXDYLD::LoadModuleAtAddress(const FileSpec &file,
589
                                                     addr_t link_map_addr,
590
                                                     addr_t base_addr,
591
20
                                                     bool base_addr_is_offset) {
592
20
  if (ModuleSP module_sp = DynamicLoader::LoadModuleAtAddress(
593
20
          file, link_map_addr, base_addr, base_addr_is_offset))
594
3
    return module_sp;
595
596
  // This works around an dynamic linker "bug" on android <= 23, where the
597
  // dynamic linker would report the application name
598
  // (e.g. com.example.myapplication) instead of the main process binary
599
  // (/system/bin/app_process(32)). The logic is not sound in general (it
600
  // assumes base_addr is the real address, even though it actually is a load
601
  // bias), but it happens to work on android because app_process has a file
602
  // address of zero.
603
  // This should be removed after we drop support for android-23.
604
17
  if (m_process->GetTarget().GetArchitecture().GetTriple().isAndroid()) {
605
1
    MemoryRegionInfo memory_info;
606
1
    Status error = m_process->GetMemoryRegionInfo(base_addr, memory_info);
607
1
    if (error.Success() && memory_info.GetMapped() &&
608
1
        memory_info.GetRange().GetRangeBase() == base_addr &&
609
1
        !(memory_info.GetName().IsEmpty())) {
610
1
      if (ModuleSP module_sp = DynamicLoader::LoadModuleAtAddress(
611
1
              FileSpec(memory_info.GetName().GetStringRef()), link_map_addr,
612
1
              base_addr, base_addr_is_offset))
613
1
        return module_sp;
614
1
    }
615
1
  }
616
617
16
  return nullptr;
618
17
}
619
620
20
void DynamicLoaderPOSIXDYLD::LoadAllCurrentModules() {
621
20
  DYLDRendezvous::iterator I;
622
20
  DYLDRendezvous::iterator E;
623
20
  ModuleList module_list;
624
20
  Log *log = GetLog(LLDBLog::DynamicLoader);
625
626
20
  LoadVDSO();
627
628
20
  if (!m_rendezvous.Resolve()) {
629
12
    LLDB_LOGF(log,
630
12
              "DynamicLoaderPOSIXDYLD::%s unable to resolve POSIX DYLD "
631
12
              "rendezvous address",
632
12
              __FUNCTION__);
633
12
    return;
634
12
  }
635
636
  // The rendezvous class doesn't enumerate the main module, so track that
637
  // ourselves here.
638
8
  ModuleSP executable = GetTargetExecutable();
639
8
  m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
640
641
8
  std::vector<FileSpec> module_names;
642
28
  for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; 
++I20
)
643
20
    module_names.push_back(I->file_spec);
644
8
  m_process->PrefetchModuleSpecs(
645
8
      module_names, m_process->GetTarget().GetArchitecture().GetTriple());
646
647
28
  for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; 
++I20
) {
648
20
    ModuleSP module_sp =
649
20
        LoadModuleAtAddress(I->file_spec, I->link_addr, I->base_addr, true);
650
20
    if (module_sp.get()) {
651
4
      LLDB_LOG(log, "LoadAllCurrentModules loading module: {0}",
652
4
               I->file_spec.GetFilename());
653
4
      module_list.Append(module_sp);
654
16
    } else {
655
16
      Log *log = GetLog(LLDBLog::DynamicLoader);
656
16
      LLDB_LOGF(
657
16
          log,
658
16
          "DynamicLoaderPOSIXDYLD::%s failed loading module %s at 0x%" PRIx64,
659
16
          __FUNCTION__, I->file_spec.GetPath().c_str(), I->base_addr);
660
16
    }
661
20
  }
662
663
8
  m_process->GetTarget().ModulesDidLoad(module_list);
664
8
  m_initial_modules_added = true;
665
8
}
666
667
67
addr_t DynamicLoaderPOSIXDYLD::ComputeLoadOffset() {
668
67
  addr_t virt_entry;
669
670
67
  if (m_load_offset != LLDB_INVALID_ADDRESS)
671
0
    return m_load_offset;
672
673
67
  if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
674
7
    return LLDB_INVALID_ADDRESS;
675
676
60
  ModuleSP module = m_process->GetTarget().GetExecutableModule();
677
60
  if (!module)
678
40
    return LLDB_INVALID_ADDRESS;
679
680
20
  ObjectFile *exe = module->GetObjectFile();
681
20
  if (!exe)
682
0
    return LLDB_INVALID_ADDRESS;
683
684
20
  Address file_entry = exe->GetEntryPointAddress();
685
686
20
  if (!file_entry.IsValid())
687
0
    return LLDB_INVALID_ADDRESS;
688
689
20
  m_load_offset = virt_entry - file_entry.GetFileAddress();
690
20
  return m_load_offset;
691
20
}
692
693
67
void DynamicLoaderPOSIXDYLD::EvalSpecialModulesStatus() {
694
67
  if (std::optional<uint64_t> vdso_base =
695
67
          m_auxv->GetAuxValue(AuxVector::AUXV_AT_SYSINFO_EHDR))
696
37
    m_vdso_base = *vdso_base;
697
698
67
  if (std::optional<uint64_t> interpreter_base =
699
67
          m_auxv->GetAuxValue(AuxVector::AUXV_AT_BASE))
700
58
    m_interpreter_base = *interpreter_base;
701
67
}
702
703
68
addr_t DynamicLoaderPOSIXDYLD::GetEntryPoint() {
704
68
  if (m_entry_point != LLDB_INVALID_ADDRESS)
705
0
    return m_entry_point;
706
707
68
  if (m_auxv == nullptr)
708
0
    return LLDB_INVALID_ADDRESS;
709
710
68
  std::optional<uint64_t> entry_point =
711
68
      m_auxv->GetAuxValue(AuxVector::AUXV_AT_ENTRY);
712
68
  if (!entry_point)
713
8
    return LLDB_INVALID_ADDRESS;
714
715
60
  m_entry_point = static_cast<addr_t>(*entry_point);
716
717
60
  const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
718
719
  // On ppc64, the entry point is actually a descriptor.  Dereference it.
720
60
  if (arch.GetMachine() == llvm::Triple::ppc64)
721
0
    m_entry_point = ReadUnsignedIntWithSizeInBytes(m_entry_point, 8);
722
723
60
  return m_entry_point;
724
68
}
725
726
lldb::addr_t
727
DynamicLoaderPOSIXDYLD::GetThreadLocalData(const lldb::ModuleSP module_sp,
728
                                           const lldb::ThreadSP thread,
729
0
                                           lldb::addr_t tls_file_addr) {
730
0
  auto it = m_loaded_modules.find(module_sp);
731
0
  if (it == m_loaded_modules.end())
732
0
    return LLDB_INVALID_ADDRESS;
733
734
0
  addr_t link_map = it->second;
735
0
  if (link_map == LLDB_INVALID_ADDRESS)
736
0
    return LLDB_INVALID_ADDRESS;
737
738
0
  const DYLDRendezvous::ThreadInfo &metadata = m_rendezvous.GetThreadInfo();
739
0
  if (!metadata.valid)
740
0
    return LLDB_INVALID_ADDRESS;
741
742
  // Get the thread pointer.
743
0
  addr_t tp = thread->GetThreadPointer();
744
0
  if (tp == LLDB_INVALID_ADDRESS)
745
0
    return LLDB_INVALID_ADDRESS;
746
747
  // Find the module's modid.
748
0
  int modid_size = 4; // FIXME(spucci): This isn't right for big-endian 64-bit
749
0
  int64_t modid = ReadUnsignedIntWithSizeInBytes(
750
0
      link_map + metadata.modid_offset, modid_size);
751
0
  if (modid == -1)
752
0
    return LLDB_INVALID_ADDRESS;
753
754
  // Lookup the DTV structure for this thread.
755
0
  addr_t dtv_ptr = tp + metadata.dtv_offset;
756
0
  addr_t dtv = ReadPointer(dtv_ptr);
757
0
  if (dtv == LLDB_INVALID_ADDRESS)
758
0
    return LLDB_INVALID_ADDRESS;
759
760
  // Find the TLS block for this module.
761
0
  addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
762
0
  addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
763
764
0
  Log *log = GetLog(LLDBLog::DynamicLoader);
765
0
  LLDB_LOGF(log,
766
0
            "DynamicLoaderPOSIXDYLD::Performed TLS lookup: "
767
0
            "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
768
0
            ", modid=%" PRId64 ", tls_block=0x%" PRIx64 "\n",
769
0
            module_sp->GetObjectName().AsCString(""), link_map, tp,
770
0
            (int64_t)modid, tls_block);
771
772
0
  if (tls_block == LLDB_INVALID_ADDRESS)
773
0
    return LLDB_INVALID_ADDRESS;
774
0
  else
775
0
    return tls_block + tls_file_addr;
776
0
}
777
778
void DynamicLoaderPOSIXDYLD::ResolveExecutableModule(
779
67
    lldb::ModuleSP &module_sp) {
780
67
  Log *log = GetLog(LLDBLog::DynamicLoader);
781
782
67
  if (m_process == nullptr)
783
0
    return;
784
785
67
  auto &target = m_process->GetTarget();
786
67
  const auto platform_sp = target.GetPlatform();
787
788
67
  ProcessInstanceInfo process_info;
789
67
  if (!m_process->GetProcessInfo(process_info)) {
790
8
    LLDB_LOGF(log,
791
8
              "DynamicLoaderPOSIXDYLD::%s - failed to get process info for "
792
8
              "pid %" PRIu64,
793
8
              __FUNCTION__, m_process->GetID());
794
8
    return;
795
8
  }
796
797
59
  LLDB_LOGF(
798
59
      log, "DynamicLoaderPOSIXDYLD::%s - got executable by pid %" PRIu64 ": %s",
799
59
      __FUNCTION__, m_process->GetID(),
800
59
      process_info.GetExecutableFile().GetPath().c_str());
801
802
59
  ModuleSpec module_spec(process_info.GetExecutableFile(),
803
59
                         process_info.GetArchitecture());
804
59
  if (module_sp && 
module_sp->MatchesModuleSpec(module_spec)18
)
805
18
    return;
806
807
41
  const auto executable_search_paths(Target::GetDefaultExecutableSearchPaths());
808
41
  auto error = platform_sp->ResolveExecutable(
809
41
      module_spec, module_sp,
810
41
      !executable_search_paths.IsEmpty() ? 
&executable_search_paths0
: nullptr);
811
41
  if (error.Fail()) {
812
41
    StreamString stream;
813
41
    module_spec.Dump(stream);
814
815
41
    LLDB_LOGF(log,
816
41
              "DynamicLoaderPOSIXDYLD::%s - failed to resolve executable "
817
41
              "with module spec \"%s\": %s",
818
41
              __FUNCTION__, stream.GetData(), error.AsCString());
819
41
    return;
820
41
  }
821
822
0
  target.SetExecutableModule(module_sp, eLoadDependentsNo);
823
0
}
824
825
bool DynamicLoaderPOSIXDYLD::AlwaysRelyOnEHUnwindInfo(
826
48
    lldb_private::SymbolContext &sym_ctx) {
827
48
  ModuleSP module_sp;
828
48
  if (sym_ctx.symbol)
829
48
    module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
830
48
  if (!module_sp && 
sym_ctx.function0
)
831
0
    module_sp =
832
0
        sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
833
48
  if (!module_sp)
834
0
    return false;
835
836
48
  return module_sp->GetFileSpec().GetPath() == "[vdso]";
837
48
}
838
839
40
bool DynamicLoaderPOSIXDYLD::IsCoreFile() const {
840
40
  return !m_process->IsLiveDebugSession();
841
40
}