LLDB mainline
DynamicLoader.h
Go to the documentation of this file.
1//===-- DynamicLoader.h -----------------------------------------*- C++ -*-===//
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#ifndef LLDB_TARGET_DYNAMICLOADER_H
10#define LLDB_TARGET_DYNAMICLOADER_H
11
12#include "lldb/Core/Address.h"
16#include "lldb/Utility/Status.h"
17#include "lldb/Utility/UUID.h"
18#include "lldb/lldb-defines.h"
19#include "lldb/lldb-forward.h"
21#include "lldb/lldb-types.h"
22
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/Support/Error.h"
25
26#include <cstddef>
27#include <cstdint>
28#include <string>
29namespace lldb_private {
30class ModuleList;
31class Process;
32class SectionList;
33class Symbol;
34class SymbolContext;
36class Thread;
37}
38
39namespace lldb_private {
40
41/// \class DynamicLoader DynamicLoader.h "lldb/Target/DynamicLoader.h"
42/// A plug-in interface definition class for dynamic loaders.
43///
44/// Dynamic loader plug-ins track image (shared library) loading and
45/// unloading. The class is initialized given a live process that is halted at
46/// its entry point or just after attaching.
47///
48/// Dynamic loader plug-ins can track the process by registering callbacks
49/// using the: Process::RegisterNotificationCallbacks (const Notifications&)
50/// function.
51///
52/// Breakpoints can also be set in the process which can register functions
53/// that get called using: Process::BreakpointSetCallback (lldb::user_id_t,
54/// BreakpointHitCallback, void *). These breakpoint callbacks return a
55/// boolean value that indicates if the process should continue or halt and
56/// should return the global setting for this using:
57/// DynamicLoader::StopWhenImagesChange() const.
59public:
60 /// Find a dynamic loader plugin for a given process.
61 ///
62 /// Scans the installed DynamicLoader plug-ins and tries to find an instance
63 /// that can be used to track image changes in \a process.
64 ///
65 /// \param[in] process
66 /// The process for which to try and locate a dynamic loader
67 /// plug-in instance.
68 ///
69 /// \param[in] plugin_name
70 /// An optional name of a specific dynamic loader plug-in that
71 /// should be used. If empty, pick the best plug-in.
72 static DynamicLoader *FindPlugin(Process *process,
73 llvm::StringRef plugin_name);
74
75 /// Construct with a process.
76 DynamicLoader(Process *process);
77
78 /// Called after attaching a process.
79 ///
80 /// Allow DynamicLoader plug-ins to execute some code after attaching to a
81 /// process.
82 virtual void DidAttach() = 0;
83
84 /// Called after launching a process.
85 ///
86 /// Allow DynamicLoader plug-ins to execute some code after the process has
87 /// stopped for the first time on launch.
88 virtual void DidLaunch() = 0;
89
90 /// Helper function that can be used to detect when a process has called
91 /// exec and is now a new and different process. This can be called when
92 /// necessary to try and detect the exec. The process might be able to
93 /// answer this question, but sometimes it might not be able and the dynamic
94 /// loader often knows what the program entry point is. So the process and
95 /// the dynamic loader can work together to detect this.
96 virtual bool ProcessDidExec() { return false; }
97 /// Get whether the process should stop when images change.
98 ///
99 /// When images (executables and shared libraries) get loaded or unloaded,
100 /// often debug sessions will want to try and resolve or unresolve
101 /// breakpoints that are set in these images. Any breakpoints set by
102 /// DynamicLoader plug-in instances should return this value to ensure
103 /// consistent debug session behaviour.
104 ///
105 /// \return
106 /// Returns \b true if the process should stop when images
107 /// change, \b false if the process should resume.
108 bool GetStopWhenImagesChange() const;
109
110 /// Set whether the process should stop when images change.
111 ///
112 /// When images (executables and shared libraries) get loaded or unloaded,
113 /// often debug sessions will want to try and resolve or unresolve
114 /// breakpoints that are set in these images. The default is set so that the
115 /// process stops when images change, but this can be overridden using this
116 /// function callback.
117 ///
118 /// \param[in] stop
119 /// Boolean value that indicates whether the process should stop
120 /// when images change.
121 void SetStopWhenImagesChange(bool stop);
122
123 /// Provides a plan to step through the dynamic loader trampoline for the
124 /// current state of \a thread.
125 ///
126 ///
127 /// \param[in] stop_others
128 /// Whether the plan should be set to stop other threads.
129 ///
130 /// \return
131 /// A pointer to the plan (caller owned) or NULL if we are not at such
132 /// a trampoline.
134 bool stop_others) = 0;
135
136 /// Some dynamic loaders provide features where there are a group of symbols
137 /// "equivalent to" a given symbol one of which will be chosen when the
138 /// symbol is bound. If you want to set a breakpoint on one of these
139 /// symbols, you really need to set it on all the equivalent symbols.
140 ///
141 ///
142 /// \param[in] original_symbol
143 /// The symbol for which we are finding equivalences.
144 ///
145 /// \param[in] module_list
146 /// The set of modules in which to search.
147 ///
148 /// \param[out] equivalent_symbols
149 /// The equivalent symbol list - any equivalent symbols found are appended
150 /// to this list.
151 ///
152 virtual void FindEquivalentSymbols(const Symbol *original_symbol,
153 ModuleList &module_list,
154 SymbolContextList &equivalent_symbols) {}
155
156 /// Ask if it is ok to try and load or unload an shared library (image).
157 ///
158 /// The dynamic loader often knows when it would be ok to try and load or
159 /// unload a shared library. This function call allows the dynamic loader
160 /// plug-ins to check any current dyld state to make sure it is an ok time
161 /// to load a shared library.
162 ///
163 /// \return
164 /// \b true if it is currently ok to try and load a shared
165 /// library into the process, \b false otherwise.
166 virtual Status CanLoadImage() = 0;
167
168 /// Ask if the eh_frame information for the given SymbolContext should be
169 /// relied on even when it's the first frame in a stack unwind.
170 ///
171 /// The CFI instructions from the eh_frame section are normally only valid
172 /// at call sites -- places where a program could throw an exception and
173 /// need to unwind out. But some Modules may be known to the system as
174 /// having reliable eh_frame information at all call sites. This would be
175 /// the case if the Module's contents are largely hand-written assembly with
176 /// hand-written eh_frame information. Normally when unwinding from a
177 /// function at the beginning of a stack unwind lldb will examine the
178 /// assembly instructions to understand how the stack frame is set up and
179 /// where saved registers are stored. But with hand-written assembly this is
180 /// not reliable enough -- we need to consult those function's hand-written
181 /// eh_frame information.
182 ///
183 /// \return
184 /// \b True if the symbol context should use eh_frame instructions
185 /// unconditionally when unwinding from this frame. Else \b false,
186 /// the normal lldb unwind behavior of only using eh_frame when the
187 /// function appears in the middle of the stack.
189 return false;
190 }
191
192 /// Retrieves the per-module TLS block for a given thread.
193 ///
194 /// \param[in] module
195 /// The module to query TLS data for.
196 ///
197 /// \param[in] thread
198 /// The specific thread to query TLS data for.
199 ///
200 /// \return
201 /// If the given thread has TLS data allocated for the
202 /// module, the address of the TLS block. Otherwise
203 /// LLDB_INVALID_ADDRESS is returned.
205 const lldb::ThreadSP thread,
206 lldb::addr_t tls_file_addr) {
208 }
209
210 /// Locates or creates a module given by \p file and updates/loads the
211 /// resulting module at the virtual base address \p base_addr.
212 /// Note that this calls Target::GetOrCreateModule with notify being false,
213 /// so it is necessary to call Target::ModulesDidLoad afterwards.
215 lldb::addr_t link_map_addr,
216 lldb::addr_t base_addr,
217 bool base_addr_is_offset);
218
219 /// A binary to find and load into a Target.
220 ///
221 /// The leading fields are inputs, filled in by the caller. The trailing
222 /// fields are outputs: searching for the binary records its results in them,
223 /// and loading the binary into the Target consumes them.
224 struct BinarySpec {
225 /// Name of the binary, if available. If no matching binary can be found on
226 /// the debug host, a module may be created out of live memory and given
227 /// this name. If empty, a name is constructed from the address the binary
228 /// is loaded at.
229 std::string name;
230
231 /// UUID of the binary to be loaded. May be empty, in which case, if a load
232 /// address is supplied, the binary is read out of memory to get a UUID to
233 /// look for. There is a performance cost to doing this, it is not
234 /// preferable.
236
237 /// Address where the binary should be loaded, or read out of memory. Or a
238 /// slide value, to be applied to the file addresses of the binary.
240
241 /// A flag indicating that \a value is an address, or an offset to be
242 /// applied to the file addresses.
243 bool value_is_offset = false;
244
245 /// Allow the search to do a possibly expensive external search for the
246 /// ObjectFile and/or SymbolFile.
248
249 /// Whether ModulesDidLoad should be called once the binary has been added
250 /// to the Target. A caller loading several binaries may prefer to batch
251 /// those up.
252 bool notify = false;
253
254 /// Whether the address of the binary should be set in the Target if it is
255 /// added. A caller that wants to set the section addresses individually
256 /// leaves this false, and is then responsible for setting the load address
257 /// for the binary or its segments in the Target.
259
260 /// If no better binary image can be found, allow reading the binary out of
261 /// memory, if possible, and create the Module based on that. May be slow
262 /// to read a binary out of memory, and for unusual environments, there may
263 /// be no symbols mapped in memory at all.
265
266 /// The module found for the binary, or empty if it was not found. It is
267 /// not registered with the Target until LoadBinaryInTarget.
269
270 /// The binary as it was read out of the process' memory, if it had to be,
271 /// so that it is not read a second time.
273
274 /// What an external symbol server had to say about this binary. The search
275 /// records it rather than reporting it, so that it reaches the user in the
276 /// caller's order.
278 };
279
280 /// Find a binary and load it into a Target.
281 ///
282 /// Given a UUID, search for a binary and load it at the address provided, or
283 /// with the slide applied, or at the file address unslid.
284 ///
285 /// Given an address, try to read the binary out of memory, get the UUID, find
286 /// the file if possible and load it unslid, or add the memory module.
287 ///
288 /// May force an expensive search on the host system to find the binary by
289 /// UUID. To load more than one binary, use LocateBinaries and
290 /// LoadBinaryInTarget instead: the search is the expensive part, and those
291 /// let all of the searching happen before any of the binaries are added to
292 /// the Target.
293 ///
294 /// \param[in] process
295 /// The process to add this binary to.
296 ///
297 /// \param[in,out] bin_spec
298 /// The binary to find and load, with its input fields filled in by the
299 /// caller.
300 ///
301 /// \return
302 /// The module that was added to the Target, or an error saying why the
303 /// binary could not be found and loaded.
304 static llvm::Expected<lldb::ModuleSP>
305 LocateAndLoadBinary(Process *process, BinarySpec &bin_spec);
306
307 /// Search for a batch of binaries, without mutating the Target.
308 ///
309 /// The entries are searched for independently, and stay in the order they
310 /// were given in. A binary that cannot be found leaves its
311 /// BinarySpec::module_sp empty and has no effect on the others. Its
312 /// BinarySpec::memory_module_sp is set only when the binary's header had to
313 /// be read out of memory to get the UUID. Nothing is registered with the
314 /// Target, see LoadBinaryInTarget.
315 ///
316 /// \param[in] process
317 /// The process the binaries belong to. Used to read a binary's header
318 /// out of memory when its UUID isn't known, and otherwise only read from.
319 ///
320 /// \param[in,out] bin_specs
321 /// The binaries to search for, with their input fields filled in by the
322 /// caller.
323 static void LocateBinaries(Process *process,
324 llvm::MutableArrayRef<BinarySpec> bin_specs);
325
326 /// Add a binary that LocateBinaries searched for to the Target, and set its
327 /// load address.
328 ///
329 /// This mutates the Target and may read the process' memory, so it has to be
330 /// called for one binary at a time. Call it over the batch in the order the
331 /// batch was built in: that order decides the Target's module order, which
332 /// binary gets to set the Target's architecture, and the order in which
333 /// messages reach the user.
334 ///
335 /// Whether a failure is worth telling the user about is left to the caller,
336 /// which knows whether it went looking for a binary that has to be there. A
337 /// symbol server's word on a binary that was found anyway is reported here.
338 ///
339 /// \param[in] process
340 /// The process to add this binary to.
341 ///
342 /// \param[in,out] bin_spec
343 /// A binary that LocateBinaries has searched for.
344 ///
345 /// \return
346 /// The module that was added to the Target, or an error saying why the
347 /// binary could not be found and loaded.
348 static llvm::Expected<lldb::ModuleSP>
349 LoadBinaryInTarget(Process *process, BinarySpec &bin_spec);
350
351 /// Get information about the shared cache for a process, if possible.
352 ///
353 /// On some systems (e.g. Darwin based systems), a set of libraries that are
354 /// common to most processes may be put in a single region of memory and
355 /// mapped into every process, this is called the shared cache, as a
356 /// performance optimization.
357 ///
358 /// Many targets will not have the concept of a shared cache.
359 ///
360 /// Depending on how the DynamicLoader gathers information about the shared
361 /// cache, it may be able to only return basic information - like the UUID
362 /// of the cache - or it may be able to return additional information about
363 /// the cache.
364 ///
365 /// \param[out] base_address
366 /// The base address (load address) of the shared cache.
367 /// LLDB_INVALID_ADDRESS if it cannot be determined.
368 ///
369 /// \param[out] uuid
370 /// The UUID of the shared cache, if it can be determined.
371 /// If the UUID cannot be fetched, IsValid() will be false.
372 ///
373 /// \param[out] using_shared_cache
374 /// If this process is using a shared cache.
375 /// If unknown, eLazyBoolCalculate is returned.
376 ///
377 /// \param[out] private_shared_cache
378 /// A LazyBool indicating whether this process is using a
379 /// private shared cache.
380 /// If this information cannot be fetched, eLazyBoolCalculate.
381 ///
382 /// \param[out] shared_cache_path
383 /// A FileSpec representing the shared cache path being run
384 /// in the inferior process.
385 ///
386 /// \return
387 /// Returns false if this DynamicLoader cannot gather information
388 /// about the shared cache / has no concept of a shared cache.
390 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
391 LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path,
392 std::optional<uint64_t> &size) {
393 base_address = LLDB_INVALID_ADDRESS;
394 uuid.Clear();
395 using_shared_cache = eLazyBoolCalculate;
396 private_shared_cache = eLazyBoolCalculate;
397 shared_cache_path.Clear();
398 size.reset();
399 return false;
400 }
401
402 /// Return whether the dynamic loader is fully initialized and it's safe to
403 /// call its APIs.
404 ///
405 /// On some systems (e.g. Darwin based systems), lldb will get notified by
406 /// the dynamic loader before it itself finished initializing and it's not
407 /// safe to call certain APIs or SPIs.
408 virtual bool IsFullyInitialized() { return true; }
409
410 /// Return the `start` \b address in the dynamic loader module.
411 /// This is the address the process will begin executing with
412 /// `process launch --stop-at-entry`.
413 virtual std::optional<lldb_private::Address> GetStartAddress() {
414 return std::nullopt;
415 }
416
417 /// Returns a list of memory ranges that should be saved in the core file,
418 /// specific for this dynamic loader.
419 ///
420 /// For example, an implementation of this function can save the thread
421 /// local data of a given thread.
423 lldb_private::Process &process,
424 std::vector<lldb_private::MemoryRegionInfo> &ranges,
425 llvm::function_ref<bool(const lldb_private::Thread &)>
426 save_thread_predicate) {};
427
428protected:
429 // Utility methods for derived classes
430
431 /// Find a module in the target that matches the given module spec.
433
434 /// Checks to see if the target module has changed, updates the target
435 /// accordingly and returns the target executable module.
437
438 /// Updates the load address of every allocatable section in \p module.
439 ///
440 /// \param module The module to traverse.
441 ///
442 /// \param link_map_addr The virtual address of the link map for the @p
443 /// module.
444 ///
445 /// \param base_addr The virtual base address \p module is loaded at.
446 virtual void UpdateLoadedSections(lldb::ModuleSP module,
447 lldb::addr_t link_map_addr,
448 lldb::addr_t base_addr,
449 bool base_addr_is_offset);
450
451 // Utility method so base classes can share implementation of
452 // UpdateLoadedSections
454 bool base_addr_is_offset);
455
456 /// Removes the loaded sections from the target in \p module.
457 ///
458 /// \param module The module to traverse.
459 virtual void UnloadSections(const lldb::ModuleSP module);
460
461 // Utility method so base classes can share implementation of UnloadSections
462 void UnloadSectionsCommon(const lldb::ModuleSP module);
463
465 GetSectionListFromModule(const lldb::ModuleSP module) const;
466
467 // Read an unsigned int of the given size from memory at the given addr.
468 // Return -1 if the read fails, otherwise return the result as an int64_t.
469 int64_t ReadUnsignedIntWithSizeInBytes(lldb::addr_t addr, int size_in_bytes);
470
471 // Read a pointer from memory at the given addr. Return LLDB_INVALID_ADDRESS
472 // if the read fails.
474
475 // Calls into the Process protected method LoadOperatingSystemPlugin:
476 void LoadOperatingSystemPlugin(bool flush);
477
478
479 // Member variables.
480 Process
481 *m_process; ///< The process that this dynamic loader plug-in is tracking.
482};
483
484} // namespace lldb_private
485
486#endif // LLDB_TARGET_DYNAMICLOADER_H
void LoadOperatingSystemPlugin(bool flush)
void SetStopWhenImagesChange(bool stop)
Set whether the process should stop when images change.
virtual bool AlwaysRelyOnEHUnwindInfo(SymbolContext &sym_ctx)
Ask if the eh_frame information for the given SymbolContext should be relied on even when it's the fi...
lldb::ModuleSP FindModuleViaTarget(const ModuleSpec &module_spec)
Find a module in the target that matches the given module spec.
virtual void DidAttach()=0
Called after attaching a process.
int64_t ReadUnsignedIntWithSizeInBytes(lldb::addr_t addr, int size_in_bytes)
static llvm::Expected< lldb::ModuleSP > LocateAndLoadBinary(Process *process, BinarySpec &bin_spec)
Find a binary and load it into a Target.
virtual Status CanLoadImage()=0
Ask if it is ok to try and load or unload an shared library (image).
lldb::addr_t ReadPointer(lldb::addr_t addr)
Process * m_process
The process that this dynamic loader plug-in is tracking.
virtual lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr)
Retrieves the per-module TLS block for a given thread.
virtual std::optional< lldb_private::Address > GetStartAddress()
Return the start address in the dynamic loader module.
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 CalculateDynamicSaveCoreRanges(lldb_private::Process &process, std::vector< lldb_private::MemoryRegionInfo > &ranges, llvm::function_ref< bool(const lldb_private::Thread &)> save_thread_predicate)
Returns a list of memory ranges that should be saved in the core file, specific for this dynamic load...
virtual bool ProcessDidExec()
Helper function that can be used to detect when a process has called exec and is now a new and differ...
bool GetStopWhenImagesChange() const
Get whether the process should stop when images change.
static void LocateBinaries(Process *process, llvm::MutableArrayRef< BinarySpec > bin_specs)
Search for a batch of binaries, without mutating the Target.
virtual lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, bool stop_others)=0
Provides a plan to step through the dynamic loader trampoline for the current state of thread.
virtual lldb::ModuleSP LoadModuleAtAddress(const lldb_private::FileSpec &file, lldb::addr_t link_map_addr, lldb::addr_t base_addr, bool base_addr_is_offset)
Locates or creates a module given by file and updates/loads the resulting module at the virtual base ...
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.
const lldb_private::SectionList * GetSectionListFromModule(const lldb::ModuleSP module) const
virtual void DidLaunch()=0
Called after launching a process.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
virtual bool GetSharedCacheInformation(lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache, LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path, std::optional< uint64_t > &size)
Get information about the shared cache for a process, if possible.
virtual void FindEquivalentSymbols(const Symbol *original_symbol, ModuleList &module_list, SymbolContextList &equivalent_symbols)
Some dynamic loaders provide features where there are a group of symbols "equivalent to" a given symb...
static llvm::Expected< lldb::ModuleSP > LoadBinaryInTarget(Process *process, BinarySpec &bin_spec)
Add a binary that LocateBinaries searched for to the Target, and set its load address.
void UnloadSectionsCommon(const lldb::ModuleSP module)
virtual bool IsFullyInitialized()
Return whether the dynamic loader is fully initialized and it's safe to call its APIs.
virtual void UnloadSections(const lldb::ModuleSP module)
Removes the loaded sections from the target in module.
A file utility class.
Definition FileSpec.h:56
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
A collection class for Module objects.
Definition ModuleList.h:125
A plug-in interface definition class for debugging a process.
Definition Process.h:360
An error handling class.
Definition Status.h:118
Defines a list of symbol context objects.
Defines a symbol context baton that can be handed other debug core functions.
Represents UUID's of various sizes.
Definition UUID.h:27
void Clear()
Definition UUID.h:62
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
A binary to find and load into a Target.
lldb::addr_t value
Address where the binary should be loaded, or read out of memory.
bool allow_memory_image_last_resort
If no better binary image can be found, allow reading the binary out of memory, if possible,...
UUID uuid
UUID of the binary to be loaded.
lldb::ModuleSP memory_module_sp
The binary as it was read out of the process' memory, if it had to be, so that it is not read a secon...
std::string name
Name of the binary, if available.
lldb::ModuleSP module_sp
The module found for the binary, or empty if it was not found.
Status error
What an external symbol server had to say about this binary.
bool force_symbol_search
Allow the search to do a possibly expensive external search for the ObjectFile and/or SymbolFile.
bool set_address_in_target
Whether the address of the binary should be set in the Target if it is added.
bool notify
Whether ModulesDidLoad should be called once the binary has been added to the Target.
bool value_is_offset
A flag indicating that value is an address, or an offset to be applied to the file addresses.