Coverage Report

Created: 2022-01-22 13:19

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