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
98 /// Allow the dynamic loader to handle a request to update loaded modules.
99 ///
100 /// This is intended for dynamic loaders that rely on notifications from a
101 /// driver or debug service instead of a rendezvous breakpoint.
102 ///
103 /// \returns
104 /// True if shared-library loading was handled, false otherwise.
105 virtual bool HandleStopReasonDynamicLoader() { return false; }
106
107 /// Get whether the process should stop when images change.
108 ///
109 /// When images (executables and shared libraries) get loaded or unloaded,
110 /// often debug sessions will want to try and resolve or unresolve
111 /// breakpoints that are set in these images. Any breakpoints set by
112 /// DynamicLoader plug-in instances should return this value to ensure
113 /// consistent debug session behaviour.
114 ///
115 /// \return
116 /// Returns \b true if the process should stop when images
117 /// change, \b false if the process should resume.
118 bool GetStopWhenImagesChange() const;
119
120 /// Set whether the process should stop when images change.
121 ///
122 /// When images (executables and shared libraries) get loaded or unloaded,
123 /// often debug sessions will want to try and resolve or unresolve
124 /// breakpoints that are set in these images. The default is set so that the
125 /// process stops when images change, but this can be overridden using this
126 /// function callback.
127 ///
128 /// \param[in] stop
129 /// Boolean value that indicates whether the process should stop
130 /// when images change.
131 void SetStopWhenImagesChange(bool stop);
132
133 /// Provides a plan to step through the dynamic loader trampoline for the
134 /// current state of \a thread.
135 ///
136 ///
137 /// \param[in] stop_others
138 /// Whether the plan should be set to stop other threads.
139 ///
140 /// \return
141 /// A pointer to the plan (caller owned) or NULL if we are not at such
142 /// a trampoline.
144 bool stop_others) = 0;
145
146 /// Some dynamic loaders provide features where there are a group of symbols
147 /// "equivalent to" a given symbol one of which will be chosen when the
148 /// symbol is bound. If you want to set a breakpoint on one of these
149 /// symbols, you really need to set it on all the equivalent symbols.
150 ///
151 ///
152 /// \param[in] original_symbol
153 /// The symbol for which we are finding equivalences.
154 ///
155 /// \param[in] module_list
156 /// The set of modules in which to search.
157 ///
158 /// \param[out] equivalent_symbols
159 /// The equivalent symbol list - any equivalent symbols found are appended
160 /// to this list.
161 ///
162 virtual void FindEquivalentSymbols(const Symbol *original_symbol,
163 ModuleList &module_list,
164 SymbolContextList &equivalent_symbols) {}
165
166 /// Ask if it is ok to try and load or unload an shared library (image).
167 ///
168 /// The dynamic loader often knows when it would be ok to try and load or
169 /// unload a shared library. This function call allows the dynamic loader
170 /// plug-ins to check any current dyld state to make sure it is an ok time
171 /// to load a shared library.
172 ///
173 /// \return
174 /// \b true if it is currently ok to try and load a shared
175 /// library into the process, \b false otherwise.
176 virtual Status CanLoadImage() = 0;
177
178 /// Ask if the eh_frame information for the given SymbolContext should be
179 /// relied on even when it's the first frame in a stack unwind.
180 ///
181 /// The CFI instructions from the eh_frame section are normally only valid
182 /// at call sites -- places where a program could throw an exception and
183 /// need to unwind out. But some Modules may be known to the system as
184 /// having reliable eh_frame information at all call sites. This would be
185 /// the case if the Module's contents are largely hand-written assembly with
186 /// hand-written eh_frame information. Normally when unwinding from a
187 /// function at the beginning of a stack unwind lldb will examine the
188 /// assembly instructions to understand how the stack frame is set up and
189 /// where saved registers are stored. But with hand-written assembly this is
190 /// not reliable enough -- we need to consult those function's hand-written
191 /// eh_frame information.
192 ///
193 /// \return
194 /// \b True if the symbol context should use eh_frame instructions
195 /// unconditionally when unwinding from this frame. Else \b false,
196 /// the normal lldb unwind behavior of only using eh_frame when the
197 /// function appears in the middle of the stack.
199 return false;
200 }
201
202 /// Retrieves the per-module TLS block for a given thread.
203 ///
204 /// \param[in] module
205 /// The module to query TLS data for.
206 ///
207 /// \param[in] thread
208 /// The specific thread to query TLS data for.
209 ///
210 /// \return
211 /// If the given thread has TLS data allocated for the
212 /// module, the address of the TLS block. Otherwise
213 /// LLDB_INVALID_ADDRESS is returned.
215 const lldb::ThreadSP thread,
216 lldb::addr_t tls_file_addr) {
218 }
219
220 /// Locates or creates a module given by \p file and updates/loads the
221 /// resulting module at the virtual base address \p base_addr.
222 /// Note that this calls Target::GetOrCreateModule with notify being false,
223 /// so it is necessary to call Target::ModulesDidLoad afterwards.
225 lldb::addr_t link_map_addr,
226 lldb::addr_t base_addr,
227 bool base_addr_is_offset);
228
229 /// A binary to find and load into a Target.
230 ///
231 /// The leading fields are inputs, filled in by the caller. The trailing
232 /// fields are outputs: searching for the binary records its results in them,
233 /// and loading the binary into the Target consumes them.
234 struct BinarySpec {
235 /// Name of the binary, if available. If no matching binary can be found on
236 /// the debug host, a module may be created out of live memory and given
237 /// this name. If empty, a name is constructed from the address the binary
238 /// is loaded at.
239 std::string name;
240
241 /// UUID of the binary to be loaded. May be empty, in which case, if a load
242 /// address is supplied, the binary is read out of memory to get a UUID to
243 /// look for. There is a performance cost to doing this, it is not
244 /// preferable.
246
247 /// Address where the binary should be loaded, or read out of memory. Or a
248 /// slide value, to be applied to the file addresses of the binary.
250
251 /// A flag indicating that \a value is an address, or an offset to be
252 /// applied to the file addresses.
253 bool value_is_offset = false;
254
255 /// Allow the search to do a possibly expensive external search for the
256 /// ObjectFile and/or SymbolFile.
258
259 /// Whether ModulesDidLoad should be called once the binary has been added
260 /// to the Target. A caller loading several binaries may prefer to batch
261 /// those up.
262 bool notify = false;
263
264 /// Whether the address of the binary should be set in the Target if it is
265 /// added. A caller that wants to set the section addresses individually
266 /// leaves this false, and is then responsible for setting the load address
267 /// for the binary or its segments in the Target.
269
270 /// If no better binary image can be found, allow reading the binary out of
271 /// memory, if possible, and create the Module based on that. May be slow
272 /// to read a binary out of memory, and for unusual environments, there may
273 /// be no symbols mapped in memory at all.
275
276 /// Whether this is the process' main executable. It becomes the Target's
277 /// executable if the Target has none.
278 bool is_main_executable = false;
279
280 /// The module found for the binary, or empty if it was not found. It is
281 /// not registered with the Target until LoadBinaryInTarget.
283
284 /// The binary as it was read out of the process' memory, if it had to be,
285 /// so that it is not read a second time.
287
288 /// What an external symbol server had to say about this binary. The search
289 /// records it rather than reporting it, so that it reaches the user in the
290 /// caller's order.
292 };
293
294 /// Find a binary and load it into a Target.
295 ///
296 /// Given a UUID, search for a binary and load it at the address provided, or
297 /// with the slide applied, or at the file address unslid.
298 ///
299 /// Given an address, try to read the binary out of memory, get the UUID, find
300 /// the file if possible and load it unslid, or add the memory module.
301 ///
302 /// May force an expensive search on the host system to find the binary by
303 /// UUID. To load more than one binary, use LocateBinaries and
304 /// LoadBinaryInTarget instead: the search is the expensive part, and those
305 /// let all of the searching happen before any of the binaries are added to
306 /// the Target.
307 ///
308 /// \param[in] process
309 /// The process to add this binary to.
310 ///
311 /// \param[in,out] bin_spec
312 /// The binary to find and load, with its input fields filled in by the
313 /// caller.
314 ///
315 /// \return
316 /// The module that was added to the Target, or an error saying why the
317 /// binary could not be found and loaded.
318 static llvm::Expected<lldb::ModuleSP>
319 LocateAndLoadBinary(Process *process, BinarySpec &bin_spec);
320
321 /// Search for a batch of binaries, without mutating the Target.
322 ///
323 /// The entries are searched for independently, and stay in the order they
324 /// were given in. A binary that cannot be found leaves its
325 /// BinarySpec::module_sp empty and has no effect on the others. Its
326 /// BinarySpec::memory_module_sp is set only when the binary's header had to
327 /// be read out of memory to get the UUID. Nothing is registered with the
328 /// Target, see LoadBinaryInTarget.
329 ///
330 /// \param[in] process
331 /// The process the binaries belong to. Used to read a binary's header
332 /// out of memory when its UUID isn't known, and otherwise only read from.
333 ///
334 /// \param[in,out] bin_specs
335 /// The binaries to search for, with their input fields filled in by the
336 /// caller.
337 static void LocateBinaries(Process *process,
338 llvm::MutableArrayRef<BinarySpec> bin_specs);
339
340 /// Add a binary that LocateBinaries searched for to the Target, and set its
341 /// load address.
342 ///
343 /// This mutates the Target and may read the process' memory, so it has to be
344 /// called for one binary at a time. Call it over the batch in the order the
345 /// batch was built in: that order decides the Target's module order, which
346 /// binary gets to set the Target's architecture, and the order in which
347 /// messages reach the user.
348 ///
349 /// Whether a failure is worth telling the user about is left to the caller,
350 /// which knows whether it went looking for a binary that has to be there. A
351 /// symbol server's word on a binary that was found anyway is reported here.
352 ///
353 /// \param[in] process
354 /// The process to add this binary to.
355 ///
356 /// \param[in,out] bin_spec
357 /// A binary that LocateBinaries has searched for.
358 ///
359 /// \return
360 /// The module that was added to the Target, or an error saying why the
361 /// binary could not be found and loaded.
362 static llvm::Expected<lldb::ModuleSP>
363 LoadBinaryInTarget(Process *process, BinarySpec &bin_spec);
364
365 /// Get information about the shared cache for a process, if possible.
366 ///
367 /// On some systems (e.g. Darwin based systems), a set of libraries that are
368 /// common to most processes may be put in a single region of memory and
369 /// mapped into every process, this is called the shared cache, as a
370 /// performance optimization.
371 ///
372 /// Many targets will not have the concept of a shared cache.
373 ///
374 /// Depending on how the DynamicLoader gathers information about the shared
375 /// cache, it may be able to only return basic information - like the UUID
376 /// of the cache - or it may be able to return additional information about
377 /// the cache.
378 ///
379 /// \param[out] base_address
380 /// The base address (load address) of the shared cache.
381 /// LLDB_INVALID_ADDRESS if it cannot be determined.
382 ///
383 /// \param[out] uuid
384 /// The UUID of the shared cache, if it can be determined.
385 /// If the UUID cannot be fetched, IsValid() will be false.
386 ///
387 /// \param[out] using_shared_cache
388 /// If this process is using a shared cache.
389 /// If unknown, eLazyBoolCalculate is returned.
390 ///
391 /// \param[out] private_shared_cache
392 /// A LazyBool indicating whether this process is using a
393 /// private shared cache.
394 /// If this information cannot be fetched, eLazyBoolCalculate.
395 ///
396 /// \param[out] shared_cache_path
397 /// A FileSpec representing the shared cache path being run
398 /// in the inferior process.
399 ///
400 /// \return
401 /// Returns false if this DynamicLoader cannot gather information
402 /// about the shared cache / has no concept of a shared cache.
404 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
405 LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path,
406 std::optional<uint64_t> &size) {
407 base_address = LLDB_INVALID_ADDRESS;
408 uuid.Clear();
409 using_shared_cache = eLazyBoolCalculate;
410 private_shared_cache = eLazyBoolCalculate;
411 shared_cache_path.Clear();
412 size.reset();
413 return false;
414 }
415
416 /// Return whether the dynamic loader is fully initialized and it's safe to
417 /// call its APIs.
418 ///
419 /// On some systems (e.g. Darwin based systems), lldb will get notified by
420 /// the dynamic loader before it itself finished initializing and it's not
421 /// safe to call certain APIs or SPIs.
422 virtual bool IsFullyInitialized() { return true; }
423
424 /// Return the `start` \b address in the dynamic loader module.
425 /// This is the address the process will begin executing with
426 /// `process launch --stop-at-entry`.
427 virtual std::optional<lldb_private::Address> GetStartAddress() {
428 return std::nullopt;
429 }
430
431 /// Returns a list of memory ranges that should be saved in the core file,
432 /// specific for this dynamic loader.
433 ///
434 /// For example, an implementation of this function can save the thread
435 /// local data of a given thread.
437 lldb_private::Process &process,
438 std::vector<lldb_private::MemoryRegionInfo> &ranges,
439 llvm::function_ref<bool(const lldb_private::Thread &)>
440 save_thread_predicate) {};
441
442protected:
443 // Utility methods for derived classes
444
445 /// Find a module in the target that matches the given module spec.
447
448 /// Checks to see if the target module has changed, updates the target
449 /// accordingly and returns the target executable module.
451
452 /// Updates the load address of every allocatable section in \p module.
453 ///
454 /// \param module The module to traverse.
455 ///
456 /// \param link_map_addr The virtual address of the link map for the @p
457 /// module.
458 ///
459 /// \param base_addr The virtual base address \p module is loaded at.
460 virtual void UpdateLoadedSections(lldb::ModuleSP module,
461 lldb::addr_t link_map_addr,
462 lldb::addr_t base_addr,
463 bool base_addr_is_offset);
464
465 // Utility method so base classes can share implementation of
466 // UpdateLoadedSections
468 bool base_addr_is_offset);
469
470 /// Removes the loaded sections from the target in \p module.
471 ///
472 /// \param module The module to traverse.
473 virtual void UnloadSections(const lldb::ModuleSP module);
474
475 // Utility method so base classes can share implementation of UnloadSections
476 void UnloadSectionsCommon(const lldb::ModuleSP module);
477
479 GetSectionListFromModule(const lldb::ModuleSP module) const;
480
481 // Read an unsigned int of the given size from memory at the given addr.
482 // Return -1 if the read fails, otherwise return the result as an int64_t.
483 int64_t ReadUnsignedIntWithSizeInBytes(lldb::addr_t addr, int size_in_bytes);
484
485 // Read a pointer from memory at the given addr. Return LLDB_INVALID_ADDRESS
486 // if the read fails.
488
489 // Calls into the Process protected method LoadOperatingSystemPlugin:
490 void LoadOperatingSystemPlugin(bool flush);
491
492
493 // Member variables.
494 Process
495 *m_process; ///< The process that this dynamic loader plug-in is tracking.
496};
497
498} // namespace lldb_private
499
500#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...
virtual bool HandleStopReasonDynamicLoader()
Allow the dynamic loader to handle a request to update loaded modules.
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:127
A plug-in interface definition class for debugging a process.
Definition Process.h:369
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.
bool is_main_executable
Whether this is the process' main executable.
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.