Warning: This file is not a C or C++ file. It does not have highlighting.

1//===-- Target.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_TARGET_H
10#define LLDB_TARGET_TARGET_H
11
12#include <list>
13#include <map>
14#include <memory>
15#include <string>
16#include <vector>
17
18#include "lldb/Breakpoint/BreakpointList.h"
19#include "lldb/Breakpoint/BreakpointName.h"
20#include "lldb/Breakpoint/WatchpointList.h"
21#include "lldb/Core/Architecture.h"
22#include "lldb/Core/Disassembler.h"
23#include "lldb/Core/ModuleList.h"
24#include "lldb/Core/StructuredDataImpl.h"
25#include "lldb/Core/UserSettingsController.h"
26#include "lldb/Expression/Expression.h"
27#include "lldb/Host/ProcessLaunchInfo.h"
28#include "lldb/Symbol/TypeSystem.h"
29#include "lldb/Target/ExecutionContextScope.h"
30#include "lldb/Target/PathMappingList.h"
31#include "lldb/Target/SectionLoadHistory.h"
32#include "lldb/Target/Statistics.h"
33#include "lldb/Target/ThreadSpec.h"
34#include "lldb/Utility/ArchSpec.h"
35#include "lldb/Utility/Broadcaster.h"
36#include "lldb/Utility/LLDBAssert.h"
37#include "lldb/Utility/Timeout.h"
38#include "lldb/lldb-public.h"
39
40namespace lldb_private {
41
42OptionEnumValues GetDynamicValueTypes();
43
44enum InlineStrategy {
45 eInlineBreakpointsNever = 0,
46 eInlineBreakpointsHeaders,
47 eInlineBreakpointsAlways
48};
49
50enum LoadScriptFromSymFile {
51 eLoadScriptFromSymFileTrue,
52 eLoadScriptFromSymFileFalse,
53 eLoadScriptFromSymFileWarn
54};
55
56enum LoadCWDlldbinitFile {
57 eLoadCWDlldbinitTrue,
58 eLoadCWDlldbinitFalse,
59 eLoadCWDlldbinitWarn
60};
61
62enum ImportStdModule {
63 eImportStdModuleFalse,
64 eImportStdModuleFallback,
65 eImportStdModuleTrue,
66};
67
68enum DynamicClassInfoHelper {
69 eDynamicClassInfoHelperAuto,
70 eDynamicClassInfoHelperRealizedClassesStruct,
71 eDynamicClassInfoHelperCopyRealizedClassList,
72 eDynamicClassInfoHelperGetRealizedClassList,
73};
74
75class TargetExperimentalProperties : public Properties {
76public:
77 TargetExperimentalProperties();
78};
79
80class TargetProperties : public Properties {
81public:
82 TargetProperties(Target *target);
83
84 ~TargetProperties() override;
85
86 ArchSpec GetDefaultArchitecture() const;
87
88 void SetDefaultArchitecture(const ArchSpec &arch);
89
90 bool GetMoveToNearestCode() const;
91
92 lldb::DynamicValueType GetPreferDynamicValue() const;
93
94 bool SetPreferDynamicValue(lldb::DynamicValueType d);
95
96 bool GetPreloadSymbols() const;
97
98 void SetPreloadSymbols(bool b);
99
100 bool GetDisableASLR() const;
101
102 void SetDisableASLR(bool b);
103
104 bool GetInheritTCC() const;
105
106 void SetInheritTCC(bool b);
107
108 bool GetDetachOnError() const;
109
110 void SetDetachOnError(bool b);
111
112 bool GetDisableSTDIO() const;
113
114 void SetDisableSTDIO(bool b);
115
116 const char *GetDisassemblyFlavor() const;
117
118 InlineStrategy GetInlineStrategy() const;
119
120 llvm::StringRef GetArg0() const;
121
122 void SetArg0(llvm::StringRef arg);
123
124 bool GetRunArguments(Args &args) const;
125
126 void SetRunArguments(const Args &args);
127
128 // Get the whole environment including the platform inherited environment and
129 // the target specific environment, excluding the unset environment variables.
130 Environment GetEnvironment() const;
131 // Get the platform inherited environment, excluding the unset environment
132 // variables.
133 Environment GetInheritedEnvironment() const;
134 // Get the target specific environment only, without the platform inherited
135 // environment.
136 Environment GetTargetEnvironment() const;
137 // Set the target specific environment.
138 void SetEnvironment(Environment env);
139
140 bool GetSkipPrologue() const;
141
142 PathMappingList &GetSourcePathMap() const;
143
144 bool GetAutoSourceMapRelative() const;
145
146 FileSpecList GetExecutableSearchPaths();
147
148 void AppendExecutableSearchPaths(const FileSpec &);
149
150 FileSpecList GetDebugFileSearchPaths();
151
152 FileSpecList GetClangModuleSearchPaths();
153
154 bool GetEnableAutoImportClangModules() const;
155
156 ImportStdModule GetImportStdModule() const;
157
158 DynamicClassInfoHelper GetDynamicClassInfoHelper() const;
159
160 bool GetEnableAutoApplyFixIts() const;
161
162 uint64_t GetNumberOfRetriesWithFixits() const;
163
164 bool GetEnableNotifyAboutFixIts() const;
165
166 FileSpec GetSaveJITObjectsDir() const;
167
168 bool GetEnableSyntheticValue() const;
169
170 uint32_t GetMaxZeroPaddingInFloatFormat() const;
171
172 uint32_t GetMaximumNumberOfChildrenToDisplay() const;
173
174 /// Get the max depth value, augmented with a bool to indicate whether the
175 /// depth is the default.
176 ///
177 /// When the user has customized the max depth, the bool will be false.
178 ///
179 /// \returns the max depth, and true if the max depth is the system default,
180 /// otherwise false.
181 std::pair<uint32_t, bool> GetMaximumDepthOfChildrenToDisplay() const;
182
183 uint32_t GetMaximumSizeOfStringSummary() const;
184
185 uint32_t GetMaximumMemReadSize() const;
186
187 FileSpec GetStandardInputPath() const;
188 FileSpec GetStandardErrorPath() const;
189 FileSpec GetStandardOutputPath() const;
190
191 void SetStandardInputPath(llvm::StringRef path);
192 void SetStandardOutputPath(llvm::StringRef path);
193 void SetStandardErrorPath(llvm::StringRef path);
194
195 void SetStandardInputPath(const char *path) = delete;
196 void SetStandardOutputPath(const char *path) = delete;
197 void SetStandardErrorPath(const char *path) = delete;
198
199 bool GetBreakpointsConsultPlatformAvoidList();
200
201 lldb::LanguageType GetLanguage() const;
202
203 llvm::StringRef GetExpressionPrefixContents();
204
205 uint64_t GetExprErrorLimit() const;
206
207 bool GetUseHexImmediates() const;
208
209 bool GetUseFastStepping() const;
210
211 bool GetDisplayExpressionsInCrashlogs() const;
212
213 LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const;
214
215 LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const;
216
217 Disassembler::HexImmediateStyle GetHexImmediateStyle() const;
218
219 MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const;
220
221 bool GetUserSpecifiedTrapHandlerNames(Args &args) const;
222
223 void SetUserSpecifiedTrapHandlerNames(const Args &args);
224
225 bool GetDisplayRuntimeSupportValues() const;
226
227 void SetDisplayRuntimeSupportValues(bool b);
228
229 bool GetDisplayRecognizedArguments() const;
230
231 void SetDisplayRecognizedArguments(bool b);
232
233 const ProcessLaunchInfo &GetProcessLaunchInfo() const;
234
235 void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info);
236
237 bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const;
238
239 void SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b);
240
241 void SetRequireHardwareBreakpoints(bool b);
242
243 bool GetRequireHardwareBreakpoints() const;
244
245 bool GetAutoInstallMainExecutable() const;
246
247 void UpdateLaunchInfoFromProperties();
248
249 void SetDebugUtilityExpression(bool debug);
250
251 bool GetDebugUtilityExpression() const;
252
253private:
254 // Callbacks for m_launch_info.
255 void Arg0ValueChangedCallback();
256 void RunArgsValueChangedCallback();
257 void EnvVarsValueChangedCallback();
258 void InputPathValueChangedCallback();
259 void OutputPathValueChangedCallback();
260 void ErrorPathValueChangedCallback();
261 void DetachOnErrorValueChangedCallback();
262 void DisableASLRValueChangedCallback();
263 void InheritTCCValueChangedCallback();
264 void DisableSTDIOValueChangedCallback();
265
266 // Settings checker for target.jit-save-objects-dir:
267 void CheckJITObjectsDir();
268
269 Environment ComputeEnvironment() const;
270
271 // Member variables.
272 ProcessLaunchInfo m_launch_info;
273 std::unique_ptr<TargetExperimentalProperties> m_experimental_properties_up;
274 Target *m_target;
275};
276
277class EvaluateExpressionOptions {
278public:
279// MSVC has a bug here that reports C4268: 'const' static/global data
280// initialized with compiler generated default constructor fills the object
281// with zeros. Confirmed that MSVC is *not* zero-initializing, it's just a
282// bogus warning.
283#if defined(_MSC_VER)
284#pragma warning(push)
285#pragma warning(disable : 4268)
286#endif
287 static constexpr std::chrono::milliseconds default_timeout{500};
288#if defined(_MSC_VER)
289#pragma warning(pop)
290#endif
291
292 static constexpr ExecutionPolicy default_execution_policy =
293 eExecutionPolicyOnlyWhenNeeded;
294
295 EvaluateExpressionOptions() = default;
296
297 ExecutionPolicy GetExecutionPolicy() const { return m_execution_policy; }
298
299 void SetExecutionPolicy(ExecutionPolicy policy = eExecutionPolicyAlways) {
300 m_execution_policy = policy;
301 }
302
303 lldb::LanguageType GetLanguage() const { return m_language; }
304
305 void SetLanguage(lldb::LanguageType language) { m_language = language; }
306
307 bool DoesCoerceToId() const { return m_coerce_to_id; }
308
309 const char *GetPrefix() const {
310 return (m_prefix.empty() ? nullptr : m_prefix.c_str());
311 }
312
313 void SetPrefix(const char *prefix) {
314 if (prefix && prefix[0])
315 m_prefix = prefix;
316 else
317 m_prefix.clear();
318 }
319
320 void SetCoerceToId(bool coerce = true) { m_coerce_to_id = coerce; }
321
322 bool DoesUnwindOnError() const { return m_unwind_on_error; }
323
324 void SetUnwindOnError(bool unwind = false) { m_unwind_on_error = unwind; }
325
326 bool DoesIgnoreBreakpoints() const { return m_ignore_breakpoints; }
327
328 void SetIgnoreBreakpoints(bool ignore = false) {
329 m_ignore_breakpoints = ignore;
330 }
331
332 bool DoesKeepInMemory() const { return m_keep_in_memory; }
333
334 void SetKeepInMemory(bool keep = true) { m_keep_in_memory = keep; }
335
336 lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
337
338 void
339 SetUseDynamic(lldb::DynamicValueType dynamic = lldb::eDynamicCanRunTarget) {
340 m_use_dynamic = dynamic;
341 }
342
343 const Timeout<std::micro> &GetTimeout() const { return m_timeout; }
344
345 void SetTimeout(const Timeout<std::micro> &timeout) { m_timeout = timeout; }
346
347 const Timeout<std::micro> &GetOneThreadTimeout() const {
348 return m_one_thread_timeout;
349 }
350
351 void SetOneThreadTimeout(const Timeout<std::micro> &timeout) {
352 m_one_thread_timeout = timeout;
353 }
354
355 bool GetTryAllThreads() const { return m_try_others; }
356
357 void SetTryAllThreads(bool try_others = true) { m_try_others = try_others; }
358
359 bool GetStopOthers() const { return m_stop_others; }
360
361 void SetStopOthers(bool stop_others = true) { m_stop_others = stop_others; }
362
363 bool GetDebug() const { return m_debug; }
364
365 void SetDebug(bool b) {
366 m_debug = b;
367 if (m_debug)
368 m_generate_debug_info = true;
369 }
370
371 bool GetGenerateDebugInfo() const { return m_generate_debug_info; }
372
373 void SetGenerateDebugInfo(bool b) { m_generate_debug_info = b; }
374
375 bool GetColorizeErrors() const { return m_ansi_color_errors; }
376
377 void SetColorizeErrors(bool b) { m_ansi_color_errors = b; }
378
379 bool GetTrapExceptions() const { return m_trap_exceptions; }
380
381 void SetTrapExceptions(bool b) { m_trap_exceptions = b; }
382
383 bool GetREPLEnabled() const { return m_repl; }
384
385 void SetREPLEnabled(bool b) { m_repl = b; }
386
387 void SetCancelCallback(lldb::ExpressionCancelCallback callback, void *baton) {
388 m_cancel_callback_baton = baton;
389 m_cancel_callback = callback;
390 }
391
392 bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const {
393 return ((m_cancel_callback != nullptr)
394 ? m_cancel_callback(phase, m_cancel_callback_baton)
395 : false);
396 }
397
398 // Allows the expression contents to be remapped to point to the specified
399 // file and line using #line directives.
400 void SetPoundLine(const char *path, uint32_t line) const {
401 if (path && path[0]) {
402 m_pound_line_file = path;
403 m_pound_line_line = line;
404 } else {
405 m_pound_line_file.clear();
406 m_pound_line_line = 0;
407 }
408 }
409
410 const char *GetPoundLineFilePath() const {
411 return (m_pound_line_file.empty() ? nullptr : m_pound_line_file.c_str());
412 }
413
414 uint32_t GetPoundLineLine() const { return m_pound_line_line; }
415
416 void SetSuppressPersistentResult(bool b) { m_suppress_persistent_result = b; }
417
418 bool GetSuppressPersistentResult() const {
419 return m_suppress_persistent_result;
420 }
421
422 void SetAutoApplyFixIts(bool b) { m_auto_apply_fixits = b; }
423
424 bool GetAutoApplyFixIts() const { return m_auto_apply_fixits; }
425
426 void SetRetriesWithFixIts(uint64_t number_of_retries) {
427 m_retries_with_fixits = number_of_retries;
428 }
429
430 uint64_t GetRetriesWithFixIts() const { return m_retries_with_fixits; }
431
432 bool IsForUtilityExpr() const { return m_running_utility_expression; }
433
434 void SetIsForUtilityExpr(bool b) { m_running_utility_expression = b; }
435
436private:
437 ExecutionPolicy m_execution_policy = default_execution_policy;
438 lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
439 std::string m_prefix;
440 bool m_coerce_to_id = false;
441 bool m_unwind_on_error = true;
442 bool m_ignore_breakpoints = false;
443 bool m_keep_in_memory = false;
444 bool m_try_others = true;
445 bool m_stop_others = true;
446 bool m_debug = false;
447 bool m_trap_exceptions = true;
448 bool m_repl = false;
449 bool m_generate_debug_info = false;
450 bool m_ansi_color_errors = false;
451 bool m_suppress_persistent_result = false;
452 bool m_auto_apply_fixits = true;
453 uint64_t m_retries_with_fixits = 1;
454 /// True if the executed code should be treated as utility code that is only
455 /// used by LLDB internally.
456 bool m_running_utility_expression = false;
457
458 lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues;
459 Timeout<std::micro> m_timeout = default_timeout;
460 Timeout<std::micro> m_one_thread_timeout = std::nullopt;
461 lldb::ExpressionCancelCallback m_cancel_callback = nullptr;
462 void *m_cancel_callback_baton = nullptr;
463 // If m_pound_line_file is not empty and m_pound_line_line is non-zero, use
464 // #line %u "%s" before the expression content to remap where the source
465 // originates
466 mutable std::string m_pound_line_file;
467 mutable uint32_t m_pound_line_line = 0;
468};
469
470// Target
471class Target : public std::enable_shared_from_this<Target>,
472 public TargetProperties,
473 public Broadcaster,
474 public ExecutionContextScope,
475 public ModuleList::Notifier {
476public:
477 friend class TargetList;
478 friend class Debugger;
479
480 /// Broadcaster event bits definitions.
481 enum {
482 eBroadcastBitBreakpointChanged = (1 << 0),
483 eBroadcastBitModulesLoaded = (1 << 1),
484 eBroadcastBitModulesUnloaded = (1 << 2),
485 eBroadcastBitWatchpointChanged = (1 << 3),
486 eBroadcastBitSymbolsLoaded = (1 << 4),
487 eBroadcastBitSymbolsChanged = (1 << 5),
488 };
489
490 // These two functions fill out the Broadcaster interface:
491
492 static ConstString &GetStaticBroadcasterClass();
493
494 ConstString &GetBroadcasterClass() const override {
495 return GetStaticBroadcasterClass();
496 }
497
498 // This event data class is for use by the TargetList to broadcast new target
499 // notifications.
500 class TargetEventData : public EventData {
501 public:
502 TargetEventData(const lldb::TargetSP &target_sp);
503
504 TargetEventData(const lldb::TargetSP &target_sp,
505 const ModuleList &module_list);
506
507 ~TargetEventData() override;
508
509 static llvm::StringRef GetFlavorString();
510
511 llvm::StringRef GetFlavor() const override {
512 return TargetEventData::GetFlavorString();
513 }
514
515 void Dump(Stream *s) const override;
516
517 static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr);
518
519 static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
520
521 static ModuleList GetModuleListFromEvent(const Event *event_ptr);
522
523 const lldb::TargetSP &GetTarget() const { return m_target_sp; }
524
525 const ModuleList &GetModuleList() const { return m_module_list; }
526
527 private:
528 lldb::TargetSP m_target_sp;
529 ModuleList m_module_list;
530
531 TargetEventData(const TargetEventData &) = delete;
532 const TargetEventData &operator=(const TargetEventData &) = delete;
533 };
534
535 ~Target() override;
536
537 static void SettingsInitialize();
538
539 static void SettingsTerminate();
540
541 static FileSpecList GetDefaultExecutableSearchPaths();
542
543 static FileSpecList GetDefaultDebugFileSearchPaths();
544
545 static ArchSpec GetDefaultArchitecture();
546
547 static void SetDefaultArchitecture(const ArchSpec &arch);
548
549 bool IsDummyTarget() const { return m_is_dummy_target; }
550
551 /// Find a binary on the system and return its Module,
552 /// or return an existing Module that is already in the Target.
553 ///
554 /// Given a ModuleSpec, find a binary satisifying that specification,
555 /// or identify a matching Module already present in the Target,
556 /// and return a shared pointer to it.
557 ///
558 /// \param[in] module_spec
559 /// The criteria that must be matched for the binary being loaded.
560 /// e.g. UUID, architecture, file path.
561 ///
562 /// \param[in] notify
563 /// If notify is true, and the Module is new to this Target,
564 /// Target::ModulesDidLoad will be called.
565 /// If notify is false, it is assumed that the caller is adding
566 /// multiple Modules and will call ModulesDidLoad with the
567 /// full list at the end.
568 /// ModulesDidLoad must be called when a Module/Modules have
569 /// been added to the target, one way or the other.
570 ///
571 /// \param[out] error_ptr
572 /// Optional argument, pointing to a Status object to fill in
573 /// with any results / messages while attempting to find/load
574 /// this binary. Many callers will be internal functions that
575 /// will handle / summarize the failures in a custom way and
576 /// don't use these messages.
577 ///
578 /// \return
579 /// An empty ModuleSP will be returned if no matching file
580 /// was found. If error_ptr was non-nullptr, an error message
581 /// will likely be provided.
582 lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
583 Status *error_ptr = nullptr);
584
585 // Settings accessors
586
587 static TargetProperties &GetGlobalProperties();
588
589 std::recursive_mutex &GetAPIMutex();
590
591 void DeleteCurrentProcess();
592
593 void CleanupProcess();
594
595 /// Dump a description of this object to a Stream.
596 ///
597 /// Dump a description of the contents of this object to the
598 /// supplied stream \a s. The dumped content will be only what has
599 /// been loaded or parsed up to this point at which this function
600 /// is called, so this is a good way to see what has been parsed
601 /// in a target.
602 ///
603 /// \param[in] s
604 /// The stream to which to dump the object description.
605 void Dump(Stream *s, lldb::DescriptionLevel description_level);
606
607 // If listener_sp is null, the listener of the owning Debugger object will be
608 // used.
609 const lldb::ProcessSP &CreateProcess(lldb::ListenerSP listener_sp,
610 llvm::StringRef plugin_name,
611 const FileSpec *crash_file,
612 bool can_connect);
613
614 const lldb::ProcessSP &GetProcessSP() const;
615
616 bool IsValid() { return m_valid; }
617
618 void Destroy();
619
620 Status Launch(ProcessLaunchInfo &launch_info,
621 Stream *stream); // Optional stream to receive first stop info
622
623 Status Attach(ProcessAttachInfo &attach_info,
624 Stream *stream); // Optional stream to receive first stop info
625
626 // This part handles the breakpoints.
627
628 BreakpointList &GetBreakpointList(bool internal = false);
629
630 const BreakpointList &GetBreakpointList(bool internal = false) const;
631
632 lldb::BreakpointSP GetLastCreatedBreakpoint() {
633 return m_last_created_breakpoint;
634 }
635
636 lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id);
637
638 // Use this to create a file and line breakpoint to a given module or all
639 // module it is nullptr
640 lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
641 const FileSpec &file, uint32_t line_no,
642 uint32_t column, lldb::addr_t offset,
643 LazyBool check_inlines,
644 LazyBool skip_prologue, bool internal,
645 bool request_hardware,
646 LazyBool move_to_nearest_code);
647
648 // Use this to create breakpoint that matches regex against the source lines
649 // in files given in source_file_list: If function_names is non-empty, also
650 // filter by function after the matches are made.
651 lldb::BreakpointSP CreateSourceRegexBreakpoint(
652 const FileSpecList *containingModules,
653 const FileSpecList *source_file_list,
654 const std::unordered_set<std::string> &function_names,
655 RegularExpression source_regex, bool internal, bool request_hardware,
656 LazyBool move_to_nearest_code);
657
658 // Use this to create a breakpoint from a load address
659 lldb::BreakpointSP CreateBreakpoint(lldb::addr_t load_addr, bool internal,
660 bool request_hardware);
661
662 // Use this to create a breakpoint from a load address and a module file spec
663 lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,
664 bool internal,
665 const FileSpec *file_spec,
666 bool request_hardware);
667
668 // Use this to create Address breakpoints:
669 lldb::BreakpointSP CreateBreakpoint(const Address &addr, bool internal,
670 bool request_hardware);
671
672 // Use this to create a function breakpoint by regexp in
673 // containingModule/containingSourceFiles, or all modules if it is nullptr
674 // When "skip_prologue is set to eLazyBoolCalculate, we use the current
675 // target setting, else we use the values passed in
676 lldb::BreakpointSP CreateFuncRegexBreakpoint(
677 const FileSpecList *containingModules,
678 const FileSpecList *containingSourceFiles, RegularExpression func_regexp,
679 lldb::LanguageType requested_language, LazyBool skip_prologue,
680 bool internal, bool request_hardware);
681
682 // Use this to create a function breakpoint by name in containingModule, or
683 // all modules if it is nullptr When "skip_prologue is set to
684 // eLazyBoolCalculate, we use the current target setting, else we use the
685 // values passed in. func_name_type_mask is or'ed values from the
686 // FunctionNameType enum.
687 lldb::BreakpointSP CreateBreakpoint(
688 const FileSpecList *containingModules,
689 const FileSpecList *containingSourceFiles, const char *func_name,
690 lldb::FunctionNameType func_name_type_mask, lldb::LanguageType language,
691 lldb::addr_t offset, LazyBool skip_prologue, bool internal,
692 bool request_hardware);
693
694 lldb::BreakpointSP
695 CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp,
696 bool throw_bp, bool internal,
697 Args *additional_args = nullptr,
698 Status *additional_args_error = nullptr);
699
700 lldb::BreakpointSP CreateScriptedBreakpoint(
701 const llvm::StringRef class_name, const FileSpecList *containingModules,
702 const FileSpecList *containingSourceFiles, bool internal,
703 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
704 Status *creation_error = nullptr);
705
706 // This is the same as the func_name breakpoint except that you can specify a
707 // vector of names. This is cheaper than a regular expression breakpoint in
708 // the case where you just want to set a breakpoint on a set of names you
709 // already know. func_name_type_mask is or'ed values from the
710 // FunctionNameType enum.
711 lldb::BreakpointSP CreateBreakpoint(
712 const FileSpecList *containingModules,
713 const FileSpecList *containingSourceFiles, const char *func_names[],
714 size_t num_names, lldb::FunctionNameType func_name_type_mask,
715 lldb::LanguageType language, lldb::addr_t offset, LazyBool skip_prologue,
716 bool internal, bool request_hardware);
717
718 lldb::BreakpointSP
719 CreateBreakpoint(const FileSpecList *containingModules,
720 const FileSpecList *containingSourceFiles,
721 const std::vector<std::string> &func_names,
722 lldb::FunctionNameType func_name_type_mask,
723 lldb::LanguageType language, lldb::addr_t m_offset,
724 LazyBool skip_prologue, bool internal,
725 bool request_hardware);
726
727 // Use this to create a general breakpoint:
728 lldb::BreakpointSP CreateBreakpoint(lldb::SearchFilterSP &filter_sp,
729 lldb::BreakpointResolverSP &resolver_sp,
730 bool internal, bool request_hardware,
731 bool resolve_indirect_symbols);
732
733 // Use this to create a watchpoint:
734 lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size,
735 const CompilerType *type, uint32_t kind,
736 Status &error);
737
738 lldb::WatchpointSP GetLastCreatedWatchpoint() {
739 return m_last_created_watchpoint;
740 }
741
742 WatchpointList &GetWatchpointList() { return m_watchpoint_list; }
743
744 // Manages breakpoint names:
745 void AddNameToBreakpoint(BreakpointID &id, const char *name, Status &error);
746
747 void AddNameToBreakpoint(lldb::BreakpointSP &bp_sp, const char *name,
748 Status &error);
749
750 void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, ConstString name);
751
752 BreakpointName *FindBreakpointName(ConstString name, bool can_create,
753 Status &error);
754
755 void DeleteBreakpointName(ConstString name);
756
757 void ConfigureBreakpointName(BreakpointName &bp_name,
758 const BreakpointOptions &options,
759 const BreakpointName::Permissions &permissions);
760 void ApplyNameToBreakpoints(BreakpointName &bp_name);
761
762 void AddBreakpointName(std::unique_ptr<BreakpointName> bp_name);
763
764 void GetBreakpointNames(std::vector<std::string> &names);
765
766 // This call removes ALL breakpoints regardless of permission.
767 void RemoveAllBreakpoints(bool internal_also = false);
768
769 // This removes all the breakpoints, but obeys the ePermDelete on them.
770 void RemoveAllowedBreakpoints();
771
772 void DisableAllBreakpoints(bool internal_also = false);
773
774 void DisableAllowedBreakpoints();
775
776 void EnableAllBreakpoints(bool internal_also = false);
777
778 void EnableAllowedBreakpoints();
779
780 bool DisableBreakpointByID(lldb::break_id_t break_id);
781
782 bool EnableBreakpointByID(lldb::break_id_t break_id);
783
784 bool RemoveBreakpointByID(lldb::break_id_t break_id);
785
786 /// Resets the hit count of all breakpoints.
787 void ResetBreakpointHitCounts();
788
789 // The flag 'end_to_end', default to true, signifies that the operation is
790 // performed end to end, for both the debugger and the debuggee.
791
792 bool RemoveAllWatchpoints(bool end_to_end = true);
793
794 bool DisableAllWatchpoints(bool end_to_end = true);
795
796 bool EnableAllWatchpoints(bool end_to_end = true);
797
798 bool ClearAllWatchpointHitCounts();
799
800 bool ClearAllWatchpointHistoricValues();
801
802 bool IgnoreAllWatchpoints(uint32_t ignore_count);
803
804 bool DisableWatchpointByID(lldb::watch_id_t watch_id);
805
806 bool EnableWatchpointByID(lldb::watch_id_t watch_id);
807
808 bool RemoveWatchpointByID(lldb::watch_id_t watch_id);
809
810 bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count);
811
812 Status SerializeBreakpointsToFile(const FileSpec &file,
813 const BreakpointIDList &bp_ids,
814 bool append);
815
816 Status CreateBreakpointsFromFile(const FileSpec &file,
817 BreakpointIDList &new_bps);
818
819 Status CreateBreakpointsFromFile(const FileSpec &file,
820 std::vector<std::string> &names,
821 BreakpointIDList &new_bps);
822
823 /// Get \a load_addr as a callable code load address for this target
824 ///
825 /// Take \a load_addr and potentially add any address bits that are
826 /// needed to make the address callable. For ARM this can set bit
827 /// zero (if it already isn't) if \a load_addr is a thumb function.
828 /// If \a addr_class is set to AddressClass::eInvalid, then the address
829 /// adjustment will always happen. If it is set to an address class
830 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
831 /// returned.
832 lldb::addr_t GetCallableLoadAddress(
833 lldb::addr_t load_addr,
834 AddressClass addr_class = AddressClass::eInvalid) const;
835
836 /// Get \a load_addr as an opcode for this target.
837 ///
838 /// Take \a load_addr and potentially strip any address bits that are
839 /// needed to make the address point to an opcode. For ARM this can
840 /// clear bit zero (if it already isn't) if \a load_addr is a
841 /// thumb function and load_addr is in code.
842 /// If \a addr_class is set to AddressClass::eInvalid, then the address
843 /// adjustment will always happen. If it is set to an address class
844 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
845 /// returned.
846 lldb::addr_t
847 GetOpcodeLoadAddress(lldb::addr_t load_addr,
848 AddressClass addr_class = AddressClass::eInvalid) const;
849
850 // Get load_addr as breakable load address for this target. Take a addr and
851 // check if for any reason there is a better address than this to put a
852 // breakpoint on. If there is then return that address. For MIPS, if
853 // instruction at addr is a delay slot instruction then this method will find
854 // the address of its previous instruction and return that address.
855 lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr);
856
857 void ModulesDidLoad(ModuleList &module_list);
858
859 void ModulesDidUnload(ModuleList &module_list, bool delete_locations);
860
861 void SymbolsDidLoad(ModuleList &module_list);
862
863 void ClearModules(bool delete_locations);
864
865 /// Called as the last function in Process::DidExec().
866 ///
867 /// Process::DidExec() will clear a lot of state in the process,
868 /// then try to reload a dynamic loader plugin to discover what
869 /// binaries are currently available and then this function should
870 /// be called to allow the target to do any cleanup after everything
871 /// has been figured out. It can remove breakpoints that no longer
872 /// make sense as the exec might have changed the target
873 /// architecture, and unloaded some modules that might get deleted.
874 void DidExec();
875
876 /// Gets the module for the main executable.
877 ///
878 /// Each process has a notion of a main executable that is the file
879 /// that will be executed or attached to. Executable files can have
880 /// dependent modules that are discovered from the object files, or
881 /// discovered at runtime as things are dynamically loaded.
882 ///
883 /// \return
884 /// The shared pointer to the executable module which can
885 /// contains a nullptr Module object if no executable has been
886 /// set.
887 ///
888 /// \see DynamicLoader
889 /// \see ObjectFile::GetDependentModules (FileSpecList&)
890 /// \see Process::SetExecutableModule(lldb::ModuleSP&)
891 lldb::ModuleSP GetExecutableModule();
892
893 Module *GetExecutableModulePointer();
894
895 /// Set the main executable module.
896 ///
897 /// Each process has a notion of a main executable that is the file
898 /// that will be executed or attached to. Executable files can have
899 /// dependent modules that are discovered from the object files, or
900 /// discovered at runtime as things are dynamically loaded.
901 ///
902 /// Setting the executable causes any of the current dependent
903 /// image information to be cleared and replaced with the static
904 /// dependent image information found by calling
905 /// ObjectFile::GetDependentModules (FileSpecList&) on the main
906 /// executable and any modules on which it depends. Calling
907 /// Process::GetImages() will return the newly found images that
908 /// were obtained from all of the object files.
909 ///
910 /// \param[in] module_sp
911 /// A shared pointer reference to the module that will become
912 /// the main executable for this process.
913 ///
914 /// \param[in] load_dependent_files
915 /// If \b true then ask the object files to track down any
916 /// known dependent files.
917 ///
918 /// \see ObjectFile::GetDependentModules (FileSpecList&)
919 /// \see Process::GetImages()
920 void SetExecutableModule(
921 lldb::ModuleSP &module_sp,
922 LoadDependentFiles load_dependent_files = eLoadDependentsDefault);
923
924 bool LoadScriptingResources(std::list<Status> &errors,
925 Stream *feedback_stream = nullptr,
926 bool continue_on_error = true) {
927 return m_images.LoadScriptingResourcesInTarget(
928 this, errors, feedback_stream, continue_on_error);
929 }
930
931 /// Get accessor for the images for this process.
932 ///
933 /// Each process has a notion of a main executable that is the file
934 /// that will be executed or attached to. Executable files can have
935 /// dependent modules that are discovered from the object files, or
936 /// discovered at runtime as things are dynamically loaded. After
937 /// a main executable has been set, the images will contain a list
938 /// of all the files that the executable depends upon as far as the
939 /// object files know. These images will usually contain valid file
940 /// virtual addresses only. When the process is launched or attached
941 /// to, the DynamicLoader plug-in will discover where these images
942 /// were loaded in memory and will resolve the load virtual
943 /// addresses is each image, and also in images that are loaded by
944 /// code.
945 ///
946 /// \return
947 /// A list of Module objects in a module list.
948 const ModuleList &GetImages() const { return m_images; }
949
950 ModuleList &GetImages() { return m_images; }
951
952 /// Return whether this FileSpec corresponds to a module that should be
953 /// considered for general searches.
954 ///
955 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
956 /// and any module that returns \b true will not be searched. Note the
957 /// SearchFilterForUnconstrainedSearches is the search filter that
958 /// gets used in the CreateBreakpoint calls when no modules is provided.
959 ///
960 /// The target call at present just consults the Platform's call of the
961 /// same name.
962 ///
963 /// \param[in] module_spec
964 /// Path to the module.
965 ///
966 /// \return \b true if the module should be excluded, \b false otherwise.
967 bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec);
968
969 /// Return whether this module should be considered for general searches.
970 ///
971 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
972 /// and any module that returns \b true will not be searched. Note the
973 /// SearchFilterForUnconstrainedSearches is the search filter that
974 /// gets used in the CreateBreakpoint calls when no modules is provided.
975 ///
976 /// The target call at present just consults the Platform's call of the
977 /// same name.
978 ///
979 /// FIXME: When we get time we should add a way for the user to set modules
980 /// that they
981 /// don't want searched, in addition to or instead of the platform ones.
982 ///
983 /// \param[in] module_sp
984 /// A shared pointer reference to the module that checked.
985 ///
986 /// \return \b true if the module should be excluded, \b false otherwise.
987 bool
988 ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP &module_sp);
989
990 const ArchSpec &GetArchitecture() const { return m_arch.GetSpec(); }
991
992 /// Returns the name of the target's ABI plugin.
993 llvm::StringRef GetABIName() const;
994
995 /// Set the architecture for this target.
996 ///
997 /// If the current target has no Images read in, then this just sets the
998 /// architecture, which will be used to select the architecture of the
999 /// ExecutableModule when that is set. If the current target has an
1000 /// ExecutableModule, then calling SetArchitecture with a different
1001 /// architecture from the currently selected one will reset the
1002 /// ExecutableModule to that slice of the file backing the ExecutableModule.
1003 /// If the file backing the ExecutableModule does not contain a fork of this
1004 /// architecture, then this code will return false, and the architecture
1005 /// won't be changed. If the input arch_spec is the same as the already set
1006 /// architecture, this is a no-op.
1007 ///
1008 /// \param[in] arch_spec
1009 /// The new architecture.
1010 ///
1011 /// \param[in] set_platform
1012 /// If \b true, then the platform will be adjusted if the currently
1013 /// selected platform is not compatible with the architecture being set.
1014 /// If \b false, then just the architecture will be set even if the
1015 /// currently selected platform isn't compatible (in case it might be
1016 /// manually set following this function call).
1017 ///
1018 /// \param[in] merged
1019 /// If true, arch_spec is merged with the current
1020 /// architecture. Otherwise it's replaced.
1021 ///
1022 /// \return
1023 /// \b true if the architecture was successfully set, \b false otherwise.
1024 bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform = false,
1025 bool merge = true);
1026
1027 bool MergeArchitecture(const ArchSpec &arch_spec);
1028
1029 Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }
1030
1031 Debugger &GetDebugger() { return m_debugger; }
1032
1033 size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
1034 Status &error);
1035
1036 // Reading memory through the target allows us to skip going to the process
1037 // for reading memory if possible and it allows us to try and read from any
1038 // constant sections in our object files on disk. If you always want live
1039 // program memory, read straight from the process. If you possibly want to
1040 // read from const sections in object files, read from the target. This
1041 // version of ReadMemory will try and read memory from the process if the
1042 // process is alive. The order is:
1043 // 1 - if (force_live_memory == false) and the address falls in a read-only
1044 // section, then read from the file cache
1045 // 2 - if there is a process, then read from memory
1046 // 3 - if there is no process, then read from the file cache
1047 size_t ReadMemory(const Address &addr, void *dst, size_t dst_len,
1048 Status &error, bool force_live_memory = false,
1049 lldb::addr_t *load_addr_ptr = nullptr);
1050
1051 size_t ReadCStringFromMemory(const Address &addr, std::string &out_str,
1052 Status &error, bool force_live_memory = false);
1053
1054 size_t ReadCStringFromMemory(const Address &addr, char *dst,
1055 size_t dst_max_len, Status &result_error,
1056 bool force_live_memory = false);
1057
1058 /// Read a NULL terminated string from memory
1059 ///
1060 /// This function will read a cache page at a time until a NULL string
1061 /// terminator is found. It will stop reading if an aligned sequence of NULL
1062 /// termination \a type_width bytes is not found before reading \a
1063 /// cstr_max_len bytes. The results are always guaranteed to be NULL
1064 /// terminated, and that no more than (max_bytes - type_width) bytes will be
1065 /// read.
1066 ///
1067 /// \param[in] addr
1068 /// The address to start the memory read.
1069 ///
1070 /// \param[in] dst
1071 /// A character buffer containing at least max_bytes.
1072 ///
1073 /// \param[in] max_bytes
1074 /// The maximum number of bytes to read.
1075 ///
1076 /// \param[in] error
1077 /// The error status of the read operation.
1078 ///
1079 /// \param[in] type_width
1080 /// The size of the null terminator (1 to 4 bytes per
1081 /// character). Defaults to 1.
1082 ///
1083 /// \return
1084 /// The error status or the number of bytes prior to the null terminator.
1085 size_t ReadStringFromMemory(const Address &addr, char *dst, size_t max_bytes,
1086 Status &error, size_t type_width,
1087 bool force_live_memory = true);
1088
1089 size_t ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
1090 bool is_signed, Scalar &scalar,
1091 Status &error,
1092 bool force_live_memory = false);
1093
1094 uint64_t ReadUnsignedIntegerFromMemory(const Address &addr,
1095 size_t integer_byte_size,
1096 uint64_t fail_value, Status &error,
1097 bool force_live_memory = false);
1098
1099 bool ReadPointerFromMemory(const Address &addr, Status &error,
1100 Address &pointer_addr,
1101 bool force_live_memory = false);
1102
1103 SectionLoadList &GetSectionLoadList() {
1104 return m_section_load_history.GetCurrentSectionLoadList();
1105 }
1106
1107 static Target *GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
1108 const SymbolContext *sc_ptr);
1109
1110 // lldb::ExecutionContextScope pure virtual functions
1111 lldb::TargetSP CalculateTarget() override;
1112
1113 lldb::ProcessSP CalculateProcess() override;
1114
1115 lldb::ThreadSP CalculateThread() override;
1116
1117 lldb::StackFrameSP CalculateStackFrame() override;
1118
1119 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
1120
1121 PathMappingList &GetImageSearchPathList();
1122
1123 llvm::Expected<lldb::TypeSystemSP>
1124 GetScratchTypeSystemForLanguage(lldb::LanguageType language,
1125 bool create_on_demand = true);
1126
1127 std::vector<lldb::TypeSystemSP>
1128 GetScratchTypeSystems(bool create_on_demand = true);
1129
1130 PersistentExpressionState *
1131 GetPersistentExpressionStateForLanguage(lldb::LanguageType language);
1132
1133 // Creates a UserExpression for the given language, the rest of the
1134 // parameters have the same meaning as for the UserExpression constructor.
1135 // Returns a new-ed object which the caller owns.
1136
1137 UserExpression *
1138 GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix,
1139 lldb::LanguageType language,
1140 Expression::ResultType desired_type,
1141 const EvaluateExpressionOptions &options,
1142 ValueObject *ctx_obj, Status &error);
1143
1144 // Creates a FunctionCaller for the given language, the rest of the
1145 // parameters have the same meaning as for the FunctionCaller constructor.
1146 // Since a FunctionCaller can't be
1147 // IR Interpreted, it makes no sense to call this with an
1148 // ExecutionContextScope that lacks
1149 // a Process.
1150 // Returns a new-ed object which the caller owns.
1151
1152 FunctionCaller *GetFunctionCallerForLanguage(lldb::LanguageType language,
1153 const CompilerType &return_type,
1154 const Address &function_address,
1155 const ValueList &arg_value_list,
1156 const char *name, Status &error);
1157
1158 /// Creates and installs a UtilityFunction for the given language.
1159 llvm::Expected<std::unique_ptr<UtilityFunction>>
1160 CreateUtilityFunction(std::string expression, std::string name,
1161 lldb::LanguageType language, ExecutionContext &exe_ctx);
1162
1163 // Install any files through the platform that need be to installed prior to
1164 // launching or attaching.
1165 Status Install(ProcessLaunchInfo *launch_info);
1166
1167 bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr);
1168
1169 bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr,
1170 uint32_t stop_id = SectionLoadHistory::eStopIDNow);
1171
1172 bool SetSectionLoadAddress(const lldb::SectionSP &section,
1173 lldb::addr_t load_addr,
1174 bool warn_multiple = false);
1175
1176 size_t UnloadModuleSections(const lldb::ModuleSP &module_sp);
1177
1178 size_t UnloadModuleSections(const ModuleList &module_list);
1179
1180 bool SetSectionUnloaded(const lldb::SectionSP &section_sp);
1181
1182 bool SetSectionUnloaded(const lldb::SectionSP &section_sp,
1183 lldb::addr_t load_addr);
1184
1185 void ClearAllLoadedSections();
1186
1187 /// Set the \a Trace object containing processor trace information of this
1188 /// target.
1189 ///
1190 /// \param[in] trace_sp
1191 /// The trace object.
1192 void SetTrace(const lldb::TraceSP &trace_sp);
1193
1194 /// Get the \a Trace object containing processor trace information of this
1195 /// target.
1196 ///
1197 /// \return
1198 /// The trace object. It might be undefined.
1199 lldb::TraceSP GetTrace();
1200
1201 /// Create a \a Trace object for the current target using the using the
1202 /// default supported tracing technology for this process.
1203 ///
1204 /// \return
1205 /// The new \a Trace or an \a llvm::Error if a \a Trace already exists or
1206 /// the trace couldn't be created.
1207 llvm::Expected<lldb::TraceSP> CreateTrace();
1208
1209 /// If a \a Trace object is present, this returns it, otherwise a new Trace is
1210 /// created with \a Trace::CreateTrace.
1211 llvm::Expected<lldb::TraceSP> GetTraceOrCreate();
1212
1213 // Since expressions results can persist beyond the lifetime of a process,
1214 // and the const expression results are available after a process is gone, we
1215 // provide a way for expressions to be evaluated from the Target itself. If
1216 // an expression is going to be run, then it should have a frame filled in in
1217 // the execution context.
1218 lldb::ExpressionResults EvaluateExpression(
1219 llvm::StringRef expression, ExecutionContextScope *exe_scope,
1220 lldb::ValueObjectSP &result_valobj_sp,
1221 const EvaluateExpressionOptions &options = EvaluateExpressionOptions(),
1222 std::string *fixed_expression = nullptr, ValueObject *ctx_obj = nullptr);
1223
1224 lldb::ExpressionVariableSP GetPersistentVariable(ConstString name);
1225
1226 lldb::addr_t GetPersistentSymbol(ConstString name);
1227
1228 /// This method will return the address of the starting function for
1229 /// this binary, e.g. main() or its equivalent. This can be used as
1230 /// an address of a function that is not called once a binary has
1231 /// started running - e.g. as a return address for inferior function
1232 /// calls that are unambiguous completion of the function call, not
1233 /// called during the course of the inferior function code running.
1234 ///
1235 /// If no entry point can be found, an invalid address is returned.
1236 ///
1237 /// \param [out] err
1238 /// This object will be set to failure if no entry address could
1239 /// be found, and may contain a helpful error message.
1240 //
1241 /// \return
1242 /// Returns the entry address for this program, or an error
1243 /// if none can be found.
1244 llvm::Expected<lldb_private::Address> GetEntryPointAddress();
1245
1246 CompilerType GetRegisterType(const std::string &name,
1247 const lldb_private::RegisterFlags &flags,
1248 uint32_t byte_size);
1249
1250 // Target Stop Hooks
1251 class StopHook : public UserID {
1252 public:
1253 StopHook(const StopHook &rhs);
1254 virtual ~StopHook() = default;
1255
1256 enum class StopHookKind : uint32_t { CommandBased = 0, ScriptBased };
1257 enum class StopHookResult : uint32_t {
1258 KeepStopped = 0,
1259 RequestContinue,
1260 AlreadyContinued
1261 };
1262
1263 lldb::TargetSP &GetTarget() { return m_target_sp; }
1264
1265 // Set the specifier. The stop hook will own the specifier, and is
1266 // responsible for deleting it when we're done.
1267 void SetSpecifier(SymbolContextSpecifier *specifier);
1268
1269 SymbolContextSpecifier *GetSpecifier() { return m_specifier_sp.get(); }
1270
1271 bool ExecutionContextPasses(const ExecutionContext &exe_ctx);
1272
1273 // Called on stop, this gets passed the ExecutionContext for each "stop
1274 // with a reason" thread. It should add to the stream whatever text it
1275 // wants to show the user, and return False to indicate it wants the target
1276 // not to stop.
1277 virtual StopHookResult HandleStop(ExecutionContext &exe_ctx,
1278 lldb::StreamSP output) = 0;
1279
1280 // Set the Thread Specifier. The stop hook will own the thread specifier,
1281 // and is responsible for deleting it when we're done.
1282 void SetThreadSpecifier(ThreadSpec *specifier);
1283
1284 ThreadSpec *GetThreadSpecifier() { return m_thread_spec_up.get(); }
1285
1286 bool IsActive() { return m_active; }
1287
1288 void SetIsActive(bool is_active) { m_active = is_active; }
1289
1290 void SetAutoContinue(bool auto_continue) {
1291 m_auto_continue = auto_continue;
1292 }
1293
1294 bool GetAutoContinue() const { return m_auto_continue; }
1295
1296 void GetDescription(Stream *s, lldb::DescriptionLevel level) const;
1297 virtual void GetSubclassDescription(Stream *s,
1298 lldb::DescriptionLevel level) const = 0;
1299
1300 protected:
1301 lldb::TargetSP m_target_sp;
1302 lldb::SymbolContextSpecifierSP m_specifier_sp;
1303 std::unique_ptr<ThreadSpec> m_thread_spec_up;
1304 bool m_active = true;
1305 bool m_auto_continue = false;
1306
1307 StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid);
1308 };
1309
1310 class StopHookCommandLine : public StopHook {
1311 public:
1312 ~StopHookCommandLine() override = default;
1313
1314 StringList &GetCommands() { return m_commands; }
1315 void SetActionFromString(const std::string &strings);
1316 void SetActionFromStrings(const std::vector<std::string> &strings);
1317
1318 StopHookResult HandleStop(ExecutionContext &exc_ctx,
1319 lldb::StreamSP output_sp) override;
1320 void GetSubclassDescription(Stream *s,
1321 lldb::DescriptionLevel level) const override;
1322
1323 private:
1324 StringList m_commands;
1325 // Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
1326 // and fill it with commands, and SetSpecifier to set the specifier shared
1327 // pointer (can be null, that will match anything.)
1328 StopHookCommandLine(lldb::TargetSP target_sp, lldb::user_id_t uid)
1329 : StopHook(target_sp, uid) {}
1330 friend class Target;
1331 };
1332
1333 class StopHookScripted : public StopHook {
1334 public:
1335 ~StopHookScripted() override = default;
1336 StopHookResult HandleStop(ExecutionContext &exc_ctx,
1337 lldb::StreamSP output) override;
1338
1339 Status SetScriptCallback(std::string class_name,
1340 StructuredData::ObjectSP extra_args_sp);
1341
1342 void GetSubclassDescription(Stream *s,
1343 lldb::DescriptionLevel level) const override;
1344
1345 private:
1346 std::string m_class_name;
1347 /// This holds the dictionary of keys & values that can be used to
1348 /// parametrize any given callback's behavior.
1349 StructuredDataImpl m_extra_args;
1350 /// This holds the python callback object.
1351 StructuredData::GenericSP m_implementation_sp;
1352
1353 /// Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
1354 /// and fill it with commands, and SetSpecifier to set the specifier shared
1355 /// pointer (can be null, that will match anything.)
1356 StopHookScripted(lldb::TargetSP target_sp, lldb::user_id_t uid)
1357 : StopHook(target_sp, uid) {}
1358 friend class Target;
1359 };
1360
1361 typedef std::shared_ptr<StopHook> StopHookSP;
1362
1363 /// Add an empty stop hook to the Target's stop hook list, and returns a
1364 /// shared pointer to it in new_hook. Returns the id of the new hook.
1365 StopHookSP CreateStopHook(StopHook::StopHookKind kind);
1366
1367 /// If you tried to create a stop hook, and that failed, call this to
1368 /// remove the stop hook, as it will also reset the stop hook counter.
1369 void UndoCreateStopHook(lldb::user_id_t uid);
1370
1371 // Runs the stop hooks that have been registered for this target.
1372 // Returns true if the stop hooks cause the target to resume.
1373 bool RunStopHooks();
1374
1375 size_t GetStopHookSize();
1376
1377 bool SetSuppresStopHooks(bool suppress) {
1378 bool old_value = m_suppress_stop_hooks;
1379 m_suppress_stop_hooks = suppress;
1380 return old_value;
1381 }
1382
1383 bool GetSuppressStopHooks() { return m_suppress_stop_hooks; }
1384
1385 bool RemoveStopHookByID(lldb::user_id_t uid);
1386
1387 void RemoveAllStopHooks();
1388
1389 StopHookSP GetStopHookByID(lldb::user_id_t uid);
1390
1391 bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state);
1392
1393 void SetAllStopHooksActiveState(bool active_state);
1394
1395 size_t GetNumStopHooks() const { return m_stop_hooks.size(); }
1396
1397 StopHookSP GetStopHookAtIndex(size_t index) {
1398 if (index >= GetNumStopHooks())
1399 return StopHookSP();
1400 StopHookCollection::iterator pos = m_stop_hooks.begin();
1401
1402 while (index > 0) {
1403 pos++;
1404 index--;
1405 }
1406 return (*pos).second;
1407 }
1408
1409 lldb::PlatformSP GetPlatform() { return m_platform_sp; }
1410
1411 void SetPlatform(const lldb::PlatformSP &platform_sp) {
1412 m_platform_sp = platform_sp;
1413 }
1414
1415 SourceManager &GetSourceManager();
1416
1417 // Methods.
1418 lldb::SearchFilterSP
1419 GetSearchFilterForModule(const FileSpec *containingModule);
1420
1421 lldb::SearchFilterSP
1422 GetSearchFilterForModuleList(const FileSpecList *containingModuleList);
1423
1424 lldb::SearchFilterSP
1425 GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules,
1426 const FileSpecList *containingSourceFiles);
1427
1428 lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language,
1429 const char *repl_options, bool can_create);
1430
1431 void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp);
1432
1433 StackFrameRecognizerManager &GetFrameRecognizerManager() {
1434 return *m_frame_recognizer_manager_up;
1435 }
1436
1437 void SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info);
1438
1439 /// Add a signal for the target. This will get copied over to the process
1440 /// if the signal exists on that target. Only the values with Yes and No are
1441 /// set, Calculate values will be ignored.
1442protected:
1443 struct DummySignalValues {
1444 LazyBool pass = eLazyBoolCalculate;
1445 LazyBool notify = eLazyBoolCalculate;
1446 LazyBool stop = eLazyBoolCalculate;
1447 DummySignalValues(LazyBool pass, LazyBool notify, LazyBool stop)
1448 : pass(pass), notify(notify), stop(stop) {}
1449 DummySignalValues() = default;
1450 };
1451 using DummySignalElement = llvm::StringMapEntry<DummySignalValues>;
1452 static bool UpdateSignalFromDummy(lldb::UnixSignalsSP signals_sp,
1453 const DummySignalElement &element);
1454 static bool ResetSignalFromDummy(lldb::UnixSignalsSP signals_sp,
1455 const DummySignalElement &element);
1456
1457public:
1458 /// Add a signal to the Target's list of stored signals/actions. These
1459 /// values will get copied into any processes launched from
1460 /// this target.
1461 void AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool print,
1462 LazyBool stop);
1463 /// Updates the signals in signals_sp using the stored dummy signals.
1464 /// If warning_stream_sp is not null, if any stored signals are not found in
1465 /// the current process, a warning will be emitted here.
1466 void UpdateSignalsFromDummy(lldb::UnixSignalsSP signals_sp,
1467 lldb::StreamSP warning_stream_sp);
1468 /// Clear the dummy signals in signal_names from the target, or all signals
1469 /// if signal_names is empty. Also remove the behaviors they set from the
1470 /// process's signals if it exists.
1471 void ClearDummySignals(Args &signal_names);
1472 /// Print all the signals set in this target.
1473 void PrintDummySignals(Stream &strm, Args &signals);
1474
1475protected:
1476 /// Implementing of ModuleList::Notifier.
1477
1478 void NotifyModuleAdded(const ModuleList &module_list,
1479 const lldb::ModuleSP &module_sp) override;
1480
1481 void NotifyModuleRemoved(const ModuleList &module_list,
1482 const lldb::ModuleSP &module_sp) override;
1483
1484 void NotifyModuleUpdated(const ModuleList &module_list,
1485 const lldb::ModuleSP &old_module_sp,
1486 const lldb::ModuleSP &new_module_sp) override;
1487
1488 void NotifyWillClearList(const ModuleList &module_list) override;
1489
1490 void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override;
1491
1492 class Arch {
1493 public:
1494 explicit Arch(const ArchSpec &spec);
1495 const Arch &operator=(const ArchSpec &spec);
1496
1497 const ArchSpec &GetSpec() const { return m_spec; }
1498 Architecture *GetPlugin() const { return m_plugin_up.get(); }
1499
1500 private:
1501 ArchSpec m_spec;
1502 std::unique_ptr<Architecture> m_plugin_up;
1503 };
1504
1505 // Member variables.
1506 Debugger &m_debugger;
1507 lldb::PlatformSP m_platform_sp; ///< The platform for this target.
1508 std::recursive_mutex m_mutex; ///< An API mutex that is used by the lldb::SB*
1509 /// classes make the SB interface thread safe
1510 /// When the private state thread calls SB API's - usually because it is
1511 /// running OS plugin or Python ThreadPlan code - it should not block on the
1512 /// API mutex that is held by the code that kicked off the sequence of events
1513 /// that led us to run the code. We hand out this mutex instead when we
1514 /// detect that code is running on the private state thread.
1515 std::recursive_mutex m_private_mutex;
1516 Arch m_arch;
1517 ModuleList m_images; ///< The list of images for this process (shared
1518 /// libraries and anything dynamically loaded).
1519 SectionLoadHistory m_section_load_history;
1520 BreakpointList m_breakpoint_list;
1521 BreakpointList m_internal_breakpoint_list;
1522 using BreakpointNameList =
1523 std::map<ConstString, std::unique_ptr<BreakpointName>>;
1524 BreakpointNameList m_breakpoint_names;
1525
1526 lldb::BreakpointSP m_last_created_breakpoint;
1527 WatchpointList m_watchpoint_list;
1528 lldb::WatchpointSP m_last_created_watchpoint;
1529 // We want to tightly control the process destruction process so we can
1530 // correctly tear down everything that we need to, so the only class that
1531 // knows about the process lifespan is this target class.
1532 lldb::ProcessSP m_process_sp;
1533 lldb::SearchFilterSP m_search_filter_sp;
1534 PathMappingList m_image_search_paths;
1535 TypeSystemMap m_scratch_type_system_map;
1536
1537 typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
1538 REPLMap m_repl_map;
1539
1540 lldb::SourceManagerUP m_source_manager_up;
1541
1542 typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
1543 StopHookCollection m_stop_hooks;
1544 lldb::user_id_t m_stop_hook_next_id;
1545 uint32_t m_latest_stop_hook_id; /// This records the last natural stop at
1546 /// which we ran a stop-hook.
1547 bool m_valid;
1548 bool m_suppress_stop_hooks; /// Used to not run stop hooks for expressions
1549 bool m_is_dummy_target;
1550 unsigned m_next_persistent_variable_index = 0;
1551 /// An optional \a lldb_private::Trace object containing processor trace
1552 /// information of this target.
1553 lldb::TraceSP m_trace_sp;
1554 /// Stores the frame recognizers of this target.
1555 lldb::StackFrameRecognizerManagerUP m_frame_recognizer_manager_up;
1556 /// These are used to set the signal state when you don't have a process and
1557 /// more usefully in the Dummy target where you can't know exactly what
1558 /// signals you will have.
1559 llvm::StringMap<DummySignalValues> m_dummy_signals;
1560
1561 static void ImageSearchPathsChanged(const PathMappingList &path_list,
1562 void *baton);
1563
1564 // Utilities for `statistics` command.
1565private:
1566 // Target metrics storage.
1567 TargetStats m_stats;
1568
1569public:
1570 /// Get metrics associated with this target in JSON format.
1571 ///
1572 /// Target metrics help measure timings and information that is contained in
1573 /// a target. These are designed to help measure performance of a debug
1574 /// session as well as represent the current state of the target, like
1575 /// information on the currently modules, currently set breakpoints and more.
1576 ///
1577 /// \return
1578 /// Returns a JSON value that contains all target metrics.
1579 llvm::json::Value ReportStatistics();
1580
1581 TargetStats &GetStatistics() { return m_stats; }
1582
1583private:
1584 /// Construct with optional file and arch.
1585 ///
1586 /// This member is private. Clients must use
1587 /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1588 /// so all targets can be tracked from the central target list.
1589 ///
1590 /// \see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1591 Target(Debugger &debugger, const ArchSpec &target_arch,
1592 const lldb::PlatformSP &platform_sp, bool is_dummy_target);
1593
1594 // Helper function.
1595 bool ProcessIsValid();
1596
1597 // Copy breakpoints, stop hooks and so forth from the dummy target:
1598 void PrimeFromDummyTarget(Target &target);
1599
1600 void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal);
1601
1602 void FinalizeFileActions(ProcessLaunchInfo &info);
1603
1604 /// Return a recommended size for memory reads at \a addr, optimizing for
1605 /// cache usage.
1606 lldb::addr_t GetReasonableReadSize(const Address &addr);
1607
1608 Target(const Target &) = delete;
1609 const Target &operator=(const Target &) = delete;
1610};
1611
1612} // namespace lldb_private
1613
1614#endif // LLDB_TARGET_TARGET_H
1615

Warning: This file is not a C or C++ file. It does not have highlighting.

source code of lldb/include/lldb/Target/Target.h