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