Coverage Report

Created: 2023-09-12 09:32

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