LLDB mainline
DynamicLoaderWindowsDYLD.cpp
Go to the documentation of this file.
1//===-- DynamicLoaderWindowsDYLD.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
10
13#include "lldb/Core/Module.h"
18#include "lldb/Target/Process.h"
20#include "lldb/Target/Target.h"
23#include "lldb/Utility/Log.h"
24
25#include "llvm/TargetParser/Triple.h"
26
27using namespace lldb;
28using namespace lldb_private;
29
31
34
36
41
45
47 return "Dynamic loader plug-in that watches for shared library "
48 "loads/unloads in Windows processes.";
49}
50
52 bool force) {
53 bool should_create = force;
54 if (!should_create) {
55 const llvm::Triple &triple_ref =
56 process->GetTarget().GetArchitecture().GetTriple();
57 if (triple_ref.getOS() == llvm::Triple::Win32)
58 should_create = true;
59 }
60
61 if (should_create)
62 return new DynamicLoaderWindowsDYLD(process);
63
64 return nullptr;
65}
66
68 const ModuleSpec module_spec,
69 lldb::addr_t module_addr) {
70 // Resolve the module unless we already have one.
71 if (!module_sp) {
73 module_sp = m_process->GetTarget().GetOrCreateModule(
74 module_spec, true /* notify */, &error);
75 if (error.Fail())
76 return;
77 }
78
79 m_loaded_modules.insert({module_addr, lldb::ModuleWP(module_sp)});
80 UpdateLoadedSectionsCommon(module_sp, module_addr, false);
81 ModuleList module_list;
82 module_list.Append(module_sp);
83 m_process->GetTarget().ModulesDidLoad(module_list);
84}
85
87 auto it = m_loaded_modules.find(module_addr);
88 if (it == m_loaded_modules.end())
89 return;
90
91 ModuleSP module_sp = it->second.lock();
92 m_loaded_modules.erase(it);
93
94 if (!module_sp)
95 return;
96
97 bool full_unload = true;
98 for (const auto &entry : m_loaded_modules) {
99 ModuleSP other_sp = entry.second.lock();
100 if (other_sp == module_sp) {
101 UpdateLoadedSectionsCommon(module_sp, entry.first, false);
102 full_unload = false;
103 }
104 }
105
106 if (full_unload) {
107 UnloadSectionsCommon(module_sp);
108 ModuleList module_list;
109 module_list.Append(module_sp);
110 m_process->GetTarget().ModulesDidUnload(module_list, false);
111 }
112}
113
115 // First, see if the load address is already cached.
116 for (const auto &entry : m_loaded_modules) {
117 ModuleSP mod = entry.second.lock();
118 if (mod == executable && entry.first != LLDB_INVALID_ADDRESS)
119 return entry.first;
120 }
121
123
124 // Second, try to get it through the process plugins. For a remote process,
125 // the remote platform will be responsible for providing it.
126 FileSpec file_spec(executable->GetPlatformFileSpec());
127 bool is_loaded = false;
128 Status status =
129 m_process->GetFileLoadAddress(file_spec, is_loaded, load_addr);
130 // Servers other than lldb server could respond with a bogus address.
131 if (status.Success() && is_loaded && load_addr != LLDB_INVALID_ADDRESS) {
132 m_loaded_modules.insert({load_addr, lldb::ModuleWP(executable)});
133 return load_addr;
134 }
135
137}
138
141 LLDB_LOGF(log, "DynamicLoaderWindowsDYLD::%s()", __FUNCTION__);
142
144
145 ModuleSP executable = GetTargetExecutable();
146
147 if (!executable)
148 return;
149
150 // Try to fetch the load address of the file from the process, since there
151 // could be randomization of the load address.
152 lldb::addr_t load_addr = GetLoadAddress(executable);
153 if (load_addr == LLDB_INVALID_ADDRESS) {
154 // The process does not know the executable under the target's path: it
155 // was started through another path to the same file, or runs a different
156 // one. Take the modules it reports as loaded, which replaces the target's
157 // executable with the process's.
158 auto error = m_process->LoadModules();
159 if (!error)
160 return;
161 LLDB_LOG_ERROR(log, std::move(error), "failed to load modules: {0}");
162
163 // If the load address couldn't be determined (e.g. for a remote gdbstub
164 // target), fall back to the preferred load address/image base from the
165 // file if the process is live.
166 // This is a best-effort guess, if the image isn't loaded there the
167 // sections will have incorrect addresses and the slide will have to be
168 // specified manually.
169 if (!m_process->IsLiveDebugSession())
170 return;
171
172 ObjectFile *object_file = executable->GetObjectFile();
173 if (!object_file)
174 return;
175
176 load_addr = object_file->GetBaseAddress().GetFileAddress();
177 if (load_addr == LLDB_INVALID_ADDRESS)
178 return;
179
180 executable->ReportWarning(
181 "failed to get load address, assuming image base at {0:x}", load_addr);
182 } else {
183 // Request the process base address.
184 lldb::addr_t image_base = m_process->GetImageInfoAddress();
185 if (image_base == load_addr)
186 return;
187 }
188
189 // Rebase the process's modules if there is a mismatch.
190 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_addr, false);
191
192 ModuleList module_list;
193 module_list.Append(executable);
194 m_process->GetTarget().ModulesDidLoad(module_list);
195 auto error = m_process->LoadModules();
196 LLDB_LOG_ERROR(log, std::move(error), "failed to load modules: {0}");
197}
198
201 LLDB_LOGF(log, "DynamicLoaderWindowsDYLD::%s()", __FUNCTION__);
202
204
205 ModuleSP executable = GetTargetExecutable();
206 if (!executable)
207 return;
208
209 lldb::addr_t load_addr = GetLoadAddress(executable);
210 if (load_addr != LLDB_INVALID_ADDRESS) {
211 // Update the loaded sections so that the breakpoints can be resolved.
212 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_addr, false);
213
214 ModuleList module_list;
215 module_list.Append(executable);
216 m_process->GetTarget().ModulesDidLoad(module_list);
217 auto error = m_process->LoadModules();
218 LLDB_LOG_ERROR(log, std::move(error), "failed to load modules: {0}");
219 }
220}
221
223
226 bool stop) {
227 auto arch = m_process->GetTarget().GetArchitecture();
228 if (arch.GetMachine() != llvm::Triple::x86) {
229 return ThreadPlanSP();
230 }
231
232 RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
233 if (!reg_ctx_sp)
234 return ThreadPlanSP();
235
236 uint64_t pc = reg_ctx_sp->GetPC();
237 // Max size of an instruction in x86 is 15 bytes.
238 AddressRange range(pc, 2 * 15);
239
241 arch, nullptr, nullptr, nullptr, nullptr, m_process->GetTarget(), range);
242 if (!disassembler_sp) {
243 return ThreadPlanSP();
244 }
245
246 InstructionList &insn_list = disassembler_sp->GetInstructionList();
247
248 // First instruction in a x86 Windows trampoline is going to be an indirect
249 // jump through the IAT and the next one will be a nop (usually there for
250 // alignment purposes). e.g.:
251 // 0x70ff4cfc <+956>: jmpl *0x7100c2a8
252 // 0x70ff4d02 <+962>: nop
253
254 auto first_insn = insn_list.GetInstructionAtIndex(0);
255 auto second_insn = insn_list.GetInstructionAtIndex(1);
256
257 ExecutionContext exe_ctx(m_process->GetTarget());
258 if (first_insn == nullptr || second_insn == nullptr)
259 return ThreadPlanSP();
260
261 const char *first_mnemonic = first_insn->GetMnemonic(&exe_ctx);
262 const char *second_mnemonic = second_insn->GetMnemonic(&exe_ctx);
263 if (!first_mnemonic || !second_mnemonic ||
264 strcmp(first_mnemonic, "jmpl") != 0 ||
265 strcmp(second_mnemonic, "nop") != 0)
266 return ThreadPlanSP();
267
268 assert(first_insn->DoesBranch() && !second_insn->DoesBranch());
269
271 thread, false, false, eVoteNoOpinion, eVoteNoOpinion));
272}
273
276 lldb::ThreadSP thread,
277 lldb::addr_t tls_file_addr) {
279 ObjectFile *obj = module->GetObjectFile();
280 if (!obj) {
281 LLDB_LOG(log, "no object file for module");
283 }
284 std::string object_name;
285 if (log)
286 object_name = obj->GetObjectName();
287
288 StructuredData::ObjectSP extended_info = thread->GetExtendedInfo();
289 if (!extended_info) {
290 LLDB_LOG(log, "missing extended info of thread");
292 }
293 StructuredData::Dictionary *dict = extended_info->GetAsDictionary();
294 if (!dict) {
295 LLDB_LOG(log, "extended info of thread is not a dictionary");
297 }
298 addr_t teb_base = 0;
299 if (!dict->GetValueForKeyAsInteger("teb_address", teb_base) || !teb_base ||
300 teb_base == LLDB_INVALID_ADDRESS) {
301 LLDB_LOG(log, "missing 'teb_address' in extended thread info");
303 }
304
305 ProcessSP process = thread->GetProcess();
306 if (!process) {
307 LLDB_LOG(log, "missing process");
309 }
310 uint32_t addr_byte_size = process->GetAddressByteSize();
311 addr_t tls_array_addr = teb_base + 11 * addr_byte_size;
312 llvm::Expected<addr_t> tls_array =
313 process->ReadPointerFromMemory(tls_array_addr);
314 if (!tls_array || *tls_array == LLDB_INVALID_ADDRESS) {
315 LLDB_LOG_ERROR(log, tls_array.takeError(),
316 "failed to read TLS array from {1:x16}: {0}",
317 tls_array_addr);
319 }
320
321 Address tls_index_addr;
322 if (!GetTlsIndexAddressForModule(module, tls_index_addr)) {
323 LLDB_LOG(log, "failed to resolve tls index for {0}", object_name);
325 }
326
327 Target &target = process->GetTarget();
328 addr_t tls_index_load_addr = tls_index_addr.GetLoadAddress(&target);
329 if (tls_index_load_addr == LLDB_INVALID_ADDRESS) {
330 LLDB_LOG(log, "failed to resolve load address of '_tls_index' in {0}",
331 object_name);
333 }
334
336 uint64_t tls_index =
337 process->ReadUnsignedIntegerFromMemory(tls_index_load_addr, 4, 0, error);
338 if (error.Fail()) {
339 LLDB_LOG_ERROR(log, error.takeError(),
340 "failed to read '_tls_index' in {1} from {2:x8}: {0}",
341 object_name, tls_index_load_addr);
343 }
344
345 addr_t tls_index_item = *tls_array + tls_index * addr_byte_size;
346 LLDB_LOG(log, "tls base address for {0} is at {1:x8} + {2:x8} * {3} = {4:x8}",
347 object_name, *tls_array, tls_index, addr_byte_size, tls_index_item);
348
349 llvm::Expected<addr_t> tls_base =
350 process->ReadPointerFromMemory(tls_index_item);
351 if (!tls_base || *tls_base == LLDB_INVALID_ADDRESS || *tls_base == 0) {
352 LLDB_LOG_ERROR(log, tls_base.takeError(),
353 "failed to read tls array in {1} at index {2} ({3:x8}): {0}",
354 object_name, tls_index, tls_index_item);
356 }
357
358 return *tls_base + tls_file_addr;
359}
360
362 const ModuleSP &module, Address &addr) const {
363 ObjectFilePECOFF *obj =
364 llvm::dyn_cast_or_null<ObjectFilePECOFF>(module->GetObjectFile());
365 if (obj) {
366 addr_t tls_index_file_addr = obj->GetTlsIndexAddress();
367 if (tls_index_file_addr != LLDB_INVALID_ADDRESS &&
368 module->ResolveFileAddress(tls_index_file_addr, addr))
369 return true;
370 }
371
372 // If we can't get the tls index from the object file, try the _tls_index
373 // symbol.
374 Symtab *symtab = module->GetSymtab();
375 if (!symtab)
376 return false;
377
378 Symbol *tls_index_sym = symtab->FindFirstSymbolWithNameAndType(
381 if (!tls_index_sym)
382 return false;
383
384 addr = tls_index_sym->GetAddress();
385 return addr.IsValid();
386}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_PLUGIN_DEFINE(PluginName)
lldb::addr_t GetTlsIndexAddress() const
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:547
A uniqued constant string class.
Definition ConstString.h:40
static lldb::DisassemblerSP DisassembleRange(const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, Target &target, llvm::ArrayRef< AddressRange > disasm_ranges, bool force_live_memory=false)
void DidAttach() override
Called after attaching a process.
void DidLaunch() override
Called after launching a process.
lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr) override
Retrieves the per-module TLS block for a given thread.
llvm::DenseMap< lldb::addr_t, lldb::ModuleWP > m_loaded_modules
Maps load addresses to their corresponding modules.
Status CanLoadImage() override
Ask if it is ok to try and load or unload an shared library (image).
void OnLoadModule(lldb::ModuleSP module_sp, const ModuleSpec module_spec, lldb::addr_t module_addr)
lldb::addr_t GetLoadAddress(lldb::ModuleSP executable)
Returns the load address for the given executable module.
static DynamicLoader * CreateInstance(Process *process, bool force)
lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, bool stop) override
Provides a plan to step through the dynamic loader trampoline for the current state of thread.
bool GetTlsIndexAddressForModule(const lldb::ModuleSP &module, Address &addr) const
Process * m_process
The process that this dynamic loader plug-in is tracking.
void UpdateLoadedSectionsCommon(lldb::ModuleSP module, lldb::addr_t base_addr, bool base_addr_is_offset)
lldb::ModuleSP GetTargetExecutable()
Checks to see if the target module has changed, updates the target accordingly and returns the target...
virtual void UpdateLoadedSections(lldb::ModuleSP module, lldb::addr_t link_map_addr, lldb::addr_t base_addr, bool base_addr_is_offset)
Updates the load address of every allocatable section in module.
DynamicLoader(Process *process)
Construct with a process.
void UnloadSectionsCommon(const lldb::ModuleSP module)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file utility class.
Definition FileSpec.h:56
lldb::InstructionSP GetInstructionAtIndex(size_t idx) const
A collection class for Module objects.
Definition ModuleList.h:128
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
std::string GetObjectName() const
virtual lldb_private::Address GetBaseAddress()
Returns base address of this object file.
Definition ObjectFile.h:469
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:369
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
An error handling class.
Definition Status.h:118
bool Success() const
Test for success condition.
Definition Status.cpp:303
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
std::shared_ptr< Object > ObjectSP
Address GetAddress() const
Definition Symbol.h:98
Symbol * FindFirstSymbolWithNameAndType(ConstString name, lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility)
Definition Symtab.cpp:842
const ArchSpec & GetArchitecture() const
Definition Target.h:1324
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
void RegisterMSVCRTCFrameRecognizer(Target &target)
Registers the MSVC run-time check failure frame recognizer with the target.
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::weak_ptr< lldb_private::Module > ModuleWP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
std::shared_ptr< lldb_private::Module > ModuleSP