Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Target/Target.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Target.cpp --------------------------------------------------------===//
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
#include "lldb/Target/Target.h"
10
#include "lldb/Breakpoint/BreakpointIDList.h"
11
#include "lldb/Breakpoint/BreakpointPrecondition.h"
12
#include "lldb/Breakpoint/BreakpointResolver.h"
13
#include "lldb/Breakpoint/BreakpointResolverAddress.h"
14
#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
15
#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
16
#include "lldb/Breakpoint/BreakpointResolverName.h"
17
#include "lldb/Breakpoint/BreakpointResolverScripted.h"
18
#include "lldb/Breakpoint/Watchpoint.h"
19
#include "lldb/Core/Debugger.h"
20
#include "lldb/Core/Module.h"
21
#include "lldb/Core/ModuleSpec.h"
22
#include "lldb/Core/PluginManager.h"
23
#include "lldb/Core/SearchFilter.h"
24
#include "lldb/Core/Section.h"
25
#include "lldb/Core/SourceManager.h"
26
#include "lldb/Core/StructuredDataImpl.h"
27
#include "lldb/Core/ValueObject.h"
28
#include "lldb/Core/ValueObjectConstResult.h"
29
#include "lldb/Expression/DiagnosticManager.h"
30
#include "lldb/Expression/ExpressionVariable.h"
31
#include "lldb/Expression/REPL.h"
32
#include "lldb/Expression/UserExpression.h"
33
#include "lldb/Expression/UtilityFunction.h"
34
#include "lldb/Host/Host.h"
35
#include "lldb/Host/PosixApi.h"
36
#include "lldb/Host/StreamFile.h"
37
#include "lldb/Interpreter/CommandInterpreter.h"
38
#include "lldb/Interpreter/CommandReturnObject.h"
39
#include "lldb/Interpreter/OptionGroupWatchpoint.h"
40
#include "lldb/Interpreter/OptionValues.h"
41
#include "lldb/Interpreter/Property.h"
42
#include "lldb/Symbol/Function.h"
43
#include "lldb/Symbol/ObjectFile.h"
44
#include "lldb/Symbol/Symbol.h"
45
#include "lldb/Target/ABI.h"
46
#include "lldb/Target/Language.h"
47
#include "lldb/Target/LanguageRuntime.h"
48
#include "lldb/Target/Process.h"
49
#include "lldb/Target/RegisterTypeBuilder.h"
50
#include "lldb/Target/SectionLoadList.h"
51
#include "lldb/Target/StackFrame.h"
52
#include "lldb/Target/StackFrameRecognizer.h"
53
#include "lldb/Target/SystemRuntime.h"
54
#include "lldb/Target/Thread.h"
55
#include "lldb/Target/ThreadSpec.h"
56
#include "lldb/Target/UnixSignals.h"
57
#include "lldb/Utility/Event.h"
58
#include "lldb/Utility/FileSpec.h"
59
#include "lldb/Utility/LLDBAssert.h"
60
#include "lldb/Utility/LLDBLog.h"
61
#include "lldb/Utility/Log.h"
62
#include "lldb/Utility/State.h"
63
#include "lldb/Utility/StreamString.h"
64
#include "lldb/Utility/Timer.h"
65
66
#include "llvm/ADT/ScopeExit.h"
67
#include "llvm/ADT/SetVector.h"
68
69
#include <memory>
70
#include <mutex>
71
#include <optional>
72
#include <sstream>
73
74
using namespace lldb;
75
using namespace lldb_private;
76
77
constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
78
79
Target::Arch::Arch(const ArchSpec &spec)
80
9.02k
    : m_spec(spec),
81
9.02k
      m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
82
83
3.14k
const Target::Arch &Target::Arch::operator=(const ArchSpec &spec) {
84
3.14k
  m_spec = spec;
85
3.14k
  m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
86
3.14k
  return *this;
87
3.14k
}
88
89
10.6k
ConstString &Target::GetStaticBroadcasterClass() {
90
10.6k
  static ConstString class_name("lldb.target");
91
10.6k
  return class_name;
92
10.6k
}
93
94
Target::Target(Debugger &debugger, const ArchSpec &target_arch,
95
               const lldb::PlatformSP &platform_sp, bool is_dummy_target)
96
9.02k
    : TargetProperties(this),
97
9.02k
      Broadcaster(debugger.GetBroadcasterManager(),
98
9.02k
                  Target::GetStaticBroadcasterClass().AsCString()),
99
9.02k
      ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
100
9.02k
      m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
101
9.02k
      m_breakpoint_list(false), m_internal_breakpoint_list(true),
102
9.02k
      m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
103
9.02k
      m_image_search_paths(ImageSearchPathsChanged, this),
104
9.02k
      m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
105
9.02k
      m_latest_stop_hook_id(0), m_valid(true), m_suppress_stop_hooks(false),
106
9.02k
      m_is_dummy_target(is_dummy_target),
107
      m_frame_recognizer_manager_up(
108
9.02k
          std::make_unique<StackFrameRecognizerManager>()) {
109
9.02k
  SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
110
9.02k
  SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
111
9.02k
  SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
112
9.02k
  SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
113
9.02k
  SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
114
115
9.02k
  CheckInWithManager();
116
117
9.02k
  LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()",
118
9.02k
           static_cast<void *>(this));
119
9.02k
  if (target_arch.IsValid()) {
120
8.73k
    LLDB_LOG(GetLog(LLDBLog::Target),
121
8.73k
             "Target::Target created with architecture {0} ({1})",
122
8.73k
             target_arch.GetArchitectureName(),
123
8.73k
             target_arch.GetTriple().getTriple().c_str());
124
8.73k
  }
125
126
9.02k
  UpdateLaunchInfoFromProperties();
127
9.02k
}
128
129
8.87k
Target::~Target() {
130
8.87k
  Log *log = GetLog(LLDBLog::Object);
131
8.87k
  LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
132
8.87k
  DeleteCurrentProcess();
133
8.87k
}
134
135
2.88k
void Target::PrimeFromDummyTarget(Target &target) {
136
2.88k
  m_stop_hooks = target.m_stop_hooks;
137
138
2.88k
  for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) {
139
15
    if (breakpoint_sp->IsInternal())
140
0
      continue;
141
142
15
    BreakpointSP new_bp(
143
15
        Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
144
15
    AddBreakpoint(std::move(new_bp), false);
145
15
  }
146
147
2.88k
  for (const auto &bp_name_entry : target.m_breakpoint_names) {
148
1
    AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second));
149
1
  }
150
151
2.88k
  m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
152
2.88k
      *target.m_frame_recognizer_manager_up);
153
154
2.88k
  m_dummy_signals = target.m_dummy_signals;
155
2.88k
}
156
157
11
void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
158
  //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
159
11
  if (description_level != lldb::eDescriptionLevelBrief) {
160
2
    s->Indent();
161
2
    s->PutCString("Target\n");
162
2
    s->IndentMore();
163
2
    m_images.Dump(s);
164
2
    m_breakpoint_list.Dump(s);
165
2
    m_internal_breakpoint_list.Dump(s);
166
2
    s->IndentLess();
167
9
  } else {
168
9
    Module *exe_module = GetExecutableModulePointer();
169
9
    if (exe_module)
170
9
      s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
171
0
    else
172
0
      s->PutCString("No executable module.");
173
9
  }
174
11
}
175
176
2.48k
void Target::CleanupProcess() {
177
  // Do any cleanup of the target we need to do between process instances.
178
  // NB It is better to do this before destroying the process in case the
179
  // clean up needs some help from the process.
180
2.48k
  m_breakpoint_list.ClearAllBreakpointSites();
181
2.48k
  m_internal_breakpoint_list.ClearAllBreakpointSites();
182
2.48k
  ResetBreakpointHitCounts();
183
  // Disable watchpoints just on the debugger side.
184
2.48k
  std::unique_lock<std::recursive_mutex> lock;
185
2.48k
  this->GetWatchpointList().GetListMutex(lock);
186
2.48k
  DisableAllWatchpoints(false);
187
2.48k
  ClearAllWatchpointHitCounts();
188
2.48k
  ClearAllWatchpointHistoricValues();
189
2.48k
  m_latest_stop_hook_id = 0;
190
2.48k
}
191
192
16.3k
void Target::DeleteCurrentProcess() {
193
16.3k
  if (m_process_sp) {
194
    // We dispose any active tracing sessions on the current process
195
2.48k
    m_trace_sp.reset();
196
2.48k
    m_section_load_history.Clear();
197
2.48k
    if (m_process_sp->IsAlive())
198
194
      m_process_sp->Destroy(false);
199
200
2.48k
    m_process_sp->Finalize();
201
202
2.48k
    CleanupProcess();
203
204
2.48k
    m_process_sp.reset();
205
2.48k
  }
206
16.3k
}
207
208
const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
209
                                             llvm::StringRef plugin_name,
210
                                             const FileSpec *crash_file,
211
2.48k
                                             bool can_connect) {
212
2.48k
  if (!listener_sp)
213
11
    listener_sp = GetDebugger().GetListener();
214
2.48k
  DeleteCurrentProcess();
215
2.48k
  m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
216
2.48k
                                     listener_sp, crash_file, can_connect);
217
2.48k
  return m_process_sp;
218
2.48k
}
219
220
1.73M
const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
221
222
lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
223
0
                             const char *repl_options, bool can_create) {
224
0
  if (language == eLanguageTypeUnknown)
225
0
    language = m_debugger.GetREPLLanguage();
226
227
0
  if (language == eLanguageTypeUnknown) {
228
0
    LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
229
230
0
    if (auto single_lang = repl_languages.GetSingularLanguage()) {
231
0
      language = *single_lang;
232
0
    } else if (repl_languages.Empty()) {
233
0
      err.SetErrorString(
234
0
          "LLDB isn't configured with REPL support for any languages.");
235
0
      return REPLSP();
236
0
    } else {
237
0
      err.SetErrorString(
238
0
          "Multiple possible REPL languages.  Please specify a language.");
239
0
      return REPLSP();
240
0
    }
241
0
  }
242
243
0
  REPLMap::iterator pos = m_repl_map.find(language);
244
245
0
  if (pos != m_repl_map.end()) {
246
0
    return pos->second;
247
0
  }
248
249
0
  if (!can_create) {
250
0
    err.SetErrorStringWithFormat(
251
0
        "Couldn't find an existing REPL for %s, and can't create a new one",
252
0
        Language::GetNameForLanguageType(language));
253
0
    return lldb::REPLSP();
254
0
  }
255
256
0
  Debugger *const debugger = nullptr;
257
0
  lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
258
259
0
  if (ret) {
260
0
    m_repl_map[language] = ret;
261
0
    return m_repl_map[language];
262
0
  }
263
264
0
  if (err.Success()) {
265
0
    err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
266
0
                                 Language::GetNameForLanguageType(language));
267
0
  }
268
269
0
  return lldb::REPLSP();
270
0
}
271
272
0
void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
273
0
  lldbassert(!m_repl_map.count(language));
274
275
0
  m_repl_map[language] = repl_sp;
276
0
}
277
278
2.88k
void Target::Destroy() {
279
2.88k
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
280
2.88k
  m_valid = false;
281
2.88k
  DeleteCurrentProcess();
282
2.88k
  m_platform_sp.reset();
283
2.88k
  m_arch = ArchSpec();
284
2.88k
  ClearModules(true);
285
2.88k
  m_section_load_history.Clear();
286
2.88k
  const bool notify = false;
287
2.88k
  m_breakpoint_list.RemoveAll(notify);
288
2.88k
  m_internal_breakpoint_list.RemoveAll(notify);
289
2.88k
  m_last_created_breakpoint.reset();
290
2.88k
  m_watchpoint_list.RemoveAll(notify);
291
2.88k
  m_last_created_watchpoint.reset();
292
2.88k
  m_search_filter_sp.reset();
293
2.88k
  m_image_search_paths.Clear(notify);
294
2.88k
  m_stop_hooks.clear();
295
2.88k
  m_stop_hook_next_id = 0;
296
2.88k
  m_suppress_stop_hooks = false;
297
2.88k
  m_repl_map.clear();
298
2.88k
  Args signal_args;
299
2.88k
  ClearDummySignals(signal_args);
300
2.88k
}
301
302
70
llvm::StringRef Target::GetABIName() const {
303
70
  lldb::ABISP abi_sp;
304
70
  if (m_process_sp)
305
68
    abi_sp = m_process_sp->GetABI();
306
70
  if (!abi_sp)
307
2
    abi_sp = ABI::FindPlugin(ProcessSP(), GetArchitecture());
308
70
  if (abi_sp)
309
70
      return abi_sp->GetPluginName();
310
0
  return {};
311
70
}
312
313
3.46k
BreakpointList &Target::GetBreakpointList(bool internal) {
314
3.46k
  if (internal)
315
26
    return m_internal_breakpoint_list;
316
3.43k
  else
317
3.43k
    return m_breakpoint_list;
318
3.46k
}
319
320
0
const BreakpointList &Target::GetBreakpointList(bool internal) const {
321
0
  if (internal)
322
0
    return m_internal_breakpoint_list;
323
0
  else
324
0
    return m_breakpoint_list;
325
0
}
326
327
1.61k
BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
328
1.61k
  BreakpointSP bp_sp;
329
330
1.61k
  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
331
300
    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
332
1.31k
  else
333
1.31k
    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
334
335
1.61k
  return bp_sp;
336
1.61k
}
337
338
lldb::BreakpointSP
339
1
lldb_private::Target::CreateBreakpointAtUserEntry(Status &error) {
340
1
  ModuleSP main_module_sp = GetExecutableModule();
341
1
  FileSpecList shared_lib_filter;
342
1
  shared_lib_filter.Append(main_module_sp->GetFileSpec());
343
1
  llvm::SetVector<std::string, std::vector<std::string>,
344
1
                  std::unordered_set<std::string>>
345
1
      entryPointNamesSet;
346
3
  for (LanguageType lang_type : Language::GetSupportedLanguages()) {
347
3
    Language *lang = Language::FindPlugin(lang_type);
348
3
    if (!lang) {
349
0
      error.SetErrorString("Language not found\n");
350
0
      return lldb::BreakpointSP();
351
0
    }
352
3
    std::string entryPointName = lang->GetUserEntryPointName().str();
353
3
    if (!entryPointName.empty())
354
3
      entryPointNamesSet.insert(entryPointName);
355
3
  }
356
1
  if (entryPointNamesSet.empty()) {
357
0
    error.SetErrorString("No entry point name found\n");
358
0
    return lldb::BreakpointSP();
359
0
  }
360
1
  BreakpointSP bp_sp = CreateBreakpoint(
361
1
      &shared_lib_filter,
362
1
      /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(),
363
1
      /*func_name_type_mask=*/eFunctionNameTypeFull,
364
1
      /*language=*/eLanguageTypeUnknown,
365
1
      /*offset=*/0,
366
1
      /*skip_prologue=*/eLazyBoolNo,
367
1
      /*internal=*/false,
368
1
      /*hardware=*/false);
369
1
  if (!bp_sp) {
370
0
    error.SetErrorString("Breakpoint creation failed.\n");
371
0
    return lldb::BreakpointSP();
372
0
  }
373
1
  bp_sp->SetOneShot(true);
374
1
  return bp_sp;
375
1
}
376
377
BreakpointSP Target::CreateSourceRegexBreakpoint(
378
    const FileSpecList *containingModules,
379
    const FileSpecList *source_file_spec_list,
380
    const std::unordered_set<std::string> &function_names,
381
    RegularExpression source_regex, bool internal, bool hardware,
382
1.06k
    LazyBool move_to_nearest_code) {
383
1.06k
  SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
384
1.06k
      containingModules, source_file_spec_list));
385
1.06k
  if (move_to_nearest_code == eLazyBoolCalculate)
386
1.06k
    move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : 
eLazyBoolNo0
;
387
1.06k
  BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
388
1.06k
      nullptr, std::move(source_regex), function_names,
389
1.06k
      !static_cast<bool>(move_to_nearest_code)));
390
391
1.06k
  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
392
1.06k
}
393
394
BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
395
                                      const FileSpec &file, uint32_t line_no,
396
                                      uint32_t column, lldb::addr_t offset,
397
                                      LazyBool check_inlines,
398
                                      LazyBool skip_prologue, bool internal,
399
                                      bool hardware,
400
1.15k
                                      LazyBool move_to_nearest_code) {
401
1.15k
  FileSpec remapped_file;
402
1.15k
  std::optional<llvm::StringRef> removed_prefix_opt =
403
1.15k
      GetSourcePathMap().ReverseRemapPath(file, remapped_file);
404
1.15k
  if (!removed_prefix_opt)
405
1.14k
    remapped_file = file;
406
407
1.15k
  if (check_inlines == eLazyBoolCalculate) {
408
1.15k
    const InlineStrategy inline_strategy = GetInlineStrategy();
409
1.15k
    switch (inline_strategy) {
410
0
    case eInlineBreakpointsNever:
411
0
      check_inlines = eLazyBoolNo;
412
0
      break;
413
414
2
    case eInlineBreakpointsHeaders:
415
2
      if (remapped_file.IsSourceImplementationFile())
416
2
        check_inlines = eLazyBoolNo;
417
0
      else
418
0
        check_inlines = eLazyBoolYes;
419
2
      break;
420
421
1.14k
    case eInlineBreakpointsAlways:
422
1.14k
      check_inlines = eLazyBoolYes;
423
1.14k
      break;
424
1.15k
    }
425
1.15k
  }
426
1.15k
  SearchFilterSP filter_sp;
427
1.15k
  if (check_inlines == eLazyBoolNo) {
428
    // Not checking for inlines, we are looking only for matching compile units
429
2
    FileSpecList compile_unit_list;
430
2
    compile_unit_list.Append(remapped_file);
431
2
    filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
432
2
                                                  &compile_unit_list);
433
1.14k
  } else {
434
1.14k
    filter_sp = GetSearchFilterForModuleList(containingModules);
435
1.14k
  }
436
1.15k
  if (skip_prologue == eLazyBoolCalculate)
437
1.14k
    skip_prologue = GetSkipPrologue() ? eLazyBoolYes : 
eLazyBoolNo0
;
438
1.15k
  if (move_to_nearest_code == eLazyBoolCalculate)
439
1.13k
    move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : 
eLazyBoolNo0
;
440
441
1.15k
  SourceLocationSpec location_spec(remapped_file, line_no, column,
442
1.15k
                                   check_inlines,
443
1.15k
                                   !static_cast<bool>(move_to_nearest_code));
444
1.15k
  if (!location_spec)
445
0
    return nullptr;
446
447
1.15k
  BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
448
1.15k
      nullptr, offset, skip_prologue, location_spec, removed_prefix_opt));
449
1.15k
  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
450
1.15k
}
451
452
BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
453
4.12k
                                      bool hardware) {
454
4.12k
  Address so_addr;
455
456
  // Check for any reason we want to move this breakpoint to other address.
457
4.12k
  addr = GetBreakableLoadAddress(addr);
458
459
  // Attempt to resolve our load address if possible, though it is ok if it
460
  // doesn't resolve to section/offset.
461
462
  // Try and resolve as a load address if possible
463
4.12k
  GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
464
4.12k
  if (!so_addr.IsValid()) {
465
    // The address didn't resolve, so just set this as an absolute address
466
7
    so_addr.SetOffset(addr);
467
7
  }
468
4.12k
  BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
469
4.12k
  return bp_sp;
470
4.12k
}
471
472
BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
473
4.34k
                                      bool hardware) {
474
4.34k
  SearchFilterSP filter_sp(
475
4.34k
      new SearchFilterForUnconstrainedSearches(shared_from_this()));
476
4.34k
  BreakpointResolverSP resolver_sp(
477
4.34k
      new BreakpointResolverAddress(nullptr, addr));
478
4.34k
  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
479
4.34k
}
480
481
lldb::BreakpointSP
482
Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
483
                                        const FileSpec &file_spec,
484
0
                                        bool request_hardware) {
485
0
  SearchFilterSP filter_sp(
486
0
      new SearchFilterForUnconstrainedSearches(shared_from_this()));
487
0
  BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(
488
0
      nullptr, file_addr, file_spec));
489
0
  return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
490
0
                          false);
491
0
}
492
493
BreakpointSP Target::CreateBreakpoint(
494
    const FileSpecList *containingModules,
495
    const FileSpecList *containingSourceFiles, const char *func_name,
496
    FunctionNameType func_name_type_mask, LanguageType language,
497
4.73k
    lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
498
4.73k
  BreakpointSP bp_sp;
499
4.73k
  if (func_name) {
500
4.73k
    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
501
4.73k
        containingModules, containingSourceFiles));
502
503
4.73k
    if (skip_prologue == eLazyBoolCalculate)
504
448
      skip_prologue = GetSkipPrologue() ? 
eLazyBoolYes442
:
eLazyBoolNo6
;
505
4.73k
    if (language == lldb::eLanguageTypeUnknown)
506
4.71k
      language = GetLanguage();
507
508
4.73k
    BreakpointResolverSP resolver_sp(new BreakpointResolverName(
509
4.73k
        nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
510
4.73k
        offset, skip_prologue));
511
4.73k
    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
512
4.73k
  }
513
4.73k
  return bp_sp;
514
4.73k
}
515
516
lldb::BreakpointSP
517
Target::CreateBreakpoint(const FileSpecList *containingModules,
518
                         const FileSpecList *containingSourceFiles,
519
                         const std::vector<std::string> &func_names,
520
                         FunctionNameType func_name_type_mask,
521
                         LanguageType language, lldb::addr_t offset,
522
163
                         LazyBool skip_prologue, bool internal, bool hardware) {
523
163
  BreakpointSP bp_sp;
524
163
  size_t num_names = func_names.size();
525
163
  if (num_names > 0) {
526
163
    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
527
163
        containingModules, containingSourceFiles));
528
529
163
    if (skip_prologue == eLazyBoolCalculate)
530
161
      skip_prologue = GetSkipPrologue() ? eLazyBoolYes : 
eLazyBoolNo0
;
531
163
    if (language == lldb::eLanguageTypeUnknown)
532
162
      language = GetLanguage();
533
534
163
    BreakpointResolverSP resolver_sp(
535
163
        new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
536
163
                                   language, offset, skip_prologue));
537
163
    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
538
163
  }
539
163
  return bp_sp;
540
163
}
541
542
BreakpointSP
543
Target::CreateBreakpoint(const FileSpecList *containingModules,
544
                         const FileSpecList *containingSourceFiles,
545
                         const char *func_names[], size_t num_names,
546
                         FunctionNameType func_name_type_mask,
547
                         LanguageType language, lldb::addr_t offset,
548
1.09k
                         LazyBool skip_prologue, bool internal, bool hardware) {
549
1.09k
  BreakpointSP bp_sp;
550
1.09k
  if (num_names > 0) {
551
1.09k
    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
552
1.09k
        containingModules, containingSourceFiles));
553
554
1.09k
    if (skip_prologue == eLazyBoolCalculate) {
555
0
      if (offset == 0)
556
0
        skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
557
0
      else
558
0
        skip_prologue = eLazyBoolNo;
559
0
    }
560
1.09k
    if (language == lldb::eLanguageTypeUnknown)
561
1.09k
      language = GetLanguage();
562
563
1.09k
    BreakpointResolverSP resolver_sp(new BreakpointResolverName(
564
1.09k
        nullptr, func_names, num_names, func_name_type_mask, language, offset,
565
1.09k
        skip_prologue));
566
1.09k
    resolver_sp->SetOffset(offset);
567
1.09k
    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
568
1.09k
  }
569
1.09k
  return bp_sp;
570
1.09k
}
571
572
SearchFilterSP
573
0
Target::GetSearchFilterForModule(const FileSpec *containingModule) {
574
0
  SearchFilterSP filter_sp;
575
0
  if (containingModule != nullptr) {
576
    // TODO: We should look into sharing module based search filters
577
    // across many breakpoints like we do for the simple target based one
578
0
    filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
579
0
                                                       *containingModule);
580
0
  } else {
581
0
    if (!m_search_filter_sp)
582
0
      m_search_filter_sp =
583
0
          std::make_shared<SearchFilterForUnconstrainedSearches>(
584
0
              shared_from_this());
585
0
    filter_sp = m_search_filter_sp;
586
0
  }
587
0
  return filter_sp;
588
0
}
589
590
SearchFilterSP
591
9.15k
Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
592
9.15k
  SearchFilterSP filter_sp;
593
9.15k
  if (containingModules && 
containingModules->GetSize() != 08.40k
) {
594
    // TODO: We should look into sharing module based search filters
595
    // across many breakpoints like we do for the simple target based one
596
7.48k
    filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
597
7.48k
                                                           *containingModules);
598
7.48k
  } else {
599
1.66k
    if (!m_search_filter_sp)
600
1.02k
      m_search_filter_sp =
601
1.02k
          std::make_shared<SearchFilterForUnconstrainedSearches>(
602
1.02k
              shared_from_this());
603
1.66k
    filter_sp = m_search_filter_sp;
604
1.66k
  }
605
9.15k
  return filter_sp;
606
9.15k
}
607
608
SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
609
    const FileSpecList *containingModules,
610
7.06k
    const FileSpecList *containingSourceFiles) {
611
7.06k
  if (containingSourceFiles == nullptr || 
containingSourceFiles->GetSize() == 01.30k
)
612
5.98k
    return GetSearchFilterForModuleList(containingModules);
613
614
1.08k
  SearchFilterSP filter_sp;
615
1.08k
  if (containingModules == nullptr) {
616
    // We could make a special "CU List only SearchFilter".  Better yet was if
617
    // these could be composable, but that will take a little reworking.
618
619
4
    filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
620
4
        shared_from_this(), FileSpecList(), *containingSourceFiles);
621
1.08k
  } else {
622
1.08k
    filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
623
1.08k
        shared_from_this(), *containingModules, *containingSourceFiles);
624
1.08k
  }
625
1.08k
  return filter_sp;
626
7.06k
}
627
628
BreakpointSP Target::CreateFuncRegexBreakpoint(
629
    const FileSpecList *containingModules,
630
    const FileSpecList *containingSourceFiles, RegularExpression func_regex,
631
    lldb::LanguageType requested_language, LazyBool skip_prologue,
632
15
    bool internal, bool hardware) {
633
15
  SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
634
15
      containingModules, containingSourceFiles));
635
15
  bool skip = (skip_prologue == eLazyBoolCalculate)
636
15
                  ? GetSkipPrologue()
637
15
                  : 
static_cast<bool>(skip_prologue)0
;
638
15
  BreakpointResolverSP resolver_sp(new BreakpointResolverName(
639
15
      nullptr, std::move(func_regex), requested_language, 0, skip));
640
641
15
  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
642
15
}
643
644
lldb::BreakpointSP
645
Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
646
                                  bool catch_bp, bool throw_bp, bool internal,
647
10
                                  Args *additional_args, Status *error) {
648
10
  BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
649
10
      *this, language, catch_bp, throw_bp, internal);
650
10
  if (exc_bkpt_sp && additional_args) {
651
0
    BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
652
0
    if (precondition_sp && additional_args) {
653
0
      if (error)
654
0
        *error = precondition_sp->ConfigurePrecondition(*additional_args);
655
0
      else
656
0
        precondition_sp->ConfigurePrecondition(*additional_args);
657
0
    }
658
0
  }
659
10
  return exc_bkpt_sp;
660
10
}
661
662
lldb::BreakpointSP Target::CreateScriptedBreakpoint(
663
    const llvm::StringRef class_name, const FileSpecList *containingModules,
664
    const FileSpecList *containingSourceFiles, bool internal,
665
    bool request_hardware, StructuredData::ObjectSP extra_args_sp,
666
19
    Status *creation_error) {
667
19
  SearchFilterSP filter_sp;
668
669
19
  lldb::SearchDepth depth = lldb::eSearchDepthTarget;
670
19
  bool has_files =
671
19
      containingSourceFiles && containingSourceFiles->GetSize() > 0;
672
19
  bool has_modules = containingModules && containingModules->GetSize() > 0;
673
674
19
  if (has_files && 
has_modules5
) {
675
1
    filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
676
1
                                                  containingSourceFiles);
677
18
  } else if (has_files) {
678
4
    filter_sp =
679
4
        GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
680
14
  } else if (has_modules) {
681
9
    filter_sp = GetSearchFilterForModuleList(containingModules);
682
9
  } else {
683
5
    filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
684
5
        shared_from_this());
685
5
  }
686
687
19
  BreakpointResolverSP resolver_sp(new BreakpointResolverScripted(
688
19
      nullptr, class_name, depth, StructuredDataImpl(extra_args_sp)));
689
19
  return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
690
19
}
691
692
BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
693
                                      BreakpointResolverSP &resolver_sp,
694
                                      bool internal, bool request_hardware,
695
14.5k
                                      bool resolve_indirect_symbols) {
696
14.5k
  BreakpointSP bp_sp;
697
14.5k
  if (filter_sp && resolver_sp) {
698
14.5k
    const bool hardware = request_hardware || 
GetRequireHardwareBreakpoints()14.5k
;
699
14.5k
    bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
700
14.5k
                               resolve_indirect_symbols));
701
14.5k
    resolver_sp->SetBreakpoint(bp_sp);
702
14.5k
    AddBreakpoint(bp_sp, internal);
703
14.5k
  }
704
14.5k
  return bp_sp;
705
14.5k
}
706
707
14.6k
void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
708
14.6k
  if (!bp_sp)
709
0
    return;
710
14.6k
  if (internal)
711
11.6k
    m_internal_breakpoint_list.Add(bp_sp, false);
712
2.92k
  else
713
2.92k
    m_breakpoint_list.Add(bp_sp, true);
714
715
14.6k
  Log *log = GetLog(LLDBLog::Breakpoints);
716
14.6k
  if (log) {
717
0
    StreamString s;
718
0
    bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
719
0
    LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
720
0
              __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
721
0
  }
722
723
14.6k
  bp_sp->ResolveBreakpoint();
724
725
14.6k
  if (!internal) {
726
2.92k
    m_last_created_breakpoint = bp_sp;
727
2.92k
  }
728
14.6k
}
729
730
void Target::AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name,
731
0
                                 Status &error) {
732
0
  BreakpointSP bp_sp =
733
0
      m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
734
0
  if (!bp_sp) {
735
0
    StreamString s;
736
0
    id.GetDescription(&s, eDescriptionLevelBrief);
737
0
    error.SetErrorStringWithFormat("Could not find breakpoint %s", s.GetData());
738
0
    return;
739
0
  }
740
0
  AddNameToBreakpoint(bp_sp, name, error);
741
0
}
742
743
void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, llvm::StringRef name,
744
43
                                 Status &error) {
745
43
  if (!bp_sp)
746
0
    return;
747
748
43
  BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
749
43
  if (!bp_name)
750
5
    return;
751
752
38
  bp_name->ConfigureBreakpoint(bp_sp);
753
38
  bp_sp->AddName(name);
754
38
}
755
756
1
void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) {
757
1
  m_breakpoint_names.insert(
758
1
      std::make_pair(bp_name->GetName(), std::move(bp_name)));
759
1
}
760
761
BreakpointName *Target::FindBreakpointName(ConstString name, bool can_create,
762
117
                                           Status &error) {
763
117
  BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
764
117
  if (!error.Success())
765
10
    return nullptr;
766
767
107
  BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
768
107
  if (iter != m_breakpoint_names.end()) {
769
69
    return iter->second.get();
770
69
  }
771
772
38
  if (!can_create) {
773
0
    error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
774
0
                                   "can_create is false.",
775
0
                                   name.AsCString());
776
0
    return nullptr;
777
0
  }
778
779
38
  return m_breakpoint_names
780
38
      .insert(std::make_pair(name, std::make_unique<BreakpointName>(name)))
781
38
      .first->second.get();
782
38
}
783
784
3
void Target::DeleteBreakpointName(ConstString name) {
785
3
  BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
786
787
3
  if (iter != m_breakpoint_names.end()) {
788
2
    const char *name_cstr = name.AsCString();
789
2
    m_breakpoint_names.erase(iter);
790
2
    for (auto bp_sp : m_breakpoint_list.Breakpoints())
791
1
      bp_sp->RemoveName(name_cstr);
792
2
  }
793
3
}
794
795
void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
796
1
                                      ConstString name) {
797
1
  bp_sp->RemoveName(name.AsCString());
798
1
}
799
800
void Target::ConfigureBreakpointName(
801
    BreakpointName &bp_name, const BreakpointOptions &new_options,
802
3
    const BreakpointName::Permissions &new_permissions) {
803
3
  bp_name.GetOptions().CopyOverSetOptions(new_options);
804
3
  bp_name.GetPermissions().MergeInto(new_permissions);
805
3
  ApplyNameToBreakpoints(bp_name);
806
3
}
807
808
13
void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
809
13
  llvm::Expected<std::vector<BreakpointSP>> expected_vector =
810
13
      m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString());
811
812
13
  if (!expected_vector) {
813
0
    LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}",
814
0
             llvm::toString(expected_vector.takeError()));
815
0
    return;
816
0
  }
817
818
13
  for (auto bp_sp : *expected_vector)
819
1
    bp_name.ConfigureBreakpoint(bp_sp);
820
13
}
821
822
7
void Target::GetBreakpointNames(std::vector<std::string> &names) {
823
7
  names.clear();
824
9
  for (const auto& bp_name_entry : m_breakpoint_names) {
825
9
    names.push_back(bp_name_entry.first.AsCString());
826
9
  }
827
7
  llvm::sort(names);
828
7
}
829
830
460k
bool Target::ProcessIsValid() {
831
460k
  return (m_process_sp && 
m_process_sp->IsAlive()458k
);
832
460k
}
833
834
78
static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
835
78
  std::optional<uint32_t> num_supported_hardware_watchpoints =
836
78
      target->GetProcessSP()->GetWatchpointSlotCount();
837
838
  // If unable to determine the # of watchpoints available,
839
  // assume they are supported.
840
78
  if (!num_supported_hardware_watchpoints)
841
1
    return true;
842
843
77
  if (num_supported_hardware_watchpoints == 0) {
844
0
    error.SetErrorStringWithFormat(
845
0
        "Target supports (%u) hardware watchpoint slots.\n",
846
0
        *num_supported_hardware_watchpoints);
847
0
    return false;
848
0
  }
849
77
  return true;
850
77
}
851
852
// See also Watchpoint::SetWatchpointType(uint32_t type) and the
853
// OptionGroupWatchpoint::WatchType enum type.
854
WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
855
                                      const CompilerType *type, uint32_t kind,
856
78
                                      Status &error) {
857
78
  Log *log = GetLog(LLDBLog::Watchpoints);
858
78
  LLDB_LOGF(log,
859
78
            "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
860
78
            " type = %u)\n",
861
78
            __FUNCTION__, addr, (uint64_t)size, kind);
862
863
78
  WatchpointSP wp_sp;
864
78
  if (!ProcessIsValid()) {
865
0
    error.SetErrorString("process is not alive");
866
0
    return wp_sp;
867
0
  }
868
869
78
  if (addr == LLDB_INVALID_ADDRESS || size == 0) {
870
0
    if (size == 0)
871
0
      error.SetErrorString("cannot set a watchpoint with watch_size of 0");
872
0
    else
873
0
      error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
874
0
    return wp_sp;
875
0
  }
876
877
78
  if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
878
0
    error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
879
0
  }
880
881
78
  if (!CheckIfWatchpointsSupported(this, error))
882
0
    return wp_sp;
883
884
  // Currently we only support one watchpoint per address, with total number of
885
  // watchpoints limited by the hardware which the inferior is running on.
886
887
  // Grab the list mutex while doing operations.
888
78
  const bool notify = false; // Don't notify about all the state changes we do
889
                             // on creating the watchpoint.
890
891
  // Mask off ignored bits from watchpoint address.
892
78
  if (ABISP abi = m_process_sp->GetABI())
893
78
    addr = abi->FixDataAddress(addr);
894
895
78
  std::unique_lock<std::recursive_mutex> lock;
896
78
  this->GetWatchpointList().GetListMutex(lock);
897
78
  WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
898
78
  if (matched_sp) {
899
0
    size_t old_size = matched_sp->GetByteSize();
900
0
    uint32_t old_type =
901
0
        (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
902
0
        (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) |
903
0
        (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0);
904
    // Return the existing watchpoint if both size and type match.
905
0
    if (size == old_size && kind == old_type) {
906
0
      wp_sp = matched_sp;
907
0
      wp_sp->SetEnabled(false, notify);
908
0
    } else {
909
      // Nil the matched watchpoint; we will be creating a new one.
910
0
      m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
911
0
      m_watchpoint_list.Remove(matched_sp->GetID(), true);
912
0
    }
913
0
  }
914
915
78
  if (!wp_sp) {
916
78
    wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
917
78
    wp_sp->SetWatchpointType(kind, notify);
918
78
    m_watchpoint_list.Add(wp_sp, true);
919
78
  }
920
921
78
  error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
922
78
  LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
923
78
            __FUNCTION__, error.Success() ? "succeeded" : "failed",
924
78
            wp_sp->GetID());
925
926
78
  if (error.Fail()) {
927
    // Enabling the watchpoint on the device side failed. Remove the said
928
    // watchpoint from the list maintained by the target instance.
929
1
    m_watchpoint_list.Remove(wp_sp->GetID(), true);
930
    // See if we could provide more helpful error message.
931
1
    if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
932
1
      error.SetErrorStringWithFormat(
933
1
          "watch size of %" PRIu64 " is not supported", (uint64_t)size);
934
935
1
    wp_sp.reset();
936
1
  } else
937
77
    m_last_created_watchpoint = wp_sp;
938
78
  return wp_sp;
939
78
}
940
941
12
void Target::RemoveAllowedBreakpoints() {
942
12
  Log *log = GetLog(LLDBLog::Breakpoints);
943
12
  LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
944
945
12
  m_breakpoint_list.RemoveAllowed(true);
946
947
12
  m_last_created_breakpoint.reset();
948
12
}
949
950
23
void Target::RemoveAllBreakpoints(bool internal_also) {
951
23
  Log *log = GetLog(LLDBLog::Breakpoints);
952
23
  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
953
23
            internal_also ? "yes" : "no");
954
955
23
  m_breakpoint_list.RemoveAll(true);
956
23
  if (internal_also)
957
23
    m_internal_breakpoint_list.RemoveAll(false);
958
959
23
  m_last_created_breakpoint.reset();
960
23
}
961
962
0
void Target::DisableAllBreakpoints(bool internal_also) {
963
0
  Log *log = GetLog(LLDBLog::Breakpoints);
964
0
  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
965
0
            internal_also ? "yes" : "no");
966
967
0
  m_breakpoint_list.SetEnabledAll(false);
968
0
  if (internal_also)
969
0
    m_internal_breakpoint_list.SetEnabledAll(false);
970
0
}
971
972
6
void Target::DisableAllowedBreakpoints() {
973
6
  Log *log = GetLog(LLDBLog::Breakpoints);
974
6
  LLDB_LOGF(log, "Target::%s", __FUNCTION__);
975
976
6
  m_breakpoint_list.SetEnabledAllowed(false);
977
6
}
978
979
0
void Target::EnableAllBreakpoints(bool internal_also) {
980
0
  Log *log = GetLog(LLDBLog::Breakpoints);
981
0
  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
982
0
            internal_also ? "yes" : "no");
983
984
0
  m_breakpoint_list.SetEnabledAll(true);
985
0
  if (internal_also)
986
0
    m_internal_breakpoint_list.SetEnabledAll(true);
987
0
}
988
989
0
void Target::EnableAllowedBreakpoints() {
990
0
  Log *log = GetLog(LLDBLog::Breakpoints);
991
0
  LLDB_LOGF(log, "Target::%s", __FUNCTION__);
992
993
0
  m_breakpoint_list.SetEnabledAllowed(true);
994
0
}
995
996
12.2k
bool Target::RemoveBreakpointByID(break_id_t break_id) {
997
12.2k
  Log *log = GetLog(LLDBLog::Breakpoints);
998
12.2k
  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
999
12.2k
            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1000
1001
12.2k
  if (DisableBreakpointByID(break_id)) {
1002
8.69k
    if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1003
8.59k
      m_internal_breakpoint_list.Remove(break_id, false);
1004
95
    else {
1005
95
      if (m_last_created_breakpoint) {
1006
95
        if (m_last_created_breakpoint->GetID() == break_id)
1007
89
          m_last_created_breakpoint.reset();
1008
95
      }
1009
95
      m_breakpoint_list.Remove(break_id, true);
1010
95
    }
1011
8.69k
    return true;
1012
8.69k
  }
1013
3.51k
  return false;
1014
12.2k
}
1015
1016
12.2k
bool Target::DisableBreakpointByID(break_id_t break_id) {
1017
12.2k
  Log *log = GetLog(LLDBLog::Breakpoints);
1018
12.2k
  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1019
12.2k
            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1020
1021
12.2k
  BreakpointSP bp_sp;
1022
1023
12.2k
  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1024
8.59k
    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1025
3.60k
  else
1026
3.60k
    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1027
12.2k
  if (bp_sp) {
1028
8.69k
    bp_sp->SetEnabled(false);
1029
8.69k
    return true;
1030
8.69k
  }
1031
3.51k
  return false;
1032
12.2k
}
1033
1034
0
bool Target::EnableBreakpointByID(break_id_t break_id) {
1035
0
  Log *log = GetLog(LLDBLog::Breakpoints);
1036
0
  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1037
0
            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1038
1039
0
  BreakpointSP bp_sp;
1040
1041
0
  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1042
0
    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1043
0
  else
1044
0
    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1045
1046
0
  if (bp_sp) {
1047
0
    bp_sp->SetEnabled(true);
1048
0
    return true;
1049
0
  }
1050
0
  return false;
1051
0
}
1052
1053
2.48k
void Target::ResetBreakpointHitCounts() {
1054
2.48k
  GetBreakpointList().ResetHitCounts();
1055
2.48k
}
1056
1057
Status Target::SerializeBreakpointsToFile(const FileSpec &file,
1058
                                          const BreakpointIDList &bp_ids,
1059
12
                                          bool append) {
1060
12
  Status error;
1061
1062
12
  if (!file) {
1063
0
    error.SetErrorString("Invalid FileSpec.");
1064
0
    return error;
1065
0
  }
1066
1067
12
  std::string path(file.GetPath());
1068
12
  StructuredData::ObjectSP input_data_sp;
1069
1070
12
  StructuredData::ArraySP break_store_sp;
1071
12
  StructuredData::Array *break_store_ptr = nullptr;
1072
1073
12
  if (append) {
1074
1
    input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1075
1
    if (error.Success()) {
1076
1
      break_store_ptr = input_data_sp->GetAsArray();
1077
1
      if (!break_store_ptr) {
1078
0
        error.SetErrorStringWithFormat(
1079
0
            "Tried to append to invalid input file %s", path.c_str());
1080
0
        return error;
1081
0
      }
1082
1
    }
1083
1
  }
1084
1085
12
  if (!break_store_ptr) {
1086
11
    break_store_sp = std::make_shared<StructuredData::Array>();
1087
11
    break_store_ptr = break_store_sp.get();
1088
11
  }
1089
1090
12
  StreamFile out_file(path.c_str(),
1091
12
                      File::eOpenOptionTruncate | File::eOpenOptionWriteOnly |
1092
12
                          File::eOpenOptionCanCreate |
1093
12
                          File::eOpenOptionCloseOnExec,
1094
12
                      lldb::eFilePermissionsFileDefault);
1095
12
  if (!out_file.GetFile().IsValid()) {
1096
0
    error.SetErrorStringWithFormat("Unable to open output file: %s.",
1097
0
                                   path.c_str());
1098
0
    return error;
1099
0
  }
1100
1101
12
  std::unique_lock<std::recursive_mutex> lock;
1102
12
  GetBreakpointList().GetListMutex(lock);
1103
1104
12
  if (bp_ids.GetSize() == 0) {
1105
2
    const BreakpointList &breakpoints = GetBreakpointList();
1106
1107
2
    size_t num_breakpoints = breakpoints.GetSize();
1108
4
    for (size_t i = 0; i < num_breakpoints; 
i++2
) {
1109
2
      Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1110
2
      StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1111
      // If a breakpoint can't serialize it, just ignore it for now:
1112
2
      if (bkpt_save_sp)
1113
2
        break_store_ptr->AddItem(bkpt_save_sp);
1114
2
    }
1115
10
  } else {
1116
1117
10
    std::unordered_set<lldb::break_id_t> processed_bkpts;
1118
10
    const size_t count = bp_ids.GetSize();
1119
30
    for (size_t i = 0; i < count; 
++i20
) {
1120
20
      BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1121
20
      lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1122
1123
20
      if (bp_id != LLDB_INVALID_BREAK_ID) {
1124
        // Only do each breakpoint once:
1125
20
        std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1126
20
            insert_result = processed_bkpts.insert(bp_id);
1127
20
        if (!insert_result.second)
1128
0
          continue;
1129
1130
20
        Breakpoint *bp = GetBreakpointByID(bp_id).get();
1131
20
        StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1132
        // If the user explicitly asked to serialize a breakpoint, and we
1133
        // can't, then raise an error:
1134
20
        if (!bkpt_save_sp) {
1135
0
          error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1136
0
                                         bp_id);
1137
0
          return error;
1138
0
        }
1139
20
        break_store_ptr->AddItem(bkpt_save_sp);
1140
20
      }
1141
20
    }
1142
10
  }
1143
1144
12
  break_store_ptr->Dump(out_file, false);
1145
12
  out_file.PutChar('\n');
1146
12
  return error;
1147
12
}
1148
1149
Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1150
0
                                         BreakpointIDList &new_bps) {
1151
0
  std::vector<std::string> no_names;
1152
0
  return CreateBreakpointsFromFile(file, no_names, new_bps);
1153
0
}
1154
1155
Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1156
                                         std::vector<std::string> &names,
1157
11
                                         BreakpointIDList &new_bps) {
1158
11
  std::unique_lock<std::recursive_mutex> lock;
1159
11
  GetBreakpointList().GetListMutex(lock);
1160
1161
11
  Status error;
1162
11
  StructuredData::ObjectSP input_data_sp =
1163
11
      StructuredData::ParseJSONFromFile(file, error);
1164
11
  if (!error.Success()) {
1165
0
    return error;
1166
11
  } else if (!input_data_sp || !input_data_sp->IsValid()) {
1167
0
    error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1168
0
                                   file.GetPath().c_str());
1169
0
    return error;
1170
0
  }
1171
1172
11
  StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1173
11
  if (!bkpt_array) {
1174
0
    error.SetErrorStringWithFormat(
1175
0
        "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1176
0
    return error;
1177
0
  }
1178
1179
11
  size_t num_bkpts = bkpt_array->GetSize();
1180
11
  size_t num_names = names.size();
1181
1182
31
  for (size_t i = 0; i < num_bkpts; 
i++20
) {
1183
20
    StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1184
    // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1185
20
    StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1186
20
    if (!bkpt_dict) {
1187
0
      error.SetErrorStringWithFormat(
1188
0
          "Invalid breakpoint data for element %zu from input file: %s.", i,
1189
0
          file.GetPath().c_str());
1190
0
      return error;
1191
0
    }
1192
20
    StructuredData::ObjectSP bkpt_data_sp =
1193
20
        bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1194
20
    if (num_names &&
1195
20
        
!Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names)2
)
1196
1
      continue;
1197
1198
19
    BreakpointSP bkpt_sp = Breakpoint::CreateFromStructuredData(
1199
19
        shared_from_this(), bkpt_data_sp, error);
1200
19
    if (!error.Success()) {
1201
0
      error.SetErrorStringWithFormat(
1202
0
          "Error restoring breakpoint %zu from %s: %s.", i,
1203
0
          file.GetPath().c_str(), error.AsCString());
1204
0
      return error;
1205
0
    }
1206
19
    new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1207
19
  }
1208
11
  return error;
1209
11
}
1210
1211
// The flag 'end_to_end', default to true, signifies that the operation is
1212
// performed end to end, for both the debugger and the debuggee.
1213
1214
// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1215
// to end operations.
1216
16
bool Target::RemoveAllWatchpoints(bool end_to_end) {
1217
16
  Log *log = GetLog(LLDBLog::Watchpoints);
1218
16
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1219
1220
16
  if (!end_to_end) {
1221
0
    m_watchpoint_list.RemoveAll(true);
1222
0
    return true;
1223
0
  }
1224
1225
  // Otherwise, it's an end to end operation.
1226
1227
16
  if (!ProcessIsValid())
1228
0
    return false;
1229
1230
16
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1231
16
    if (!wp_sp)
1232
0
      return false;
1233
1234
16
    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1235
16
    if (rc.Fail())
1236
0
      return false;
1237
16
  }
1238
16
  m_watchpoint_list.RemoveAll(true);
1239
16
  m_last_created_watchpoint.reset();
1240
16
  return true; // Success!
1241
16
}
1242
1243
// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1244
// to end operations.
1245
2.48k
bool Target::DisableAllWatchpoints(bool end_to_end) {
1246
2.48k
  Log *log = GetLog(LLDBLog::Watchpoints);
1247
2.48k
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1248
1249
2.48k
  if (!end_to_end) {
1250
2.48k
    m_watchpoint_list.SetEnabledAll(false);
1251
2.48k
    return true;
1252
2.48k
  }
1253
1254
  // Otherwise, it's an end to end operation.
1255
1256
2
  if (!ProcessIsValid())
1257
0
    return false;
1258
1259
2
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1260
2
    if (!wp_sp)
1261
0
      return false;
1262
1263
2
    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1264
2
    if (rc.Fail())
1265
0
      return false;
1266
2
  }
1267
2
  return true; // Success!
1268
2
}
1269
1270
// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1271
// to end operations.
1272
1
bool Target::EnableAllWatchpoints(bool end_to_end) {
1273
1
  Log *log = GetLog(LLDBLog::Watchpoints);
1274
1
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1275
1276
1
  if (!end_to_end) {
1277
0
    m_watchpoint_list.SetEnabledAll(true);
1278
0
    return true;
1279
0
  }
1280
1281
  // Otherwise, it's an end to end operation.
1282
1283
1
  if (!ProcessIsValid())
1284
0
    return false;
1285
1286
1
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1287
1
    if (!wp_sp)
1288
0
      return false;
1289
1290
1
    Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1291
1
    if (rc.Fail())
1292
0
      return false;
1293
1
  }
1294
1
  return true; // Success!
1295
1
}
1296
1297
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1298
2.48k
bool Target::ClearAllWatchpointHitCounts() {
1299
2.48k
  Log *log = GetLog(LLDBLog::Watchpoints);
1300
2.48k
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1301
1302
2.48k
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1303
60
    if (!wp_sp)
1304
0
      return false;
1305
1306
60
    wp_sp->ResetHitCount();
1307
60
  }
1308
2.48k
  return true; // Success!
1309
2.48k
}
1310
1311
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1312
2.48k
bool Target::ClearAllWatchpointHistoricValues() {
1313
2.48k
  Log *log = GetLog(LLDBLog::Watchpoints);
1314
2.48k
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1315
1316
2.48k
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1317
60
    if (!wp_sp)
1318
0
      return false;
1319
1320
60
    wp_sp->ResetHistoricValues();
1321
60
  }
1322
2.48k
  return true; // Success!
1323
2.48k
}
1324
1325
// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1326
// these operations.
1327
1
bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1328
1
  Log *log = GetLog(LLDBLog::Watchpoints);
1329
1
  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1330
1331
1
  if (!ProcessIsValid())
1332
0
    return false;
1333
1334
1
  for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1335
1
    if (!wp_sp)
1336
0
      return false;
1337
1338
1
    wp_sp->SetIgnoreCount(ignore_count);
1339
1
  }
1340
1
  return true; // Success!
1341
1
}
1342
1343
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1344
2
bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1345
2
  Log *log = GetLog(LLDBLog::Watchpoints);
1346
2
  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1347
1348
2
  if (!ProcessIsValid())
1349
0
    return false;
1350
1351
2
  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1352
2
  if (wp_sp) {
1353
2
    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1354
2
    if (rc.Success())
1355
2
      return true;
1356
1357
    // Else, fallthrough.
1358
2
  }
1359
0
  return false;
1360
2
}
1361
1362
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1363
0
bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1364
0
  Log *log = GetLog(LLDBLog::Watchpoints);
1365
0
  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1366
1367
0
  if (!ProcessIsValid())
1368
0
    return false;
1369
1370
0
  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1371
0
  if (wp_sp) {
1372
0
    Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1373
0
    if (rc.Success())
1374
0
      return true;
1375
1376
    // Else, fallthrough.
1377
0
  }
1378
0
  return false;
1379
0
}
1380
1381
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1382
1
bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1383
1
  Log *log = GetLog(LLDBLog::Watchpoints);
1384
1
  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1385
1386
1
  WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1387
1
  if (watch_to_remove_sp == m_last_created_watchpoint)
1388
1
    m_last_created_watchpoint.reset();
1389
1390
1
  if (DisableWatchpointByID(watch_id)) {
1391
1
    m_watchpoint_list.Remove(watch_id, true);
1392
1
    return true;
1393
1
  }
1394
0
  return false;
1395
1
}
1396
1397
// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1398
bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1399
0
                                  uint32_t ignore_count) {
1400
0
  Log *log = GetLog(LLDBLog::Watchpoints);
1401
0
  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1402
1403
0
  if (!ProcessIsValid())
1404
0
    return false;
1405
1406
0
  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1407
0
  if (wp_sp) {
1408
0
    wp_sp->SetIgnoreCount(ignore_count);
1409
0
    return true;
1410
0
  }
1411
0
  return false;
1412
0
}
1413
1414
57.6k
ModuleSP Target::GetExecutableModule() {
1415
  // search for the first executable in the module list
1416
58.2k
  for (size_t i = 0; i < m_images.GetSize(); 
++i643
) {
1417
37.0k
    ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1418
37.0k
    lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1419
37.0k
    if (obj == nullptr)
1420
0
      continue;
1421
37.0k
    if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1422
36.4k
      return module_sp;
1423
37.0k
  }
1424
  // as fall back return the first module loaded
1425
21.2k
  return m_images.GetModuleAtIndex(0);
1426
57.6k
}
1427
1428
48.5k
Module *Target::GetExecutableModulePointer() {
1429
48.5k
  return GetExecutableModule().get();
1430
48.5k
}
1431
1432
static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1433
234k
                                           Target *target) {
1434
234k
  Status error;
1435
234k
  StreamString feedback_stream;
1436
234k
  if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error,
1437
234k
                                                             feedback_stream)) {
1438
1.00k
    if (error.AsCString())
1439
0
      target->GetDebugger().GetErrorStream().Printf(
1440
0
          "unable to load scripting data for module %s - error reported was "
1441
0
          "%s\n",
1442
0
          module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1443
0
          error.AsCString());
1444
1.00k
  }
1445
234k
  if (feedback_stream.GetSize())
1446
0
    target->GetDebugger().GetErrorStream().Printf("%s\n",
1447
0
                                                  feedback_stream.GetData());
1448
234k
}
1449
1450
5.44k
void Target::ClearModules(bool delete_locations) {
1451
5.44k
  ModulesDidUnload(m_images, delete_locations);
1452
5.44k
  m_section_load_history.Clear();
1453
5.44k
  m_images.Clear();
1454
5.44k
  m_scratch_type_system_map.Clear();
1455
5.44k
}
1456
1457
3
void Target::DidExec() {
1458
  // When a process exec's we need to know about it so we can do some cleanup.
1459
3
  m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1460
3
  m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1461
3
}
1462
1463
void Target::SetExecutableModule(ModuleSP &executable_sp,
1464
2.55k
                                 LoadDependentFiles load_dependent_files) {
1465
2.55k
  Log *log = GetLog(LLDBLog::Target);
1466
2.55k
  ClearModules(false);
1467
1468
2.55k
  if (executable_sp) {
1469
2.55k
    ElapsedTime elapsed(m_stats.GetCreateTime());
1470
2.55k
    LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1471
2.55k
                       executable_sp->GetFileSpec().GetPath().c_str());
1472
1473
2.55k
    const bool notify = true;
1474
2.55k
    m_images.Append(executable_sp,
1475
2.55k
                    notify); // The first image is our executable file
1476
1477
    // If we haven't set an architecture yet, reset our architecture based on
1478
    // what we found in the executable module.
1479
2.55k
    if (!m_arch.GetSpec().IsValid()) {
1480
2
      m_arch = executable_sp->GetArchitecture();
1481
2
      LLDB_LOG(log,
1482
2
               "Target::SetExecutableModule setting architecture to {0} ({1}) "
1483
2
               "based on executable file",
1484
2
               m_arch.GetSpec().GetArchitectureName(),
1485
2
               m_arch.GetSpec().GetTriple().getTriple());
1486
2
    }
1487
1488
2.55k
    FileSpecList dependent_files;
1489
2.55k
    ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1490
2.55k
    bool load_dependents = true;
1491
2.55k
    switch (load_dependent_files) {
1492
855
    case eLoadDependentsDefault:
1493
855
      load_dependents = executable_sp->IsExecutable();
1494
855
      break;
1495
1.64k
    case eLoadDependentsYes:
1496
1.64k
      load_dependents = true;
1497
1.64k
      break;
1498
59
    case eLoadDependentsNo:
1499
59
      load_dependents = false;
1500
59
      break;
1501
2.55k
    }
1502
1503
2.55k
    if (executable_objfile && load_dependents) {
1504
2.42k
      ModuleList added_modules;
1505
2.42k
      executable_objfile->GetDependentModules(dependent_files);
1506
118k
      for (uint32_t i = 0; i < dependent_files.GetSize(); 
i++115k
) {
1507
115k
        FileSpec dependent_file_spec(dependent_files.GetFileSpecAtIndex(i));
1508
115k
        FileSpec platform_dependent_file_spec;
1509
115k
        if (m_platform_sp)
1510
115k
          m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1511
115k
                                         platform_dependent_file_spec);
1512
0
        else
1513
0
          platform_dependent_file_spec = dependent_file_spec;
1514
1515
115k
        ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1516
115k
        ModuleSP image_module_sp(
1517
115k
            GetOrCreateModule(module_spec, false /* notify */));
1518
115k
        if (image_module_sp) {
1519
115k
          added_modules.AppendIfNeeded(image_module_sp, false);
1520
115k
          ObjectFile *objfile = image_module_sp->GetObjectFile();
1521
115k
          if (objfile)
1522
115k
            objfile->GetDependentModules(dependent_files);
1523
115k
        }
1524
115k
      }
1525
2.42k
      ModulesDidLoad(added_modules);
1526
2.42k
    }
1527
2.55k
  }
1528
2.55k
}
1529
1530
bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1531
2.49k
                             bool merge) {
1532
2.49k
  Log *log = GetLog(LLDBLog::Target);
1533
2.49k
  bool missing_local_arch = !m_arch.GetSpec().IsValid();
1534
2.49k
  bool replace_local_arch = true;
1535
2.49k
  bool compatible_local_arch = false;
1536
2.49k
  ArchSpec other(arch_spec);
1537
1538
  // Changing the architecture might mean that the currently selected platform
1539
  // isn't compatible. Set the platform correctly if we are asked to do so,
1540
  // otherwise assume the user will set the platform manually.
1541
2.49k
  if (set_platform) {
1542
110
    if (other.IsValid()) {
1543
110
      auto platform_sp = GetPlatform();
1544
110
      if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1545
110
                              other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1546
105
        ArchSpec platform_arch;
1547
105
        if (PlatformSP arch_platform_sp =
1548
105
                GetDebugger().GetPlatformList().GetOrCreate(other, {},
1549
105
                                                            &platform_arch)) {
1550
88
          SetPlatform(arch_platform_sp);
1551
88
          if (platform_arch.IsValid())
1552
88
            other = platform_arch;
1553
88
        }
1554
105
      }
1555
110
    }
1556
110
  }
1557
1558
2.49k
  if (!missing_local_arch) {
1559
2.26k
    if (merge && 
m_arch.GetSpec().IsCompatibleMatch(arch_spec)2.26k
) {
1560
2.26k
      other.MergeFrom(m_arch.GetSpec());
1561
1562
2.26k
      if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1563
2.26k
        compatible_local_arch = true;
1564
2.26k
        bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1565
2.26k
            env_changed;
1566
1567
2.26k
        m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed,
1568
2.26k
                                                vendor_changed, os_changed,
1569
2.26k
                                                os_ver_changed, env_changed);
1570
1571
2.26k
        if (!arch_changed && !vendor_changed && 
!os_changed2.25k
&&
!env_changed2.23k
)
1572
2.22k
          replace_local_arch = false;
1573
2.26k
      }
1574
2.26k
    }
1575
2.26k
  }
1576
1577
2.49k
  if (compatible_local_arch || 
missing_local_arch235
) {
1578
    // If we haven't got a valid arch spec, or the architectures are compatible
1579
    // update the architecture, unless the one we already have is more
1580
    // specified
1581
2.49k
    if (replace_local_arch)
1582
263
      m_arch = other;
1583
2.49k
    LLDB_LOG(log,
1584
2.49k
             "Target::SetArchitecture merging compatible arch; arch "
1585
2.49k
             "is now {0} ({1})",
1586
2.49k
             m_arch.GetSpec().GetArchitectureName(),
1587
2.49k
             m_arch.GetSpec().GetTriple().getTriple());
1588
2.49k
    return true;
1589
2.49k
  }
1590
1591
  // If we have an executable file, try to reset the executable to the desired
1592
  // architecture
1593
3
  LLDB_LOGF(
1594
3
      log,
1595
3
      "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1596
3
      arch_spec.GetArchitectureName(),
1597
3
      arch_spec.GetTriple().getTriple().c_str(),
1598
3
      m_arch.GetSpec().GetArchitectureName(),
1599
3
      m_arch.GetSpec().GetTriple().getTriple().c_str());
1600
3
  m_arch = other;
1601
3
  ModuleSP executable_sp = GetExecutableModule();
1602
1603
3
  ClearModules(true);
1604
  // Need to do something about unsetting breakpoints.
1605
1606
3
  if (executable_sp) {
1607
3
    LLDB_LOGF(log,
1608
3
              "Target::SetArchitecture Trying to select executable file "
1609
3
              "architecture %s (%s)",
1610
3
              arch_spec.GetArchitectureName(),
1611
3
              arch_spec.GetTriple().getTriple().c_str());
1612
3
    ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1613
3
    FileSpecList search_paths = GetExecutableSearchPaths();
1614
3
    Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1615
3
                                               &search_paths, nullptr, nullptr);
1616
1617
3
    if (!error.Fail() && 
executable_sp0
) {
1618
0
      SetExecutableModule(executable_sp, eLoadDependentsYes);
1619
0
      return true;
1620
0
    }
1621
3
  }
1622
3
  return false;
1623
3
}
1624
1625
103
bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1626
103
  Log *log = GetLog(LLDBLog::Target);
1627
103
  if (arch_spec.IsValid()) {
1628
103
    if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1629
      // The current target arch is compatible with "arch_spec", see if we can
1630
      // improve our current architecture using bits from "arch_spec"
1631
1632
66
      LLDB_LOGF(log,
1633
66
                "Target::MergeArchitecture target has arch %s, merging with "
1634
66
                "arch %s",
1635
66
                m_arch.GetSpec().GetTriple().getTriple().c_str(),
1636
66
                arch_spec.GetTriple().getTriple().c_str());
1637
1638
      // Merge bits from arch_spec into "merged_arch" and set our architecture
1639
66
      ArchSpec merged_arch(m_arch.GetSpec());
1640
66
      merged_arch.MergeFrom(arch_spec);
1641
66
      return SetArchitecture(merged_arch);
1642
66
    } else {
1643
      // The new architecture is different, we just need to replace it
1644
37
      return SetArchitecture(arch_spec);
1645
37
    }
1646
103
  }
1647
0
  return false;
1648
103
}
1649
1650
5.44k
void Target::NotifyWillClearList(const ModuleList &module_list) {}
1651
1652
void Target::NotifyModuleAdded(const ModuleList &module_list,
1653
7.57k
                               const ModuleSP &module_sp) {
1654
  // A module is being added to this target for the first time
1655
7.57k
  if (m_valid) {
1656
7.57k
    ModuleList my_module_list;
1657
7.57k
    my_module_list.Append(module_sp);
1658
7.57k
    ModulesDidLoad(my_module_list);
1659
7.57k
  }
1660
7.57k
}
1661
1662
void Target::NotifyModuleRemoved(const ModuleList &module_list,
1663
4.66k
                                 const ModuleSP &module_sp) {
1664
  // A module is being removed from this target.
1665
4.66k
  if (m_valid) {
1666
100
    ModuleList my_module_list;
1667
100
    my_module_list.Append(module_sp);
1668
100
    ModulesDidUnload(my_module_list, false);
1669
100
  }
1670
4.66k
}
1671
1672
void Target::NotifyModuleUpdated(const ModuleList &module_list,
1673
                                 const ModuleSP &old_module_sp,
1674
1
                                 const ModuleSP &new_module_sp) {
1675
  // A module is replacing an already added module
1676
1
  if (m_valid) {
1677
1
    m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1678
1
                                                            new_module_sp);
1679
1
    m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1680
1
        old_module_sp, new_module_sp);
1681
1
  }
1682
1
}
1683
1684
2.14k
void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1685
2.14k
  ModulesDidUnload(module_list, false);
1686
2.14k
}
1687
1688
14.4k
void Target::ModulesDidLoad(ModuleList &module_list) {
1689
14.4k
  const size_t num_images = module_list.GetSize();
1690
14.4k
  if (m_valid && num_images) {
1691
248k
    for (size_t idx = 0; idx < num_images; 
++idx234k
) {
1692
234k
      ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1693
234k
      LoadScriptingResourceForModule(module_sp, this);
1694
234k
    }
1695
14.2k
    m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1696
14.2k
    m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1697
14.2k
    if (m_process_sp) {
1698
9.31k
      m_process_sp->ModulesDidLoad(module_list);
1699
9.31k
    }
1700
14.2k
    BroadcastEvent(eBroadcastBitModulesLoaded,
1701
14.2k
                   new TargetEventData(this->shared_from_this(), module_list));
1702
14.2k
  }
1703
14.4k
}
1704
1705
25
void Target::SymbolsDidLoad(ModuleList &module_list) {
1706
25
  if (m_valid && module_list.GetSize()) {
1707
25
    if (m_process_sp) {
1708
16
      for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1709
16
        runtime->SymbolsDidLoad(module_list);
1710
16
      }
1711
12
    }
1712
1713
25
    m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1714
25
    m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1715
25
    BroadcastEvent(eBroadcastBitSymbolsLoaded,
1716
25
                   new TargetEventData(this->shared_from_this(), module_list));
1717
25
  }
1718
25
}
1719
1720
7.69k
void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1721
7.69k
  if (m_valid && 
module_list.GetSize()4.81k
) {
1722
2.26k
    UnloadModuleSections(module_list);
1723
2.26k
    BroadcastEvent(eBroadcastBitModulesUnloaded,
1724
2.26k
                   new TargetEventData(this->shared_from_this(), module_list));
1725
2.26k
    m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1726
2.26k
    m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1727
2.26k
                                                 delete_locations);
1728
1729
    // If a module was torn down it will have torn down the 'TypeSystemClang's
1730
    // that we used as source 'ASTContext's for the persistent variables in
1731
    // the current target. Those would now be unsafe to access because the
1732
    // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1733
    // variables. We only want to flush 'TypeSystem's if the module being
1734
    // unloaded was capable of describing a source type. JITted module unloads
1735
    // happen frequently for Objective-C utility functions or the REPL and rely
1736
    // on the persistent variables to stick around.
1737
2.26k
    const bool should_flush_type_systems =
1738
110k
        module_list.AnyOf([](lldb_private::Module &module) {
1739
110k
          auto *object_file = module.GetObjectFile();
1740
1741
110k
          if (!object_file)
1742
0
            return false;
1743
1744
110k
          auto type = object_file->GetType();
1745
1746
          // eTypeExecutable: when debugged binary was rebuilt
1747
          // eTypeSharedLibrary: if dylib was re-loaded
1748
110k
          return module.FileHasChanged() &&
1749
110k
                 
(4
type == ObjectFile::eTypeObjectFile4
||
1750
4
                  type == ObjectFile::eTypeExecutable ||
1751
4
                  
type == ObjectFile::eTypeSharedLibrary0
);
1752
110k
        });
1753
1754
2.26k
    if (should_flush_type_systems)
1755
4
      m_scratch_type_system_map.Clear();
1756
2.26k
  }
1757
7.69k
}
1758
1759
bool Target::ModuleIsExcludedForUnconstrainedSearches(
1760
0
    const FileSpec &module_file_spec) {
1761
0
  if (GetBreakpointsConsultPlatformAvoidList()) {
1762
0
    ModuleList matchingModules;
1763
0
    ModuleSpec module_spec(module_file_spec);
1764
0
    GetImages().FindModules(module_spec, matchingModules);
1765
0
    size_t num_modules = matchingModules.GetSize();
1766
1767
    // If there is more than one module for this file spec, only
1768
    // return true if ALL the modules are on the black list.
1769
0
    if (num_modules > 0) {
1770
0
      for (size_t i = 0; i < num_modules; i++) {
1771
0
        if (!ModuleIsExcludedForUnconstrainedSearches(
1772
0
                matchingModules.GetModuleAtIndex(i)))
1773
0
          return false;
1774
0
      }
1775
0
      return true;
1776
0
    }
1777
0
  }
1778
0
  return false;
1779
0
}
1780
1781
bool Target::ModuleIsExcludedForUnconstrainedSearches(
1782
273k
    const lldb::ModuleSP &module_sp) {
1783
273k
  if (GetBreakpointsConsultPlatformAvoidList()) {
1784
273k
    if (m_platform_sp)
1785
273k
      return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1786
273k
                                                                     module_sp);
1787
273k
  }
1788
0
  return false;
1789
273k
}
1790
1791
size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1792
238k
                                       size_t dst_len, Status &error) {
1793
238k
  SectionSP section_sp(addr.GetSection());
1794
238k
  if (section_sp) {
1795
    // If the contents of this section are encrypted, the on-disk file is
1796
    // unusable.  Read only from live memory.
1797
238k
    if (section_sp->IsEncrypted()) {
1798
0
      error.SetErrorString("section is encrypted");
1799
0
      return 0;
1800
0
    }
1801
238k
    ModuleSP module_sp(section_sp->GetModule());
1802
238k
    if (module_sp) {
1803
238k
      ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1804
238k
      if (objfile) {
1805
238k
        size_t bytes_read = objfile->ReadSectionData(
1806
238k
            section_sp.get(), addr.GetOffset(), dst, dst_len);
1807
238k
        if (bytes_read > 0)
1808
238k
          return bytes_read;
1809
99
        else
1810
99
          error.SetErrorStringWithFormat("error reading data from section %s",
1811
99
                                         section_sp->GetName().GetCString());
1812
238k
      } else
1813
0
        error.SetErrorString("address isn't from a object file");
1814
238k
    } else
1815
0
      error.SetErrorString("address isn't in a module");
1816
238k
  } else
1817
0
    error.SetErrorString("address doesn't contain a section that points to a "
1818
0
                         "section in a object file");
1819
1820
99
  return 0;
1821
238k
}
1822
1823
size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
1824
                          Status &error, bool force_live_memory,
1825
239k
                          lldb::addr_t *load_addr_ptr) {
1826
239k
  error.Clear();
1827
1828
239k
  Address fixed_addr = addr;
1829
239k
  if (ProcessIsValid())
1830
19.0k
    if (const ABISP &abi = m_process_sp->GetABI())
1831
19.0k
      fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
1832
19.0k
                                this);
1833
1834
  // if we end up reading this from process memory, we will fill this with the
1835
  // actual load address
1836
239k
  if (load_addr_ptr)
1837
29.1k
    *load_addr_ptr = LLDB_INVALID_ADDRESS;
1838
1839
239k
  size_t bytes_read = 0;
1840
1841
239k
  addr_t load_addr = LLDB_INVALID_ADDRESS;
1842
239k
  addr_t file_addr = LLDB_INVALID_ADDRESS;
1843
239k
  Address resolved_addr;
1844
239k
  if (!fixed_addr.IsSectionOffset()) {
1845
564
    SectionLoadList &section_load_list = GetSectionLoadList();
1846
564
    if (section_load_list.IsEmpty()) {
1847
      // No sections are loaded, so we must assume we are not running yet and
1848
      // anything we are given is a file address.
1849
194
      file_addr =
1850
194
          fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1851
                                  // its offset is the file address
1852
194
      m_images.ResolveFileAddress(file_addr, resolved_addr);
1853
370
    } else {
1854
      // We have at least one section loaded. This can be because we have
1855
      // manually loaded some sections with "target modules load ..." or
1856
      // because we have a live process that has sections loaded through
1857
      // the dynamic loader
1858
370
      load_addr =
1859
370
          fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1860
                                  // its offset is the load address
1861
370
      section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1862
370
    }
1863
564
  }
1864
239k
  if (!resolved_addr.IsValid())
1865
238k
    resolved_addr = fixed_addr;
1866
1867
  // If we read from the file cache but can't get as many bytes as requested,
1868
  // we keep the result around in this buffer, in case this result is the
1869
  // best we can do.
1870
239k
  std::unique_ptr<uint8_t[]> file_cache_read_buffer;
1871
239k
  size_t file_cache_bytes_read = 0;
1872
1873
  // Read from file cache if read-only section.
1874
239k
  if (!force_live_memory && 
resolved_addr.IsSectionOffset()18.4k
) {
1875
18.1k
    SectionSP section_sp(resolved_addr.GetSection());
1876
18.1k
    if (section_sp) {
1877
18.1k
      auto permissions = Flags(section_sp->GetPermissions());
1878
18.1k
      bool is_readonly = !permissions.Test(ePermissionsWritable) &&
1879
18.1k
                         
permissions.Test(ePermissionsReadable)18.0k
;
1880
18.1k
      if (is_readonly) {
1881
18.0k
        file_cache_bytes_read =
1882
18.0k
            ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1883
18.0k
        if (file_cache_bytes_read == dst_len)
1884
17.6k
          return file_cache_bytes_read;
1885
445
        else if (file_cache_bytes_read > 0) {
1886
397
          file_cache_read_buffer =
1887
397
              std::make_unique<uint8_t[]>(file_cache_bytes_read);
1888
397
          std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
1889
397
        }
1890
18.0k
      }
1891
18.1k
    }
1892
18.1k
  }
1893
1894
221k
  if (ProcessIsValid()) {
1895
1.40k
    if (load_addr == LLDB_INVALID_ADDRESS)
1896
1.04k
      load_addr = resolved_addr.GetLoadAddress(this);
1897
1898
1.40k
    if (load_addr == LLDB_INVALID_ADDRESS) {
1899
0
      ModuleSP addr_module_sp(resolved_addr.GetModule());
1900
0
      if (addr_module_sp && addr_module_sp->GetFileSpec())
1901
0
        error.SetErrorStringWithFormatv(
1902
0
            "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1903
0
            addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1904
0
      else
1905
0
        error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1906
0
                                       resolved_addr.GetFileAddress());
1907
1.40k
    } else {
1908
1.40k
      bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1909
1.40k
      if (bytes_read != dst_len) {
1910
76
        if (error.Success()) {
1911
0
          if (bytes_read == 0)
1912
0
            error.SetErrorStringWithFormat(
1913
0
                "read memory from 0x%" PRIx64 " failed", load_addr);
1914
0
          else
1915
0
            error.SetErrorStringWithFormat(
1916
0
                "only %" PRIu64 " of %" PRIu64
1917
0
                " bytes were read from memory at 0x%" PRIx64,
1918
0
                (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1919
0
        }
1920
76
      }
1921
1.40k
      if (bytes_read) {
1922
1.32k
        if (load_addr_ptr)
1923
297
          *load_addr_ptr = load_addr;
1924
1.32k
        return bytes_read;
1925
1.32k
      }
1926
1.40k
    }
1927
1.40k
  }
1928
1929
220k
  if (file_cache_read_buffer && 
file_cache_bytes_read > 00
) {
1930
    // Reading from the process failed. If we've previously succeeded in reading
1931
    // something from the file cache, then copy that over and return that.
1932
0
    std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
1933
0
    return file_cache_bytes_read;
1934
0
  }
1935
1936
220k
  if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
1937
    // If we didn't already try and read from the object file cache, then try
1938
    // it after failing to read from the process.
1939
220k
    return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1940
220k
  }
1941
17
  return 0;
1942
220k
}
1943
1944
size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1945
2
                                     Status &error, bool force_live_memory) {
1946
2
  char buf[256];
1947
2
  out_str.clear();
1948
2
  addr_t curr_addr = addr.GetLoadAddress(this);
1949
2
  Address address(addr);
1950
2
  while (true) {
1951
2
    size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
1952
2
                                          force_live_memory);
1953
2
    if (length == 0)
1954
0
      break;
1955
2
    out_str.append(buf, length);
1956
    // If we got "length - 1" bytes, we didn't get the whole C string, we need
1957
    // to read some more characters
1958
2
    if (length == sizeof(buf) - 1)
1959
0
      curr_addr += length;
1960
2
    else
1961
2
      break;
1962
0
    address = Address(curr_addr);
1963
0
  }
1964
2
  return out_str.size();
1965
2
}
1966
1967
size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1968
                                     size_t dst_max_len, Status &result_error,
1969
633
                                     bool force_live_memory) {
1970
633
  size_t total_cstr_len = 0;
1971
633
  if (dst && dst_max_len) {
1972
633
    result_error.Clear();
1973
    // NULL out everything just to be safe
1974
633
    memset(dst, 0, dst_max_len);
1975
633
    Status error;
1976
633
    addr_t curr_addr = addr.GetLoadAddress(this);
1977
633
    Address address(addr);
1978
1979
    // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1980
    // this really needs to be tied to the memory cache subsystem's cache line
1981
    // size, so leave this as a fixed constant.
1982
633
    const size_t cache_line_size = 512;
1983
1984
633
    size_t bytes_left = dst_max_len - 1;
1985
633
    char *curr_dst = dst;
1986
1987
669
    while (bytes_left > 0) {
1988
647
      addr_t cache_line_bytes_left =
1989
647
          cache_line_size - (curr_addr % cache_line_size);
1990
647
      addr_t bytes_to_read =
1991
647
          std::min<addr_t>(bytes_left, cache_line_bytes_left);
1992
647
      size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
1993
647
                                     force_live_memory);
1994
1995
647
      if (bytes_read == 0) {
1996
0
        result_error = error;
1997
0
        dst[total_cstr_len] = '\0';
1998
0
        break;
1999
0
      }
2000
647
      const size_t len = strlen(curr_dst);
2001
2002
647
      total_cstr_len += len;
2003
2004
647
      if (len < bytes_to_read)
2005
611
        break;
2006
2007
36
      curr_dst += bytes_read;
2008
36
      curr_addr += bytes_read;
2009
36
      bytes_left -= bytes_read;
2010
36
      address = Address(curr_addr);
2011
36
    }
2012
633
  } else {
2013
0
    if (dst == nullptr)
2014
0
      result_error.SetErrorString("invalid arguments");
2015
0
    else
2016
0
      result_error.Clear();
2017
0
  }
2018
633
  return total_cstr_len;
2019
633
}
2020
2021
66
addr_t Target::GetReasonableReadSize(const Address &addr) {
2022
66
  addr_t load_addr = addr.GetLoadAddress(this);
2023
66
  if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2024
    // Avoid crossing cache line boundaries.
2025
66
    addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2026
66
    return cache_line_size - (load_addr % cache_line_size);
2027
66
  }
2028
2029
  // The read is going to go to the file cache, so we can just pick a largish
2030
  // value.
2031
0
  return 0x1000;
2032
66
}
2033
2034
size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2035
                                    size_t max_bytes, Status &error,
2036
62
                                    size_t type_width, bool force_live_memory) {
2037
62
  if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2038
0
    return 0;
2039
2040
62
  size_t total_bytes_read = 0;
2041
2042
  // Ensure a null terminator independent of the number of bytes that is
2043
  // read.
2044
62
  memset(dst, 0, max_bytes);
2045
62
  size_t bytes_left = max_bytes - type_width;
2046
2047
62
  const char terminator[4] = {'\0', '\0', '\0', '\0'};
2048
62
  assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2049
62
                                             "string with more than 4 bytes "
2050
62
                                             "per character!");
2051
2052
62
  Address address = addr;
2053
62
  char *curr_dst = dst;
2054
2055
62
  error.Clear();
2056
66
  while (bytes_left > 0 && error.Success()) {
2057
66
    addr_t bytes_to_read =
2058
66
        std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2059
66
    size_t bytes_read =
2060
66
        ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2061
2062
66
    if (bytes_read == 0)
2063
0
      break;
2064
2065
    // Search for a null terminator of correct size and alignment in
2066
    // bytes_read
2067
66
    size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2068
66
    for (size_t i = aligned_start;
2069
598
         i + type_width <= total_bytes_read + bytes_read; 
i += type_width532
)
2070
594
      if (::memcmp(&dst[i], terminator, type_width) == 0) {
2071
62
        error.Clear();
2072
62
        return i;
2073
62
      }
2074
2075
4
    total_bytes_read += bytes_read;
2076
4
    curr_dst += bytes_read;
2077
4
    address.Slide(bytes_read);
2078
4
    bytes_left -= bytes_read;
2079
4
  }
2080
0
  return total_bytes_read;
2081
62
}
2082
2083
size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2084
                                           bool is_signed, Scalar &scalar,
2085
                                           Status &error,
2086
0
                                           bool force_live_memory) {
2087
0
  uint64_t uval;
2088
2089
0
  if (byte_size <= sizeof(uval)) {
2090
0
    size_t bytes_read =
2091
0
        ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2092
0
    if (bytes_read == byte_size) {
2093
0
      DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2094
0
                         m_arch.GetSpec().GetAddressByteSize());
2095
0
      lldb::offset_t offset = 0;
2096
0
      if (byte_size <= 4)
2097
0
        scalar = data.GetMaxU32(&offset, byte_size);
2098
0
      else
2099
0
        scalar = data.GetMaxU64(&offset, byte_size);
2100
2101
0
      if (is_signed)
2102
0
        scalar.SignExtend(byte_size * 8);
2103
0
      return bytes_read;
2104
0
    }
2105
0
  } else {
2106
0
    error.SetErrorStringWithFormat(
2107
0
        "byte size of %u is too large for integer scalar type", byte_size);
2108
0
  }
2109
0
  return 0;
2110
0
}
2111
2112
uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
2113
                                               size_t integer_byte_size,
2114
                                               uint64_t fail_value, Status &error,
2115
0
                                               bool force_live_memory) {
2116
0
  Scalar scalar;
2117
0
  if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2118
0
                                  force_live_memory))
2119
0
    return scalar.ULongLong(fail_value);
2120
0
  return fail_value;
2121
0
}
2122
2123
bool Target::ReadPointerFromMemory(const Address &addr, Status &error,
2124
                                   Address &pointer_addr,
2125
0
                                   bool force_live_memory) {
2126
0
  Scalar scalar;
2127
0
  if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2128
0
                                  false, scalar, error, force_live_memory)) {
2129
0
    addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2130
0
    if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2131
0
      SectionLoadList &section_load_list = GetSectionLoadList();
2132
0
      if (section_load_list.IsEmpty()) {
2133
        // No sections are loaded, so we must assume we are not running yet and
2134
        // anything we are given is a file address.
2135
0
        m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2136
0
      } else {
2137
        // We have at least one section loaded. This can be because we have
2138
        // manually loaded some sections with "target modules load ..." or
2139
        // because we have a live process that has sections loaded through
2140
        // the dynamic loader
2141
0
        section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2142
0
      }
2143
      // We weren't able to resolve the pointer value, so just return an
2144
      // address with no section
2145
0
      if (!pointer_addr.IsValid())
2146
0
        pointer_addr.SetOffset(pointer_vm_addr);
2147
0
      return true;
2148
0
    }
2149
0
  }
2150
0
  return false;
2151
0
}
2152
2153
ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
2154
227k
                                   Status *error_ptr) {
2155
227k
  ModuleSP module_sp;
2156
2157
227k
  Status error;
2158
2159
  // First see if we already have this module in our module list.  If we do,
2160
  // then we're done, we don't need to consult the shared modules list.  But
2161
  // only do this if we are passed a UUID.
2162
2163
227k
  if (module_spec.GetUUID().IsValid())
2164
111k
    module_sp = m_images.FindFirstModule(module_spec);
2165
2166
227k
  if (!module_sp) {
2167
227k
    llvm::SmallVector<ModuleSP, 1>
2168
227k
        old_modules; // This will get filled in if we have a new version
2169
                     // of the library
2170
227k
    bool did_create_module = false;
2171
227k
    FileSpecList search_paths = GetExecutableSearchPaths();
2172
227k
    FileSpec symbol_file_spec;
2173
2174
    // Call locate module callback if set. This allows users to implement their
2175
    // own module cache system. For example, to leverage build system artifacts,
2176
    // to bypass pulling files from remote platform, or to search symbol files
2177
    // from symbol servers.
2178
227k
    if (m_platform_sp)
2179
227k
      m_platform_sp->CallLocateModuleCallbackIfSet(
2180
227k
          module_spec, module_sp, symbol_file_spec, &did_create_module);
2181
2182
    // The result of this CallLocateModuleCallbackIfSet is one of the following.
2183
    // 1. module_sp:loaded, symbol_file_spec:set
2184
    //      The callback found a module file and a symbol file for the
2185
    //      module_spec. We will call module_sp->SetSymbolFileFileSpec with
2186
    //      the symbol_file_spec later.
2187
    // 2. module_sp:loaded, symbol_file_spec:empty
2188
    //      The callback only found a module file for the module_spec.
2189
    // 3. module_sp:empty, symbol_file_spec:set
2190
    //      The callback only found a symbol file for the module. We continue
2191
    //      to find a module file for this module_spec and we will call
2192
    //      module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2193
    // 4. module_sp:empty, symbol_file_spec:empty
2194
    //      Platform does not exist, the callback is not set, the callback did
2195
    //      not find any module files nor any symbol files, the callback failed,
2196
    //      or something went wrong. We continue to find a module file for this
2197
    //      module_spec.
2198
2199
227k
    if (!module_sp) {
2200
      // If there are image search path entries, try to use them to acquire a
2201
      // suitable image.
2202
227k
      if (m_image_search_paths.GetSize()) {
2203
249
        ModuleSpec transformed_spec(module_spec);
2204
249
        ConstString transformed_dir;
2205
249
        if (m_image_search_paths.RemapPath(
2206
249
                module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2207
3
          transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2208
3
          transformed_spec.GetFileSpec().SetFilename(
2209
3
                module_spec.GetFileSpec().GetFilename());
2210
3
          error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2211
3
                                              &search_paths, &old_modules,
2212
3
                                              &did_create_module);
2213
3
        }
2214
249
      }
2215
227k
    }
2216
2217
227k
    if (!module_sp) {
2218
      // If we have a UUID, we can check our global shared module list in case
2219
      // we already have it. If we don't have a valid UUID, then we can't since
2220
      // the path in "module_spec" will be a platform path, and we will need to
2221
      // let the platform find that file. For example, we could be asking for
2222
      // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2223
      // the local copy of "/usr/lib/dyld" since our platform could be a remote
2224
      // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2225
      // cache.
2226
227k
      if (module_spec.GetUUID().IsValid()) {
2227
        // We have a UUID, it is OK to check the global module list...
2228
111k
        error =
2229
111k
            ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2230
111k
                                        &old_modules, &did_create_module);
2231
111k
      }
2232
2233
227k
      if (!module_sp) {
2234
        // The platform is responsible for finding and caching an appropriate
2235
        // module in the shared module cache.
2236
116k
        if (m_platform_sp) {
2237
116k
          error = m_platform_sp->GetSharedModule(
2238
116k
              module_spec, m_process_sp.get(), module_sp, &search_paths,
2239
116k
              &old_modules, &did_create_module);
2240
116k
        } else {
2241
0
          error.SetErrorString("no platform is currently set");
2242
0
        }
2243
116k
      }
2244
227k
    }
2245
2246
    // We found a module that wasn't in our target list.  Let's make sure that
2247
    // there wasn't an equivalent module in the list already, and if there was,
2248
    // let's remove it.
2249
227k
    if (module_sp) {
2250
227k
      ObjectFile *objfile = module_sp->GetObjectFile();
2251
227k
      if (objfile) {
2252
227k
        switch (objfile->GetType()) {
2253
0
        case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2254
                                        /// a program's execution state
2255
2.15k
        case ObjectFile::eTypeExecutable:    /// A normal executable
2256
6.55k
        case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2257
                                             /// executable
2258
6.55k
        case ObjectFile::eTypeObjectFile:    /// An intermediate object file
2259
227k
        case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2260
                                             /// used during execution
2261
227k
          break;
2262
1
        case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2263
                                         /// debug information
2264
1
          if (error_ptr)
2265
0
            error_ptr->SetErrorString("debug info files aren't valid target "
2266
0
                                      "modules, please specify an executable");
2267
1
          return ModuleSP();
2268
0
        case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2269
                                           /// against but not used for
2270
                                           /// execution
2271
0
          if (error_ptr)
2272
0
            error_ptr->SetErrorString("stub libraries aren't valid target "
2273
0
                                      "modules, please specify an executable");
2274
0
          return ModuleSP();
2275
0
        default:
2276
0
          if (error_ptr)
2277
0
            error_ptr->SetErrorString(
2278
0
                "unsupported file type, please specify an executable");
2279
0
          return ModuleSP();
2280
227k
        }
2281
        // GetSharedModule is not guaranteed to find the old shared module, for
2282
        // instance in the common case where you pass in the UUID, it is only
2283
        // going to find the one module matching the UUID.  In fact, it has no
2284
        // good way to know what the "old module" relevant to this target is,
2285
        // since there might be many copies of a module with this file spec in
2286
        // various running debug sessions, but only one of them will belong to
2287
        // this target. So let's remove the UUID from the module list, and look
2288
        // in the target's module list. Only do this if there is SOMETHING else
2289
        // in the module spec...
2290
227k
        if (module_spec.GetUUID().IsValid() &&
2291
227k
            
!module_spec.GetFileSpec().GetFilename().IsEmpty()111k
&&
2292
227k
            
!module_spec.GetFileSpec().GetDirectory().IsEmpty()111k
) {
2293
111k
          ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2294
111k
          module_spec_copy.GetUUID().Clear();
2295
2296
111k
          ModuleList found_modules;
2297
111k
          m_images.FindModules(module_spec_copy, found_modules);
2298
111k
          found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2299
0
            old_modules.push_back(found_module);
2300
0
            return true;
2301
0
          });
2302
111k
        }
2303
2304
        // If the locate module callback had found a symbol file, set it to the
2305
        // module_sp before preloading symbols.
2306
227k
        if (symbol_file_spec)
2307
10
          module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2308
2309
        // Preload symbols outside of any lock, so hopefully we can do this for
2310
        // each library in parallel.
2311
227k
        if (GetPreloadSymbols())
2312
226k
          module_sp->PreloadSymbols();
2313
227k
        llvm::SmallVector<ModuleSP, 1> replaced_modules;
2314
227k
        for (ModuleSP &old_module_sp : old_modules) {
2315
6
          if (m_images.GetIndexForModule(old_module_sp.get()) !=
2316
6
              LLDB_INVALID_INDEX32) {
2317
1
            if (replaced_modules.empty())
2318
1
              m_images.ReplaceModule(old_module_sp, module_sp);
2319
0
            else
2320
0
              m_images.Remove(old_module_sp);
2321
2322
1
            replaced_modules.push_back(std::move(old_module_sp));
2323
1
          }
2324
6
        }
2325
2326
227k
        if (replaced_modules.size() > 1) {
2327
          // The same new module replaced multiple old modules
2328
          // simultaneously.  It's not clear this should ever
2329
          // happen (if we always replace old modules as we add
2330
          // new ones, presumably we should never have more than
2331
          // one old one).  If there are legitimate cases where
2332
          // this happens, then the ModuleList::Notifier interface
2333
          // may need to be adjusted to allow reporting this.
2334
          // In the meantime, just log that this has happened; just
2335
          // above we called ReplaceModule on the first one, and Remove
2336
          // on the rest.
2337
0
          if (Log *log = GetLog(LLDBLog::Target | LLDBLog::Modules)) {
2338
0
            StreamString message;
2339
0
            auto dump = [&message](Module &dump_module) -> void {
2340
0
              UUID dump_uuid = dump_module.GetUUID();
2341
2342
0
              message << '[';
2343
0
              dump_module.GetDescription(message.AsRawOstream());
2344
0
              message << " (uuid ";
2345
2346
0
              if (dump_uuid.IsValid())
2347
0
                dump_uuid.Dump(message);
2348
0
              else
2349
0
                message << "not specified";
2350
2351
0
              message << ")]";
2352
0
            };
2353
2354
0
            message << "New module ";
2355
0
            dump(*module_sp);
2356
0
            message.AsRawOstream()
2357
0
                << llvm::formatv(" simultaneously replaced {0} old modules: ",
2358
0
                                 replaced_modules.size());
2359
0
            for (ModuleSP &replaced_module_sp : replaced_modules)
2360
0
              dump(*replaced_module_sp);
2361
2362
0
            log->PutString(message.GetString());
2363
0
          }
2364
0
        }
2365
2366
227k
        if (replaced_modules.empty())
2367
227k
          m_images.Append(module_sp, notify);
2368
2369
227k
        for (ModuleSP &old_module_sp : replaced_modules) {
2370
1
          Module *old_module_ptr = old_module_sp.get();
2371
1
          old_module_sp.reset();
2372
1
          ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2373
1
        }
2374
227k
      } else
2375
0
        module_sp.reset();
2376
227k
    }
2377
227k
  }
2378
227k
  if (error_ptr)
2379
568
    *error_ptr = error;
2380
227k
  return module_sp;
2381
227k
}
2382
2383
335k
TargetSP Target::CalculateTarget() { return shared_from_this(); }
2384
2385
580
ProcessSP Target::CalculateProcess() { return m_process_sp; }
2386
2387
0
ThreadSP Target::CalculateThread() { return ThreadSP(); }
2388
2389
298
StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2390
2391
525k
void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2392
525k
  exe_ctx.Clear();
2393
525k
  exe_ctx.SetTargetPtr(this);
2394
525k
}
2395
2396
12
PathMappingList &Target::GetImageSearchPathList() {
2397
12
  return m_image_search_paths;
2398
12
}
2399
2400
void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2401
6
                                     void *baton) {
2402
6
  Target *target = (Target *)baton;
2403
6
  ModuleSP exe_module_sp(target->GetExecutableModule());
2404
6
  if (exe_module_sp)
2405
6
    target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2406
6
}
2407
2408
llvm::Expected<lldb::TypeSystemSP>
2409
Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2410
179k
                                        bool create_on_demand) {
2411
179k
  if (!m_valid)
2412
2.08k
    return llvm::make_error<llvm::StringError>("Invalid Target",
2413
2.08k
                                               llvm::inconvertibleErrorCode());
2414
2415
177k
  if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2416
                                             // assembly code
2417
177k
      || language == eLanguageTypeUnknown) {
2418
2.29k
    LanguageSet languages_for_expressions =
2419
2.29k
        Language::GetLanguagesSupportingTypeSystemsForExpressions();
2420
2421
2.29k
    if (languages_for_expressions[eLanguageTypeC]) {
2422
0
      language = eLanguageTypeC; // LLDB's default.  Override by setting the
2423
                                 // target language.
2424
2.29k
    } else {
2425
2.29k
      if (languages_for_expressions.Empty())
2426
0
        return llvm::make_error<llvm::StringError>(
2427
0
            "No expression support for any languages",
2428
0
            llvm::inconvertibleErrorCode());
2429
2.29k
      language = (LanguageType)languages_for_expressions.bitvector.find_first();
2430
2.29k
    }
2431
2.29k
  }
2432
2433
177k
  return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2434
177k
                                                            create_on_demand);
2435
177k
}
2436
2437
CompilerType Target::GetRegisterType(const std::string &name,
2438
                                     const lldb_private::RegisterFlags &flags,
2439
37
                                     uint32_t byte_size) {
2440
37
  RegisterTypeBuilderSP provider = PluginManager::GetRegisterTypeBuilder(*this);
2441
37
  assert(provider);
2442
37
  return provider->GetRegisterType(name, flags, byte_size);
2443
37
}
2444
2445
std::vector<lldb::TypeSystemSP>
2446
14
Target::GetScratchTypeSystems(bool create_on_demand) {
2447
14
  if (!m_valid)
2448
0
    return {};
2449
2450
  // Some TypeSystem instances are associated with several LanguageTypes so
2451
  // they will show up several times in the loop below. The SetVector filters
2452
  // out all duplicates as they serve no use for the caller.
2453
14
  std::vector<lldb::TypeSystemSP> scratch_type_systems;
2454
2455
14
  LanguageSet languages_for_expressions =
2456
14
      Language::GetLanguagesSupportingTypeSystemsForExpressions();
2457
2458
98
  for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2459
98
    auto language = (LanguageType)bit;
2460
98
    auto type_system_or_err =
2461
98
        GetScratchTypeSystemForLanguage(language, create_on_demand);
2462
98
    if (!type_system_or_err)
2463
0
      LLDB_LOG_ERROR(
2464
98
          GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2465
98
          "Language '{1}' has expression support but no scratch type "
2466
98
          "system available: {0}",
2467
98
          Language::GetNameForLanguageType(language));
2468
98
    else
2469
98
      if (auto ts = *type_system_or_err)
2470
98
        scratch_type_systems.push_back(ts);
2471
98
  }
2472
2473
14
  std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2474
14
  scratch_type_systems.erase(
2475
14
      std::unique(scratch_type_systems.begin(), scratch_type_systems.end()),
2476
14
      scratch_type_systems.end());
2477
14
  return scratch_type_systems;
2478
14
}
2479
2480
PersistentExpressionState *
2481
76.8k
Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2482
76.8k
  auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2483
2484
76.8k
  if (auto err = type_system_or_err.takeError()) {
2485
0
    LLDB_LOG_ERROR(
2486
0
        GetLog(LLDBLog::Target), std::move(err),
2487
0
        "Unable to get persistent expression state for language {1}: {0}",
2488
0
        Language::GetNameForLanguageType(language));
2489
0
    return nullptr;
2490
0
  }
2491
2492
76.8k
  if (auto ts = *type_system_or_err)
2493
76.8k
    return ts->GetPersistentExpressionState();
2494
2495
0
  LLDB_LOG(GetLog(LLDBLog::Target),
2496
0
           "Unable to get persistent expression state for language {1}: {0}",
2497
0
           Language::GetNameForLanguageType(language));
2498
0
  return nullptr;
2499
76.8k
}
2500
2501
UserExpression *Target::GetUserExpressionForLanguage(
2502
    llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2503
    Expression::ResultType desired_type,
2504
    const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2505
7.23k
    Status &error) {
2506
7.23k
  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2507
7.23k
  if (auto err = type_system_or_err.takeError()) {
2508
0
    error.SetErrorStringWithFormat(
2509
0
        "Could not find type system for language %s: %s",
2510
0
        Language::GetNameForLanguageType(language),
2511
0
        llvm::toString(std::move(err)).c_str());
2512
0
    return nullptr;
2513
0
  }
2514
2515
7.23k
  auto ts = *type_system_or_err;
2516
7.23k
  if (!ts) {
2517
0
    error.SetErrorStringWithFormat(
2518
0
        "Type system for language %s is no longer live",
2519
0
        Language::GetNameForLanguageType(language));
2520
0
    return nullptr;
2521
0
  }
2522
2523
7.23k
  auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2524
7.23k
                                          options, ctx_obj);
2525
7.23k
  if (!user_expr)
2526
0
    error.SetErrorStringWithFormat(
2527
0
        "Could not create an expression for language %s",
2528
0
        Language::GetNameForLanguageType(language));
2529
2530
7.23k
  return user_expr;
2531
7.23k
}
2532
2533
FunctionCaller *Target::GetFunctionCallerForLanguage(
2534
    lldb::LanguageType language, const CompilerType &return_type,
2535
    const Address &function_address, const ValueList &arg_value_list,
2536
2.02k
    const char *name, Status &error) {
2537
2.02k
  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2538
2.02k
  if (auto err = type_system_or_err.takeError()) {
2539
0
    error.SetErrorStringWithFormat(
2540
0
        "Could not find type system for language %s: %s",
2541
0
        Language::GetNameForLanguageType(language),
2542
0
        llvm::toString(std::move(err)).c_str());
2543
0
    return nullptr;
2544
0
  }
2545
2.02k
  auto ts = *type_system_or_err;
2546
2.02k
  if (!ts) {
2547
0
    error.SetErrorStringWithFormat(
2548
0
        "Type system for language %s is no longer live",
2549
0
        Language::GetNameForLanguageType(language));
2550
0
    return nullptr;
2551
0
  }
2552
2.02k
  auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2553
2.02k
                                              arg_value_list, name);
2554
2.02k
  if (!persistent_fn)
2555
0
    error.SetErrorStringWithFormat(
2556
0
        "Could not create an expression for language %s",
2557
0
        Language::GetNameForLanguageType(language));
2558
2559
2.02k
  return persistent_fn;
2560
2.02k
}
2561
2562
llvm::Expected<std::unique_ptr<UtilityFunction>>
2563
Target::CreateUtilityFunction(std::string expression, std::string name,
2564
                              lldb::LanguageType language,
2565
2.67k
                              ExecutionContext &exe_ctx) {
2566
2.67k
  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2567
2.67k
  if (!type_system_or_err)
2568
0
    return type_system_or_err.takeError();
2569
2.67k
  auto ts = *type_system_or_err;
2570
2.67k
  if (!ts)
2571
0
    return llvm::make_error<llvm::StringError>(
2572
0
        llvm::StringRef("Type system for language ") +
2573
0
            Language::GetNameForLanguageType(language) +
2574
0
            llvm::StringRef(" is no longer live"),
2575
0
        llvm::inconvertibleErrorCode());
2576
2.67k
  std::unique_ptr<UtilityFunction> utility_fn =
2577
2.67k
      ts->CreateUtilityFunction(std::move(expression), std::move(name));
2578
2.67k
  if (!utility_fn)
2579
0
    return llvm::make_error<llvm::StringError>(
2580
0
        llvm::StringRef("Could not create an expression for language") +
2581
0
            Language::GetNameForLanguageType(language),
2582
0
        llvm::inconvertibleErrorCode());
2583
2584
2.67k
  DiagnosticManager diagnostics;
2585
2.67k
  if (!utility_fn->Install(diagnostics, exe_ctx))
2586
0
    return llvm::make_error<llvm::StringError>(diagnostics.GetString(),
2587
0
                                               llvm::inconvertibleErrorCode());
2588
2589
2.67k
  return std::move(utility_fn);
2590
2.67k
}
2591
2592
3.95k
void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2593
2594
3.94k
void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2595
2596
2.59k
FileSpecList Target::GetDefaultExecutableSearchPaths() {
2597
2.59k
  return Target::GetGlobalProperties().GetExecutableSearchPaths();
2598
2.59k
}
2599
2600
117k
FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2601
117k
  return Target::GetGlobalProperties().GetDebugFileSearchPaths();
2602
117k
}
2603
2604
6.34k
ArchSpec Target::GetDefaultArchitecture() {
2605
6.34k
  return Target::GetGlobalProperties().GetDefaultArchitecture();
2606
6.34k
}
2607
2608
4
void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2609
4
  LLDB_LOG(GetLog(LLDBLog::Target),
2610
4
           "setting target's default architecture to  {0} ({1})",
2611
4
           arch.GetArchitectureName(), arch.GetTriple().getTriple());
2612
4
  Target::GetGlobalProperties().SetDefaultArchitecture(arch);
2613
4
}
2614
2615
6
llvm::Error Target::SetLabel(llvm::StringRef label) {
2616
6
  size_t n = LLDB_INVALID_INDEX32;
2617
6
  if (llvm::to_integer(label, n))
2618
1
    return llvm::make_error<llvm::StringError>(
2619
1
        "Cannot use integer as target label.", llvm::inconvertibleErrorCode());
2620
5
  TargetList &targets = GetDebugger().GetTargetList();
2621
14
  for (size_t i = 0; i < targets.GetNumTargets(); 
i++9
) {
2622
10
    TargetSP target_sp = targets.GetTargetAtIndex(i);
2623
10
    if (target_sp && target_sp->GetLabel() == label) {
2624
1
        return llvm::make_error<llvm::StringError>(
2625
1
            llvm::formatv(
2626
1
                "Cannot use label '{0}' since it's set in target #{1}.", label,
2627
1
                i),
2628
1
            llvm::inconvertibleErrorCode());
2629
1
    }
2630
10
  }
2631
2632
4
  m_label = label.str();
2633
4
  return llvm::Error::success();
2634
5
}
2635
2636
Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2637
1.95M
                                      const SymbolContext *sc_ptr) {
2638
  // The target can either exist in the "process" of ExecutionContext, or in
2639
  // the "target_sp" member of SymbolContext. This accessor helper function
2640
  // will get the target from one of these locations.
2641
2642
1.95M
  Target *target = nullptr;
2643
1.95M
  if (sc_ptr != nullptr)
2644
1.94M
    target = sc_ptr->target_sp.get();
2645
1.95M
  if (target == nullptr && 
exe_ctx_ptr1.94M
)
2646
1.94M
    target = exe_ctx_ptr->GetTargetPtr();
2647
1.95M
  return target;
2648
1.95M
}
2649
2650
ExpressionResults Target::EvaluateExpression(
2651
    llvm::StringRef expr, ExecutionContextScope *exe_scope,
2652
    lldb::ValueObjectSP &result_valobj_sp,
2653
    const EvaluateExpressionOptions &options, std::string *fixed_expression,
2654
7.15k
    ValueObject *ctx_obj) {
2655
7.15k
  result_valobj_sp.reset();
2656
2657
7.15k
  ExpressionResults execution_results = eExpressionSetupError;
2658
2659
7.15k
  if (expr.empty()) {
2660
1
    m_stats.GetExpressionStats().NotifyFailure();
2661
1
    return execution_results;
2662
1
  }
2663
2664
  // We shouldn't run stop hooks in expressions.
2665
7.15k
  bool old_suppress_value = m_suppress_stop_hooks;
2666
7.15k
  m_suppress_stop_hooks = true;
2667
7.15k
  auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2668
7.15k
    m_suppress_stop_hooks = old_suppress_value;
2669
7.15k
  });
2670
2671
7.15k
  ExecutionContext exe_ctx;
2672
2673
7.15k
  if (exe_scope) {
2674
6.84k
    exe_scope->CalculateExecutionContext(exe_ctx);
2675
6.84k
  } else 
if (309
m_process_sp309
) {
2676
13
    m_process_sp->CalculateExecutionContext(exe_ctx);
2677
296
  } else {
2678
296
    CalculateExecutionContext(exe_ctx);
2679
296
  }
2680
2681
  // Make sure we aren't just trying to see the value of a persistent variable
2682
  // (something like "$0")
2683
  // Only check for persistent variables the expression starts with a '$'
2684
7.15k
  lldb::ExpressionVariableSP persistent_var_sp;
2685
7.15k
  if (expr[0] == '$') {
2686
120
    auto type_system_or_err =
2687
120
            GetScratchTypeSystemForLanguage(eLanguageTypeC);
2688
120
    if (auto err = type_system_or_err.takeError()) {
2689
0
      LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2690
0
                     "Unable to get scratch type system");
2691
120
    } else {
2692
120
      auto ts = *type_system_or_err;
2693
120
      if (!ts)
2694
0
        LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2695
120
                       "Scratch type system is no longer live: {0}");
2696
120
      else
2697
120
        persistent_var_sp =
2698
120
            ts->GetPersistentExpressionState()->GetVariable(expr);
2699
120
    }
2700
120
  }
2701
7.15k
  if (persistent_var_sp) {
2702
42
    result_valobj_sp = persistent_var_sp->GetValueObject();
2703
42
    execution_results = eExpressionCompleted;
2704
7.11k
  } else {
2705
7.11k
    llvm::StringRef prefix = GetExpressionPrefixContents();
2706
7.11k
    Status error;
2707
7.11k
    execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2708
7.11k
                                                 result_valobj_sp, error,
2709
7.11k
                                                 fixed_expression, ctx_obj);
2710
    // Pass up the error by wrapping it inside an error result.
2711
7.11k
    if (error.Fail() && 
!result_valobj_sp470
)
2712
41
      result_valobj_sp = ValueObjectConstResult::Create(
2713
41
          exe_ctx.GetBestExecutionContextScope(), error);
2714
7.11k
  }
2715
2716
7.15k
  if (execution_results == eExpressionCompleted)
2717
6.79k
    m_stats.GetExpressionStats().NotifySuccess();
2718
361
  else
2719
361
    m_stats.GetExpressionStats().NotifyFailure();
2720
7.15k
  return execution_results;
2721
7.15k
}
2722
2723
99
lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2724
99
  lldb::ExpressionVariableSP variable_sp;
2725
99
  m_scratch_type_system_map.ForEach(
2726
99
      [name, &variable_sp](TypeSystemSP type_system) -> bool {
2727
99
        auto ts = type_system.get();
2728
99
        if (!ts)
2729
0
          return true;
2730
99
        if (PersistentExpressionState *persistent_state =
2731
99
                ts->GetPersistentExpressionState()) {
2732
99
          variable_sp = persistent_state->GetVariable(name);
2733
2734
99
          if (variable_sp)
2735
95
            return false; // Stop iterating the ForEach
2736
99
        }
2737
4
        return true; // Keep iterating the ForEach
2738
99
      });
2739
99
  return variable_sp;
2740
99
}
2741
2742
82
lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2743
82
  lldb::addr_t address = LLDB_INVALID_ADDRESS;
2744
2745
82
  m_scratch_type_system_map.ForEach(
2746
82
      [name, &address](lldb::TypeSystemSP type_system) -> bool {
2747
82
        auto ts = type_system.get();
2748
82
        if (!ts)
2749
0
          return true;
2750
2751
82
        if (PersistentExpressionState *persistent_state =
2752
82
                ts->GetPersistentExpressionState()) {
2753
82
          address = persistent_state->LookupSymbol(name);
2754
82
          if (address != LLDB_INVALID_ADDRESS)
2755
8
            return false; // Stop iterating the ForEach
2756
82
        }
2757
74
        return true; // Keep iterating the ForEach
2758
82
      });
2759
82
  return address;
2760
82
}
2761
2762
3.36k
llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2763
3.36k
  Module *exe_module = GetExecutableModulePointer();
2764
2765
  // Try to find the entry point address in the primary executable.
2766
3.36k
  const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2767
3.36k
  if (has_primary_executable) {
2768
3.36k
    Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2769
3.36k
    if (entry_addr.IsValid())
2770
3.36k
      return entry_addr;
2771
3.36k
  }
2772
2773
0
  const ModuleList &modules = GetImages();
2774
0
  const size_t num_images = modules.GetSize();
2775
0
  for (size_t idx = 0; idx < num_images; ++idx) {
2776
0
    ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2777
0
    if (!module_sp || !module_sp->GetObjectFile())
2778
0
      continue;
2779
2780
0
    Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2781
0
    if (entry_addr.IsValid())
2782
0
      return entry_addr;
2783
0
  }
2784
2785
  // We haven't found the entry point address. Return an appropriate error.
2786
0
  if (!has_primary_executable)
2787
0
    return llvm::make_error<llvm::StringError>(
2788
0
        "No primary executable found and could not find entry point address in "
2789
0
        "any executable module",
2790
0
        llvm::inconvertibleErrorCode());
2791
2792
0
  return llvm::make_error<llvm::StringError>(
2793
0
      "Could not find entry point address for primary executable module \"" +
2794
0
          exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2795
0
      llvm::inconvertibleErrorCode());
2796
0
}
2797
2798
lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2799
12.6k
                                            AddressClass addr_class) const {
2800
12.6k
  auto arch_plugin = GetArchitecturePlugin();
2801
12.6k
  return arch_plugin
2802
12.6k
             ? 
arch_plugin->GetCallableLoadAddress(load_addr, addr_class)0
2803
12.6k
             : load_addr;
2804
12.6k
}
2805
2806
lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2807
565k
                                          AddressClass addr_class) const {
2808
565k
  auto arch_plugin = GetArchitecturePlugin();
2809
565k
  return arch_plugin ? 
arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)186
2810
565k
                     : 
load_addr564k
;
2811
565k
}
2812
2813
4.12k
lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2814
4.12k
  auto arch_plugin = GetArchitecturePlugin();
2815
4.12k
  return arch_plugin ? 
arch_plugin->GetBreakableLoadAddress(addr, *this)5
:
addr4.12k
;
2816
4.12k
}
2817
2818
38.8k
SourceManager &Target::GetSourceManager() {
2819
38.8k
  if (!m_source_manager_up)
2820
1.70k
    m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2821
38.8k
  return *m_source_manager_up;
2822
38.8k
}
2823
2824
18
Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) {
2825
18
  lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2826
18
  Target::StopHookSP stop_hook_sp;
2827
18
  switch (kind) {
2828
8
  case StopHook::StopHookKind::CommandBased:
2829
8
    stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2830
8
    break;
2831
10
  case StopHook::StopHookKind::ScriptBased:
2832
10
    stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2833
10
    break;
2834
18
  }
2835
18
  m_stop_hooks[new_uid] = stop_hook_sp;
2836
18
  return stop_hook_sp;
2837
18
}
2838
2839
2
void Target::UndoCreateStopHook(lldb::user_id_t user_id) {
2840
2
  if (!RemoveStopHookByID(user_id))
2841
0
    return;
2842
2
  if (user_id == m_stop_hook_next_id)
2843
2
    m_stop_hook_next_id--;
2844
2
}
2845
2846
3
bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2847
3
  size_t num_removed = m_stop_hooks.erase(user_id);
2848
3
  return (num_removed != 0);
2849
3
}
2850
2851
3
void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2852
2853
0
Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2854
0
  StopHookSP found_hook;
2855
2856
0
  StopHookCollection::iterator specified_hook_iter;
2857
0
  specified_hook_iter = m_stop_hooks.find(user_id);
2858
0
  if (specified_hook_iter != m_stop_hooks.end())
2859
0
    found_hook = (*specified_hook_iter).second;
2860
0
  return found_hook;
2861
0
}
2862
2863
bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2864
2
                                        bool active_state) {
2865
2
  StopHookCollection::iterator specified_hook_iter;
2866
2
  specified_hook_iter = m_stop_hooks.find(user_id);
2867
2
  if (specified_hook_iter == m_stop_hooks.end())
2868
2
    return false;
2869
2870
0
  (*specified_hook_iter).second->SetIsActive(active_state);
2871
0
  return true;
2872
2
}
2873
2874
6
void Target::SetAllStopHooksActiveState(bool active_state) {
2875
6
  StopHookCollection::iterator pos, end = m_stop_hooks.end();
2876
12
  for (pos = m_stop_hooks.begin(); pos != end; 
pos++6
) {
2877
6
    (*pos).second->SetIsActive(active_state);
2878
6
  }
2879
6
}
2880
2881
3.70k
bool Target::RunStopHooks() {
2882
3.70k
  if (m_suppress_stop_hooks)
2883
0
    return false;
2884
2885
3.70k
  if (!m_process_sp)
2886
1
    return false;
2887
2888
  // Somebody might have restarted the process:
2889
  // Still return false, the return value is about US restarting the target.
2890
3.70k
  if (m_process_sp->GetState() != eStateStopped)
2891
0
    return false;
2892
2893
3.70k
  if (m_stop_hooks.empty())
2894
3.67k
    return false;
2895
2896
  // If there aren't any active stop hooks, don't bother either.
2897
30
  bool any_active_hooks = false;
2898
30
  for (auto hook : m_stop_hooks) {
2899
30
    if (hook.second->IsActive()) {
2900
30
      any_active_hooks = true;
2901
30
      break;
2902
30
    }
2903
30
  }
2904
30
  if (!any_active_hooks)
2905
0
    return false;
2906
2907
  // Make sure we check that we are not stopped because of us running a user
2908
  // expression since in that case we do not want to run the stop-hooks. Note,
2909
  // you can't just check whether the last stop was for a User Expression,
2910
  // because breakpoint commands get run before stop hooks, and one of them
2911
  // might have run an expression. You have to ensure you run the stop hooks
2912
  // once per natural stop.
2913
30
  uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
2914
30
  if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
2915
0
    return false;
2916
2917
30
  m_latest_stop_hook_id = last_natural_stop;
2918
2919
30
  std::vector<ExecutionContext> exc_ctx_with_reasons;
2920
2921
30
  ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2922
30
  size_t num_threads = cur_threadlist.GetSize();
2923
60
  for (size_t i = 0; i < num_threads; 
i++30
) {
2924
30
    lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2925
30
    if (cur_thread_sp->ThreadStoppedForAReason()) {
2926
30
      lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2927
30
      exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2928
30
                                        cur_frame_sp.get());
2929
30
    }
2930
30
  }
2931
2932
  // If no threads stopped for a reason, don't run the stop-hooks.
2933
30
  size_t num_exe_ctx = exc_ctx_with_reasons.size();
2934
30
  if (num_exe_ctx == 0)
2935
0
    return false;
2936
2937
30
  StreamSP output_sp = m_debugger.GetAsyncOutputStream();
2938
2939
30
  bool auto_continue = false;
2940
30
  bool hooks_ran = false;
2941
30
  bool print_hook_header = (m_stop_hooks.size() != 1);
2942
30
  bool print_thread_header = (num_exe_ctx != 1);
2943
30
  bool should_stop = false;
2944
30
  bool somebody_restarted = false;
2945
2946
30
  for (auto stop_entry : m_stop_hooks) {
2947
30
    StopHookSP cur_hook_sp = stop_entry.second;
2948
30
    if (!cur_hook_sp->IsActive())
2949
0
      continue;
2950
2951
30
    bool any_thread_matched = false;
2952
30
    for (auto exc_ctx : exc_ctx_with_reasons) {
2953
      // We detect somebody restarted in the stop-hook loop, and broke out of
2954
      // that loop back to here.  So break out of here too.
2955
30
      if (somebody_restarted)
2956
0
        break;
2957
2958
30
      if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2959
13
        continue;
2960
2961
      // We only consult the auto-continue for a stop hook if it matched the
2962
      // specifier.
2963
17
      auto_continue |= cur_hook_sp->GetAutoContinue();
2964
2965
17
      if (!hooks_ran)
2966
17
        hooks_ran = true;
2967
2968
17
      if (print_hook_header && 
!any_thread_matched0
) {
2969
0
        StreamString s;
2970
0
        cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
2971
0
        if (s.GetSize() != 0)
2972
0
          output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2973
0
                            s.GetData());
2974
0
        else
2975
0
          output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2976
0
        any_thread_matched = true;
2977
0
      }
2978
2979
17
      if (print_thread_header)
2980
0
        output_sp->Printf("-- Thread %d\n",
2981
0
                          exc_ctx.GetThreadPtr()->GetIndexID());
2982
2983
17
      StopHook::StopHookResult this_result =
2984
17
          cur_hook_sp->HandleStop(exc_ctx, output_sp);
2985
17
      bool this_should_stop = true;
2986
2987
17
      switch (this_result) {
2988
16
      case StopHook::StopHookResult::KeepStopped:
2989
        // If this hook is set to auto-continue that should override the
2990
        // HandleStop result...
2991
16
        if (cur_hook_sp->GetAutoContinue())
2992
1
          this_should_stop = false;
2993
15
        else
2994
15
          this_should_stop = true;
2995
2996
16
        break;
2997
1
      case StopHook::StopHookResult::RequestContinue:
2998
1
        this_should_stop = false;
2999
1
        break;
3000
0
      case StopHook::StopHookResult::AlreadyContinued:
3001
        // We don't have a good way to prohibit people from restarting the
3002
        // target willy nilly in a stop hook.  If the hook did so, give a
3003
        // gentle suggestion here and bag out if the hook processing.
3004
0
        output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3005
0
                          " set the program running.\n"
3006
0
                          "  Consider using '-G true' to make "
3007
0
                          "stop hooks auto-continue.\n",
3008
0
                          cur_hook_sp->GetID());
3009
0
        somebody_restarted = true;
3010
0
        break;
3011
17
      }
3012
      // If we're already restarted, stop processing stop hooks.
3013
      // FIXME: if we are doing non-stop mode for real, we would have to
3014
      // check that OUR thread was restarted, otherwise we should keep
3015
      // processing stop hooks.
3016
17
      if (somebody_restarted)
3017
0
        break;
3018
3019
      // If anybody wanted to stop, we should all stop.
3020
17
      if (!should_stop)
3021
17
        should_stop = this_should_stop;
3022
17
    }
3023
30
  }
3024
3025
30
  output_sp->Flush();
3026
3027
  // If one of the commands in the stop hook already restarted the target,
3028
  // report that fact.
3029
30
  if (somebody_restarted)
3030
0
    return true;
3031
3032
  // Finally, if auto-continue was requested, do it now:
3033
  // We only compute should_stop against the hook results if a hook got to run
3034
  // which is why we have to do this conjoint test.
3035
30
  if ((hooks_ran && 
!should_stop17
) ||
auto_continue28
) {
3036
2
    Log *log = GetLog(LLDBLog::Process);
3037
2
    Status error = m_process_sp->PrivateResume();
3038
2
    if (error.Success()) {
3039
2
      LLDB_LOG(log, "Resuming from RunStopHooks");
3040
2
      return true;
3041
2
    } else {
3042
0
      LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3043
0
      return false;
3044
0
    }
3045
2
  }
3046
3047
28
  return false;
3048
30
}
3049
3050
188k
TargetProperties &Target::GetGlobalProperties() {
3051
  // NOTE: intentional leak so we don't crash if global destructor chain gets
3052
  // called as other threads still use the result of this function
3053
188k
  static TargetProperties *g_settings_ptr =
3054
188k
      new TargetProperties(nullptr);
3055
188k
  return *g_settings_ptr;
3056
188k
}
3057
3058
9
Status Target::Install(ProcessLaunchInfo *launch_info) {
3059
9
  Status error;
3060
9
  PlatformSP platform_sp(GetPlatform());
3061
9
  if (platform_sp) {
3062
9
    if (platform_sp->IsRemote()) {
3063
1
      if (platform_sp->IsConnected()) {
3064
        // Install all files that have an install path when connected to a
3065
        // remote platform. If target.auto-install-main-executable is set then
3066
        // also install the main executable even if it does not have an explicit
3067
        // install path specified.
3068
1
        const ModuleList &modules = GetImages();
3069
1
        const size_t num_images = modules.GetSize();
3070
43
        for (size_t idx = 0; idx < num_images; 
++idx42
) {
3071
42
          ModuleSP module_sp(modules.GetModuleAtIndex(idx));
3072
42
          if (module_sp) {
3073
42
            const bool is_main_executable = module_sp == GetExecutableModule();
3074
42
            FileSpec local_file(module_sp->GetFileSpec());
3075
42
            if (local_file) {
3076
42
              FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
3077
42
              if (!remote_file) {
3078
42
                if (is_main_executable && 
GetAutoInstallMainExecutable()1
) {
3079
                  // Automatically install the main executable.
3080
0
                  remote_file = platform_sp->GetRemoteWorkingDirectory();
3081
0
                  remote_file.AppendPathComponent(
3082
0
                      module_sp->GetFileSpec().GetFilename().GetCString());
3083
0
                }
3084
42
              }
3085
42
              if (remote_file) {
3086
0
                error = platform_sp->Install(local_file, remote_file);
3087
0
                if (error.Success()) {
3088
0
                  module_sp->SetPlatformFileSpec(remote_file);
3089
0
                  if (is_main_executable) {
3090
0
                    platform_sp->SetFilePermissions(remote_file, 0700);
3091
0
                    if (launch_info)
3092
0
                      launch_info->SetExecutableFile(remote_file, false);
3093
0
                  }
3094
0
                } else
3095
0
                  break;
3096
0
              }
3097
42
            }
3098
42
          }
3099
42
        }
3100
1
      }
3101
1
    }
3102
9
  }
3103
9
  return error;
3104
9
}
3105
3106
bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
3107
1.23k
                                uint32_t stop_id) {
3108
1.23k
  return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
3109
1.23k
}
3110
3111
bool Target::ResolveFileAddress(lldb::addr_t file_addr,
3112
2
                                Address &resolved_addr) {
3113
2
  return m_images.ResolveFileAddress(file_addr, resolved_addr);
3114
2
}
3115
3116
bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
3117
                                   addr_t new_section_load_addr,
3118
366k
                                   bool warn_multiple) {
3119
366k
  const addr_t old_section_load_addr =
3120
366k
      m_section_load_history.GetSectionLoadAddress(
3121
366k
          SectionLoadHistory::eStopIDNow, section_sp);
3122
366k
  if (old_section_load_addr != new_section_load_addr) {
3123
343k
    uint32_t stop_id = 0;
3124
343k
    ProcessSP process_sp(GetProcessSP());
3125
343k
    if (process_sp)
3126
343k
      stop_id = process_sp->GetStopID();
3127
13
    else
3128
13
      stop_id = m_section_load_history.GetLastStopID();
3129
343k
    if (m_section_load_history.SetSectionLoadAddress(
3130
343k
            stop_id, section_sp, new_section_load_addr, warn_multiple))
3131
343k
      return true; // Return true if the section load address was changed...
3132
343k
  }
3133
23.8k
  return false; // Return false to indicate nothing changed
3134
366k
}
3135
3136
2.26k
size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3137
2.26k
  size_t section_unload_count = 0;
3138
2.26k
  size_t num_modules = module_list.GetSize();
3139
113k
  for (size_t i = 0; i < num_modules; 
++i111k
) {
3140
111k
    section_unload_count +=
3141
111k
        UnloadModuleSections(module_list.GetModuleAtIndex(i));
3142
111k
  }
3143
2.26k
  return section_unload_count;
3144
2.26k
}
3145
3146
111k
size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
3147
111k
  uint32_t stop_id = 0;
3148
111k
  ProcessSP process_sp(GetProcessSP());
3149
111k
  if (process_sp)
3150
110k
    stop_id = process_sp->GetStopID();
3151
253
  else
3152
253
    stop_id = m_section_load_history.GetLastStopID();
3153
111k
  SectionList *sections = module_sp->GetSectionList();
3154
111k
  size_t section_unload_count = 0;
3155
111k
  if (sections) {
3156
111k
    const uint32_t num_sections = sections->GetNumSections(0);
3157
457k
    for (uint32_t i = 0; i < num_sections; 
++i346k
) {
3158
346k
      section_unload_count += m_section_load_history.SetSectionUnloaded(
3159
346k
          stop_id, sections->GetSectionAtIndex(i));
3160
346k
    }
3161
111k
  }
3162
111k
  return section_unload_count;
3163
111k
}
3164
3165
343k
bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
3166
343k
  uint32_t stop_id = 0;
3167
343k
  ProcessSP process_sp(GetProcessSP());
3168
343k
  if (process_sp)
3169
343k
    stop_id = process_sp->GetStopID();
3170
0
  else
3171
0
    stop_id = m_section_load_history.GetLastStopID();
3172
343k
  return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3173
343k
}
3174
3175
bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
3176
0
                                addr_t load_addr) {
3177
0
  uint32_t stop_id = 0;
3178
0
  ProcessSP process_sp(GetProcessSP());
3179
0
  if (process_sp)
3180
0
    stop_id = process_sp->GetStopID();
3181
0
  else
3182
0
    stop_id = m_section_load_history.GetLastStopID();
3183
0
  return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3184
0
                                                   load_addr);
3185
0
}
3186
3187
2.15k
void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
3188
3189
2.13k
void Target::SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info) {
3190
2.13k
  if (process_info.IsScriptedProcess()) {
3191
    // Only copy scripted process launch options.
3192
4
    ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3193
4
        GetGlobalProperties().GetProcessLaunchInfo());
3194
4
    default_launch_info.SetProcessPluginName("ScriptedProcess");
3195
4
    default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3196
4
    SetProcessLaunchInfo(default_launch_info);
3197
4
  }
3198
2.13k
}
3199
3200
2.13k
Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
3201
2.13k
  m_stats.SetLaunchOrAttachTime();
3202
2.13k
  Status error;
3203
2.13k
  Log *log = GetLog(LLDBLog::Target);
3204
3205
2.13k
  LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3206
2.13k
            launch_info.GetExecutableFile().GetPath().c_str());
3207
3208
2.13k
  StateType state = eStateInvalid;
3209
3210
  // Scope to temporarily get the process state in case someone has manually
3211
  // remotely connected already to a process and we can skip the platform
3212
  // launching.
3213
2.13k
  {
3214
2.13k
    ProcessSP process_sp(GetProcessSP());
3215
3216
2.13k
    if (process_sp) {
3217
160
      state = process_sp->GetState();
3218
160
      LLDB_LOGF(log,
3219
160
                "Target::%s the process exists, and its current state is %s",
3220
160
                __FUNCTION__, StateAsCString(state));
3221
1.97k
    } else {
3222
1.97k
      LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3223
1.97k
                __FUNCTION__);
3224
1.97k
    }
3225
2.13k
  }
3226
3227
2.13k
  launch_info.GetFlags().Set(eLaunchFlagDebug);
3228
3229
2.13k
  SaveScriptedLaunchInfo(launch_info);
3230
3231
  // Get the value of synchronous execution here.  If you wait till after you
3232
  // have started to run, then you could have hit a breakpoint, whose command
3233
  // might switch the value, and then you'll pick up that incorrect value.
3234
2.13k
  Debugger &debugger = GetDebugger();
3235
2.13k
  const bool synchronous_execution =
3236
2.13k
      debugger.GetCommandInterpreter().GetSynchronous();
3237
3238
2.13k
  PlatformSP platform_sp(GetPlatform());
3239
3240
2.13k
  FinalizeFileActions(launch_info);
3241
3242
2.13k
  if (state == eStateConnected) {
3243
8
    if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3244
0
      error.SetErrorString(
3245
0
          "can't launch in tty when launching through a remote connection");
3246
0
      return error;
3247
0
    }
3248
8
  }
3249
3250
2.13k
  if (!launch_info.GetArchitecture().IsValid())
3251
812
    launch_info.GetArchitecture() = GetArchitecture();
3252
3253
  // Hijacking events of the process to be created to be sure that all events
3254
  // until the first stop are intercepted (in case if platform doesn't define
3255
  // its own hijacking listener or if the process is created by the target
3256
  // manually, without the platform).
3257
2.13k
  if (!launch_info.GetHijackListener())
3258
2.13k
    launch_info.SetHijackListener(Listener::MakeListener(
3259
2.13k
        Process::LaunchSynchronousHijackListenerName.data()));
3260
3261
  // If we're not already connected to the process, and if we have a platform
3262
  // that can launch a process for debugging, go ahead and do that here.
3263
2.13k
  if (state != eStateConnected && 
platform_sp2.12k
&&
3264
2.13k
      
platform_sp->CanDebugProcess()2.12k
&&
!launch_info.IsScriptedProcess()2.12k
) {
3265
2.12k
    LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3266
2.12k
              __FUNCTION__);
3267
3268
    // If there was a previous process, delete it before we make the new one.
3269
    // One subtle point, we delete the process before we release the reference
3270
    // to m_process_sp.  That way even if we are the last owner, the process
3271
    // will get Finalized before it gets destroyed.
3272
2.12k
    DeleteCurrentProcess();
3273
3274
2.12k
    m_process_sp =
3275
2.12k
        GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3276
3277
2.12k
  } else {
3278
11
    LLDB_LOGF(log,
3279
11
              "Target::%s the platform doesn't know how to debug a "
3280
11
              "process, getting a process plugin to do this for us.",
3281
11
              __FUNCTION__);
3282
3283
11
    if (state == eStateConnected) {
3284
8
      assert(m_process_sp);
3285
8
    } else {
3286
      // Use a Process plugin to construct the process.
3287
3
      CreateProcess(launch_info.GetListener(),
3288
3
                    launch_info.GetProcessPluginName(), nullptr, false);
3289
3
    }
3290
3291
    // Since we didn't have a platform launch the process, launch it here.
3292
11
    if (m_process_sp) {
3293
10
      m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3294
10
      m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3295
10
      error = m_process_sp->Launch(launch_info);
3296
10
    }
3297
11
  }
3298
3299
2.13k
  if (!m_process_sp && 
error.Success()4
)
3300
1
    error.SetErrorString("failed to launch or debug process");
3301
3302
2.13k
  if (!error.Success())
3303
8
    return error;
3304
3305
2.12k
  bool rebroadcast_first_stop =
3306
2.12k
      !synchronous_execution &&
3307
2.12k
      
launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)32
;
3308
3309
2.12k
  assert(launch_info.GetHijackListener());
3310
3311
2.12k
  EventSP first_stop_event_sp;
3312
2.12k
  state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3313
2.12k
                                             rebroadcast_first_stop,
3314
2.12k
                                             launch_info.GetHijackListener());
3315
2.12k
  m_process_sp->RestoreProcessEvents();
3316
3317
2.12k
  if (rebroadcast_first_stop) {
3318
2
    assert(first_stop_event_sp);
3319
2
    m_process_sp->BroadcastEvent(first_stop_event_sp);
3320
2
    return error;
3321
2
  }
3322
3323
2.12k
  switch (state) {
3324
2.12k
  case eStateStopped: {
3325
2.12k
    if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3326
11
      break;
3327
2.11k
    if (synchronous_execution)
3328
      // Now we have handled the stop-from-attach, and we are just
3329
      // switching to a synchronous resume.  So we should switch to the
3330
      // SyncResume hijacker.
3331
2.08k
      m_process_sp->ResumeSynchronous(stream);
3332
30
    else
3333
30
      error = m_process_sp->Resume();
3334
2.11k
    if (!error.Success()) {
3335
0
      Status error2;
3336
0
      error2.SetErrorStringWithFormat(
3337
0
          "process resume at entry point failed: %s", error.AsCString());
3338
0
      error = error2;
3339
0
    }
3340
2.11k
  } break;
3341
0
  case eStateExited: {
3342
0
    bool with_shell = !!launch_info.GetShell();
3343
0
    const int exit_status = m_process_sp->GetExitStatus();
3344
0
    const char *exit_desc = m_process_sp->GetExitDescription();
3345
0
    std::string desc;
3346
0
    if (exit_desc && exit_desc[0])
3347
0
      desc = " (" + std::string(exit_desc) + ')';
3348
0
    if (with_shell)
3349
0
      error.SetErrorStringWithFormat(
3350
0
          "process exited with status %i%s\n"
3351
0
          "'r' and 'run' are aliases that default to launching through a "
3352
0
          "shell.\n"
3353
0
          "Try launching without going through a shell by using "
3354
0
          "'process launch'.",
3355
0
          exit_status, desc.c_str());
3356
0
    else
3357
0
      error.SetErrorStringWithFormat("process exited with status %i%s",
3358
0
                                     exit_status, desc.c_str());
3359
0
  } break;
3360
0
  default:
3361
0
    error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
3362
0
                                   StateAsCString(state));
3363
0
    break;
3364
2.12k
  }
3365
2.12k
  return error;
3366
2.12k
}
3367
3368
0
void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3369
3370
0
TraceSP Target::GetTrace() { return m_trace_sp; }
3371
3372
8
llvm::Expected<TraceSP> Target::CreateTrace() {
3373
8
  if (!m_process_sp)
3374
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
3375
0
                                   "A process is required for tracing");
3376
8
  if (m_trace_sp)
3377
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
3378
0
                                   "A trace already exists for the target");
3379
3380
8
  llvm::Expected<TraceSupportedResponse> trace_type =
3381
8
      m_process_sp->TraceSupported();
3382
8
  if (!trace_type)
3383
8
    return llvm::createStringError(
3384
8
        llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3385
8
        llvm::toString(trace_type.takeError()).c_str());
3386
0
  if (llvm::Expected<TraceSP> trace_sp =
3387
0
          Trace::FindPluginForLiveProcess(trace_type->name, *m_process_sp))
3388
0
    m_trace_sp = *trace_sp;
3389
0
  else
3390
0
    return llvm::createStringError(
3391
0
        llvm::inconvertibleErrorCode(),
3392
0
        "Couldn't create a Trace object for the process. %s",
3393
0
        llvm::toString(trace_sp.takeError()).c_str());
3394
0
  return m_trace_sp;
3395
0
}
3396
3397
8
llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3398
8
  if (m_trace_sp)
3399
0
    return m_trace_sp;
3400
8
  return CreateTrace();
3401
8
}
3402
3403
27
Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3404
27
  m_stats.SetLaunchOrAttachTime();
3405
27
  auto state = eStateInvalid;
3406
27
  auto process_sp = GetProcessSP();
3407
27
  if (process_sp) {
3408
2
    state = process_sp->GetState();
3409
2
    if (process_sp->IsAlive() && 
state != eStateConnected1
) {
3410
0
      if (state == eStateAttaching)
3411
0
        return Status("process attach is in progress");
3412
0
      return Status("a process is already being debugged");
3413
0
    }
3414
2
  }
3415
3416
27
  const ModuleSP old_exec_module_sp = GetExecutableModule();
3417
3418
  // If no process info was specified, then use the target executable name as
3419
  // the process to attach to by default
3420
27
  if (!attach_info.ProcessInfoSpecified()) {
3421
0
    if (old_exec_module_sp)
3422
0
      attach_info.GetExecutableFile().SetFilename(
3423
0
            old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3424
3425
0
    if (!attach_info.ProcessInfoSpecified()) {
3426
0
      return Status("no process specified, create a target with a file, or "
3427
0
                    "specify the --pid or --name");
3428
0
    }
3429
0
  }
3430
3431
27
  const auto platform_sp =
3432
27
      GetDebugger().GetPlatformList().GetSelectedPlatform();
3433
27
  ListenerSP hijack_listener_sp;
3434
27
  const bool async = attach_info.GetAsync();
3435
27
  if (!async) {
3436
27
    hijack_listener_sp = Listener::MakeListener(
3437
27
        Process::AttachSynchronousHijackListenerName.data());
3438
27
    attach_info.SetHijackListener(hijack_listener_sp);
3439
27
  }
3440
3441
27
  Status error;
3442
27
  if (state != eStateConnected && 
platform_sp != nullptr26
&&
3443
27
      
platform_sp->CanDebugProcess()26
&&
!attach_info.IsScriptedProcess()26
) {
3444
25
    SetPlatform(platform_sp);
3445
25
    process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3446
25
  } else {
3447
2
    if (state != eStateConnected) {
3448
1
      SaveScriptedLaunchInfo(attach_info);
3449
1
      llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3450
1
      process_sp =
3451
1
          CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3452
1
                        plugin_name, nullptr, false);
3453
1
      if (!process_sp) {
3454
0
        error.SetErrorStringWithFormatv(
3455
0
            "failed to create process using plugin '{0}'",
3456
0
            plugin_name.empty() ? "<empty>" : plugin_name);
3457
0
        return error;
3458
0
      }
3459
1
    }
3460
2
    if (hijack_listener_sp)
3461
2
      process_sp->HijackProcessEvents(hijack_listener_sp);
3462
2
    error = process_sp->Attach(attach_info);
3463
2
  }
3464
3465
27
  if (error.Success() && 
process_sp26
) {
3466
26
    if (async) {
3467
0
      process_sp->RestoreProcessEvents();
3468
26
    } else {
3469
      // We are stopping all the way out to the user, so update selected frames.
3470
26
      state = process_sp->WaitForProcessToStop(
3471
26
          std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3472
26
          true, SelectMostRelevantFrame);
3473
26
      process_sp->RestoreProcessEvents();
3474
3475
26
      if (state != eStateStopped) {
3476
2
        const char *exit_desc = process_sp->GetExitDescription();
3477
2
        if (exit_desc)
3478
2
          error.SetErrorStringWithFormat("%s", exit_desc);
3479
0
        else
3480
0
          error.SetErrorString(
3481
0
              "process did not stop (no such process or permission problem?)");
3482
2
        process_sp->Destroy(false);
3483
2
      }
3484
26
    }
3485
26
  }
3486
27
  return error;
3487
27
}
3488
3489
2.13k
void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3490
2.13k
  Log *log = GetLog(LLDBLog::Process);
3491
3492
  // Finalize the file actions, and if none were given, default to opening up a
3493
  // pseudo terminal
3494
2.13k
  PlatformSP platform_sp = GetPlatform();
3495
2.13k
  const bool default_to_use_pty =
3496
2.13k
      m_platform_sp ? m_platform_sp->IsHost() : 
false0
;
3497
2.13k
  LLDB_LOG(
3498
2.13k
      log,
3499
2.13k
      "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3500
2.13k
      bool(platform_sp),
3501
2.13k
      platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3502
2.13k
      default_to_use_pty);
3503
3504
  // If nothing for stdin or stdout or stderr was specified, then check the
3505
  // process for any default settings that were set with "settings set"
3506
2.13k
  if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3507
2.13k
      
info.GetFileActionForFD(STDOUT_FILENO) == nullptr5
||
3508
2.13k
      
info.GetFileActionForFD(STDERR_FILENO) == nullptr4
) {
3509
2.13k
    LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3510
2.13k
                  "default handling");
3511
3512
2.13k
    if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3513
      // Do nothing, if we are launching in a remote terminal no file actions
3514
      // should be done at all.
3515
0
      return;
3516
0
    }
3517
3518
2.13k
    if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3519
1
      LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3520
1
                    "for stdin, stdout and stderr");
3521
1
      info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3522
1
      info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3523
1
      info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3524
2.12k
    } else {
3525
      // Check for any values that might have gotten set with any of: (lldb)
3526
      // settings set target.input-path (lldb) settings set target.output-path
3527
      // (lldb) settings set target.error-path
3528
2.12k
      FileSpec in_file_spec;
3529
2.12k
      FileSpec out_file_spec;
3530
2.12k
      FileSpec err_file_spec;
3531
      // Only override with the target settings if we don't already have an
3532
      // action for in, out or error
3533
2.12k
      if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3534
2.12k
        in_file_spec = GetStandardInputPath();
3535
2.12k
      if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3536
2.02k
        out_file_spec = GetStandardOutputPath();
3537
2.12k
      if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3538
2.12k
        err_file_spec = GetStandardErrorPath();
3539
3540
2.12k
      LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3541
2.12k
               in_file_spec, out_file_spec, err_file_spec);
3542
3543
2.12k
      if (in_file_spec) {
3544
0
        info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3545
0
        LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3546
0
      }
3547
3548
2.12k
      if (out_file_spec) {
3549
1
        info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3550
1
        LLDB_LOG(log, "appended stdout open file action for {0}",
3551
1
                 out_file_spec);
3552
1
      }
3553
3554
2.12k
      if (err_file_spec) {
3555
1
        info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3556
1
        LLDB_LOG(log, "appended stderr open file action for {0}",
3557
1
                 err_file_spec);
3558
1
      }
3559
3560
2.12k
      if (default_to_use_pty) {
3561
2.12k
        llvm::Error Err = info.SetUpPtyRedirection();
3562
2.12k
        LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3563
2.12k
      }
3564
2.12k
    }
3565
2.13k
  }
3566
2.13k
}
3567
3568
void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3569
25
                            LazyBool stop) {
3570
25
    if (name.empty())
3571
0
      return;
3572
    // Don't add a signal if all the actions are trivial:
3573
25
    if (pass == eLazyBoolCalculate && 
notify == eLazyBoolCalculate0
3574
25
        && 
stop == eLazyBoolCalculate0
)
3575
0
      return;
3576
3577
25
    auto& elem = m_dummy_signals[name];
3578
25
    elem.pass = pass;
3579
25
    elem.notify = notify;
3580
25
    elem.stop = stop;
3581
25
}
3582
3583
bool Target::UpdateSignalFromDummy(UnixSignalsSP signals_sp,
3584
13
                                          const DummySignalElement &elem) {
3585
13
  if (!signals_sp)
3586
0
    return false;
3587
3588
13
  int32_t signo
3589
13
      = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3590
13
  if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3591
3
    return false;
3592
3593
10
  if (elem.second.pass == eLazyBoolYes)
3594
0
    signals_sp->SetShouldSuppress(signo, false);
3595
10
  else if (elem.second.pass == eLazyBoolNo)
3596
10
    signals_sp->SetShouldSuppress(signo, true);
3597
3598
10
  if (elem.second.notify == eLazyBoolYes)
3599
7
    signals_sp->SetShouldNotify(signo, true);
3600
3
  else if (elem.second.notify == eLazyBoolNo)
3601
0
    signals_sp->SetShouldNotify(signo, false);
3602
3603
10
  if (elem.second.stop == eLazyBoolYes)
3604
7
    signals_sp->SetShouldStop(signo, true);
3605
3
  else if (elem.second.stop == eLazyBoolNo)
3606
0
    signals_sp->SetShouldStop(signo, false);
3607
10
  return true;
3608
13
}
3609
3610
bool Target::ResetSignalFromDummy(UnixSignalsSP signals_sp,
3611
2
                                          const DummySignalElement &elem) {
3612
2
  if (!signals_sp)
3613
0
    return false;
3614
2
  int32_t signo
3615
2
      = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3616
2
  if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3617
0
    return false;
3618
2
  bool do_pass = elem.second.pass != eLazyBoolCalculate;
3619
2
  bool do_stop = elem.second.stop != eLazyBoolCalculate;
3620
2
  bool do_notify = elem.second.notify != eLazyBoolCalculate;
3621
2
  signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3622
2
  return true;
3623
2
}
3624
3625
void Target::UpdateSignalsFromDummy(UnixSignalsSP signals_sp,
3626
2.26k
                                    StreamSP warning_stream_sp) {
3627
2.26k
  if (!signals_sp)
3628
0
    return;
3629
3630
2.26k
  for (const auto &elem : m_dummy_signals) {
3631
13
    if (!UpdateSignalFromDummy(signals_sp, elem))
3632
3
      warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3633
3
          elem.first().str().c_str());
3634
13
  }
3635
2.26k
}
3636
3637
2.88k
void Target::ClearDummySignals(Args &signal_names) {
3638
2.88k
  ProcessSP process_sp = GetProcessSP();
3639
  // The simplest case, delete them all with no process to update.
3640
2.88k
  if (signal_names.GetArgumentCount() == 0 && 
!process_sp2.88k
) {
3641
2.88k
    m_dummy_signals.clear();
3642
2.88k
    return;
3643
2.88k
  }
3644
3
  UnixSignalsSP signals_sp;
3645
3
  if (process_sp)
3646
2
    signals_sp = process_sp->GetUnixSignals();
3647
3648
3
  for (const Args::ArgEntry &entry : signal_names) {
3649
3
    const char *signal_name = entry.c_str();
3650
3
    auto elem = m_dummy_signals.find(signal_name);
3651
    // If we didn't find it go on.
3652
    // FIXME: Should I pipe error handling through here?
3653
3
    if (elem == m_dummy_signals.end()) {
3654
0
      continue;
3655
0
    }
3656
3
    if (signals_sp)
3657
2
      ResetSignalFromDummy(signals_sp, *elem);
3658
3
    m_dummy_signals.erase(elem);
3659
3
  }
3660
3
}
3661
3662
6
void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3663
6
  strm.Printf("NAME         PASS     STOP     NOTIFY\n");
3664
6
  strm.Printf("===========  =======  =======  =======\n");
3665
3666
12
  auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3667
12
    switch (lazy) {
3668
8
      case eLazyBoolCalculate: return "not set";
3669
0
      case eLazyBoolYes: return "true   ";
3670
4
      case eLazyBoolNo: return "false  ";
3671
12
    }
3672
0
    llvm_unreachable("Fully covered switch above!");
3673
0
  };
3674
6
  size_t num_args = signal_args.GetArgumentCount();
3675
7
  for (const auto &elem : m_dummy_signals) {
3676
7
    bool print_it = false;
3677
10
    for (size_t idx = 0; idx < num_args; 
idx++3
) {
3678
7
      if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3679
4
        print_it = true;
3680
4
        break;
3681
4
      }
3682
7
    }
3683
7
    if (print_it) {
3684
4
      strm.Printf("%-11s  ", elem.first().str().c_str());
3685
4
      strm.Printf("%s  %s  %s\n", str_for_lazy(elem.second.pass),
3686
4
                  str_for_lazy(elem.second.stop),
3687
4
                  str_for_lazy(elem.second.notify));
3688
4
    }
3689
7
  }
3690
6
}
3691
3692
// Target::StopHook
3693
Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3694
18
    : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3695
18
      m_thread_spec_up() {}
3696
3697
Target::StopHook::StopHook(const StopHook &rhs)
3698
0
    : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3699
0
      m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3700
0
      m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3701
0
  if (rhs.m_thread_spec_up)
3702
0
    m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3703
0
}
3704
3705
10
void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3706
10
  m_specifier_sp.reset(specifier);
3707
10
}
3708
3709
0
void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3710
0
  m_thread_spec_up.reset(specifier);
3711
0
}
3712
3713
30
bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) {
3714
30
  SymbolContextSpecifier *specifier = GetSpecifier();
3715
30
  if (!specifier)
3716
7
    return true;
3717
3718
23
  bool will_run = true;
3719
23
  if (exc_ctx.GetFramePtr())
3720
23
    will_run = GetSpecifier()->SymbolContextMatches(
3721
23
        exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3722
23
  if (will_run && 
GetThreadSpecifier() != nullptr10
)
3723
0
    will_run =
3724
0
        GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3725
3726
23
  return will_run;
3727
30
}
3728
3729
void Target::StopHook::GetDescription(Stream &s,
3730
12
                                      lldb::DescriptionLevel level) const {
3731
3732
  // For brief descriptions, only print the subclass description:
3733
12
  if (level == eDescriptionLevelBrief) {
3734
0
    GetSubclassDescription(s, level);
3735
0
    return;
3736
0
  }
3737
3738
12
  unsigned indent_level = s.GetIndentLevel();
3739
3740
12
  s.SetIndentLevel(indent_level + 2);
3741
3742
12
  s.Printf("Hook: %" PRIu64 "\n", GetID());
3743
12
  if (m_active)
3744
9
    s.Indent("State: enabled\n");
3745
3
  else
3746
3
    s.Indent("State: disabled\n");
3747
3748
12
  if (m_auto_continue)
3749
0
    s.Indent("AutoContinue on\n");
3750
3751
12
  if (m_specifier_sp) {
3752
9
    s.Indent();
3753
9
    s.PutCString("Specifier:\n");
3754
9
    s.SetIndentLevel(indent_level + 4);
3755
9
    m_specifier_sp->GetDescription(&s, level);
3756
9
    s.SetIndentLevel(indent_level + 2);
3757
9
  }
3758
3759
12
  if (m_thread_spec_up) {
3760
0
    StreamString tmp;
3761
0
    s.Indent("Thread:\n");
3762
0
    m_thread_spec_up->GetDescription(&tmp, level);
3763
0
    s.SetIndentLevel(indent_level + 4);
3764
0
    s.Indent(tmp.GetString());
3765
0
    s.PutCString("\n");
3766
0
    s.SetIndentLevel(indent_level + 2);
3767
0
  }
3768
12
  GetSubclassDescription(s, level);
3769
12
}
3770
3771
void Target::StopHookCommandLine::GetSubclassDescription(
3772
12
    Stream &s, lldb::DescriptionLevel level) const {
3773
  // The brief description just prints the first command.
3774
12
  if (level == eDescriptionLevelBrief) {
3775
0
    if (m_commands.GetSize() == 1)
3776
0
      s.PutCString(m_commands.GetStringAtIndex(0));
3777
0
    return;
3778
0
  }
3779
12
  s.Indent("Commands: \n");
3780
12
  s.SetIndentLevel(s.GetIndentLevel() + 4);
3781
12
  uint32_t num_commands = m_commands.GetSize();
3782
24
  for (uint32_t i = 0; i < num_commands; 
i++12
) {
3783
12
    s.Indent(m_commands.GetStringAtIndex(i));
3784
12
    s.PutCString("\n");
3785
12
  }
3786
12
  s.SetIndentLevel(s.GetIndentLevel() - 4);
3787
12
}
3788
3789
// Target::StopHookCommandLine
3790
1
void Target::StopHookCommandLine::SetActionFromString(const std::string &string) {
3791
1
  GetCommands().SplitIntoLines(string);
3792
1
}
3793
3794
void Target::StopHookCommandLine::SetActionFromStrings(
3795
7
    const std::vector<std::string> &strings) {
3796
7
  for (auto string : strings)
3797
7
    GetCommands().AppendString(string.c_str());
3798
7
}
3799
3800
Target::StopHook::StopHookResult
3801
Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx,
3802
11
                                        StreamSP output_sp) {
3803
11
  assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3804
11
                                   "with no target");
3805
3806
11
  if (!m_commands.GetSize())
3807
0
    return StopHookResult::KeepStopped;
3808
3809
11
  CommandReturnObject result(false);
3810
11
  result.SetImmediateOutputStream(output_sp);
3811
11
  result.SetInteractive(false);
3812
11
  Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3813
11
  CommandInterpreterRunOptions options;
3814
11
  options.SetStopOnContinue(true);
3815
11
  options.SetStopOnError(true);
3816
11
  options.SetEchoCommands(false);
3817
11
  options.SetPrintResults(true);
3818
11
  options.SetPrintErrors(true);
3819
11
  options.SetAddToHistory(false);
3820
3821
  // Force Async:
3822
11
  bool old_async = debugger.GetAsyncExecution();
3823
11
  debugger.SetAsyncExecution(true);
3824
11
  debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
3825
11
                                                  options, result);
3826
11
  debugger.SetAsyncExecution(old_async);
3827
11
  lldb::ReturnStatus status = result.GetStatus();
3828
11
  if (status == eReturnStatusSuccessContinuingNoResult ||
3829
11
      status == eReturnStatusSuccessContinuingResult)
3830
0
    return StopHookResult::AlreadyContinued;
3831
11
  return StopHookResult::KeepStopped;
3832
11
}
3833
3834
// Target::StopHookScripted
3835
Status Target::StopHookScripted::SetScriptCallback(
3836
10
    std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3837
10
  Status error;
3838
3839
10
  ScriptInterpreter *script_interp =
3840
10
      GetTarget()->GetDebugger().GetScriptInterpreter();
3841
10
  if (!script_interp) {
3842
0
    error.SetErrorString("No script interpreter installed.");
3843
0
    return error;
3844
0
  }
3845
3846
10
  m_class_name = class_name;
3847
10
  m_extra_args.SetObjectSP(extra_args_sp);
3848
3849
10
  m_implementation_sp = script_interp->CreateScriptedStopHook(
3850
10
      GetTarget(), m_class_name.c_str(), m_extra_args, error);
3851
3852
10
  return error;
3853
10
}
3854
3855
Target::StopHook::StopHookResult
3856
Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx,
3857
6
                                     StreamSP output_sp) {
3858
6
  assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3859
6
                                   "with no target");
3860
3861
6
  ScriptInterpreter *script_interp =
3862
6
      GetTarget()->GetDebugger().GetScriptInterpreter();
3863
6
  if (!script_interp)
3864
0
    return StopHookResult::KeepStopped;
3865
3866
6
  bool should_stop = script_interp->ScriptedStopHookHandleStop(
3867
6
      m_implementation_sp, exc_ctx, output_sp);
3868
3869
6
  return should_stop ? 
StopHookResult::KeepStopped5
3870
6
                     : 
StopHookResult::RequestContinue1
;
3871
6
}
3872
3873
void Target::StopHookScripted::GetSubclassDescription(
3874
0
    Stream &s, lldb::DescriptionLevel level) const {
3875
0
  if (level == eDescriptionLevelBrief) {
3876
0
    s.PutCString(m_class_name);
3877
0
    return;
3878
0
  }
3879
0
  s.Indent("Class:");
3880
0
  s.Printf("%s\n", m_class_name.c_str());
3881
3882
  // Now print the extra args:
3883
  // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3884
  // but that seems to rely on some printing plugin that doesn't exist.
3885
0
  if (!m_extra_args.IsValid())
3886
0
    return;
3887
0
  StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP();
3888
0
  if (!object_sp || !object_sp->IsValid())
3889
0
    return;
3890
3891
0
  StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3892
0
  if (!as_dict || !as_dict->IsValid())
3893
0
    return;
3894
3895
0
  uint32_t num_keys = as_dict->GetSize();
3896
0
  if (num_keys == 0)
3897
0
    return;
3898
3899
0
  s.Indent("Args:\n");
3900
0
  s.SetIndentLevel(s.GetIndentLevel() + 4);
3901
3902
0
  auto print_one_element = [&s](llvm::StringRef key,
3903
0
                                StructuredData::Object *object) {
3904
0
    s.Indent();
3905
0
    s.Format("{0} : {1}\n", key, object->GetStringValue());
3906
0
    return true;
3907
0
  };
3908
3909
0
  as_dict->ForEach(print_one_element);
3910
3911
0
  s.SetIndentLevel(s.GetIndentLevel() - 4);
3912
0
}
3913
3914
static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3915
    {
3916
        eNoDynamicValues,
3917
        "no-dynamic-values",
3918
        "Don't calculate the dynamic type of values",
3919
    },
3920
    {
3921
        eDynamicCanRunTarget,
3922
        "run-target",
3923
        "Calculate the dynamic type of values "
3924
        "even if you have to run the target.",
3925
    },
3926
    {
3927
        eDynamicDontRunTarget,
3928
        "no-run-target",
3929
        "Calculate the dynamic type of values, but don't run the target.",
3930
    },
3931
};
3932
3933
4.45k
OptionEnumValues lldb_private::GetDynamicValueTypes() {
3934
4.45k
  return OptionEnumValues(g_dynamic_value_types);
3935
4.45k
}
3936
3937
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3938
    {
3939
        eInlineBreakpointsNever,
3940
        "never",
3941
        "Never look for inline breakpoint locations (fastest). This setting "
3942
        "should only be used if you know that no inlining occurs in your"
3943
        "programs.",
3944
    },
3945
    {
3946
        eInlineBreakpointsHeaders,
3947
        "headers",
3948
        "Only check for inline breakpoint locations when setting breakpoints "
3949
        "in header files, but not when setting breakpoint in implementation "
3950
        "source files (default).",
3951
    },
3952
    {
3953
        eInlineBreakpointsAlways,
3954
        "always",
3955
        "Always look for inline breakpoint locations when setting file and "
3956
        "line breakpoints (slower but most accurate).",
3957
    },
3958
};
3959
3960
enum x86DisassemblyFlavor {
3961
  eX86DisFlavorDefault,
3962
  eX86DisFlavorIntel,
3963
  eX86DisFlavorATT
3964
};
3965
3966
static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3967
    {
3968
        eX86DisFlavorDefault,
3969
        "default",
3970
        "Disassembler default (currently att).",
3971
    },
3972
    {
3973
        eX86DisFlavorIntel,
3974
        "intel",
3975
        "Intel disassembler flavor.",
3976
    },
3977
    {
3978
        eX86DisFlavorATT,
3979
        "att",
3980
        "AT&T disassembler flavor.",
3981
    },
3982
};
3983
3984
static constexpr OptionEnumValueElement g_import_std_module_value_types[] = {
3985
    {
3986
        eImportStdModuleFalse,
3987
        "false",
3988
        "Never import the 'std' C++ module in the expression parser.",
3989
    },
3990
    {
3991
        eImportStdModuleFallback,
3992
        "fallback",
3993
        "Retry evaluating expressions with an imported 'std' C++ module if they"
3994
        " failed to parse without the module. This allows evaluating more "
3995
        "complex expressions involving C++ standard library types."
3996
    },
3997
    {
3998
        eImportStdModuleTrue,
3999
        "true",
4000
        "Always import the 'std' C++ module. This allows evaluating more "
4001
        "complex expressions involving C++ standard library types. This feature"
4002
        " is experimental."
4003
    },
4004
};
4005
4006
static constexpr OptionEnumValueElement
4007
    g_dynamic_class_info_helper_value_types[] = {
4008
        {
4009
            eDynamicClassInfoHelperAuto,
4010
            "auto",
4011
            "Automatically determine the most appropriate method for the "
4012
            "target OS.",
4013
        },
4014
        {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4015
         "Prefer using the realized classes struct."},
4016
        {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4017
         "Prefer using the CopyRealizedClassList API."},
4018
        {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4019
         "Prefer using the GetRealizedClassList API."},
4020
};
4021
4022
static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
4023
    {
4024
        Disassembler::eHexStyleC,
4025
        "c",
4026
        "C-style (0xffff).",
4027
    },
4028
    {
4029
        Disassembler::eHexStyleAsm,
4030
        "asm",
4031
        "Asm-style (0ffffh).",
4032
    },
4033
};
4034
4035
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
4036
    {
4037
        eLoadScriptFromSymFileTrue,
4038
        "true",
4039
        "Load debug scripts inside symbol files",
4040
    },
4041
    {
4042
        eLoadScriptFromSymFileFalse,
4043
        "false",
4044
        "Do not load debug scripts inside symbol files.",
4045
    },
4046
    {
4047
        eLoadScriptFromSymFileWarn,
4048
        "warn",
4049
        "Warn about debug scripts inside symbol files but do not load them.",
4050
    },
4051
};
4052
4053
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
4054
    {
4055
        eLoadCWDlldbinitTrue,
4056
        "true",
4057
        "Load .lldbinit files from current directory",
4058
    },
4059
    {
4060
        eLoadCWDlldbinitFalse,
4061
        "false",
4062
        "Do not load .lldbinit files from current directory",
4063
    },
4064
    {
4065
        eLoadCWDlldbinitWarn,
4066
        "warn",
4067
        "Warn about loading .lldbinit files from current directory",
4068
    },
4069
};
4070
4071
static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
4072
    {
4073
        eMemoryModuleLoadLevelMinimal,
4074
        "minimal",
4075
        "Load minimal information when loading modules from memory. Currently "
4076
        "this setting loads sections only.",
4077
    },
4078
    {
4079
        eMemoryModuleLoadLevelPartial,
4080
        "partial",
4081
        "Load partial information when loading modules from memory. Currently "
4082
        "this setting loads sections and function bounds.",
4083
    },
4084
    {
4085
        eMemoryModuleLoadLevelComplete,
4086
        "complete",
4087
        "Load complete information when loading modules from memory. Currently "
4088
        "this setting loads sections and all symbols.",
4089
    },
4090
};
4091
4092
#define LLDB_PROPERTIES_target
4093
#include "TargetProperties.inc"
4094
4095
enum {
4096
#define LLDB_PROPERTIES_target
4097
#include "TargetPropertiesEnum.inc"
4098
  ePropertyExperimental,
4099
};
4100
4101
class TargetOptionValueProperties
4102
    : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4103
public:
4104
3.95k
  TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4105
4106
  const Property *
4107
  GetPropertyAtIndex(size_t idx,
4108
3.74M
                     const ExecutionContext *exe_ctx = nullptr) const override {
4109
    // When getting the value for a key from the target options, we will always
4110
    // try and grab the setting from the current target if there is one. Else
4111
    // we just use the one from this instance.
4112
3.74M
    if (exe_ctx) {
4113
19.2k
      Target *target = exe_ctx->GetTargetPtr();
4114
19.2k
      if (target) {
4115
7.37k
        TargetOptionValueProperties *target_properties =
4116
7.37k
            static_cast<TargetOptionValueProperties *>(
4117
7.37k
                target->GetValueProperties().get());
4118
7.37k
        if (this != target_properties)
4119
527
          return target_properties->ProtectedGetPropertyAtIndex(idx);
4120
7.37k
      }
4121
19.2k
    }
4122
3.74M
    return ProtectedGetPropertyAtIndex(idx);
4123
3.74M
  }
4124
};
4125
4126
// TargetProperties
4127
#define LLDB_PROPERTIES_target_experimental
4128
#include "TargetProperties.inc"
4129
4130
enum {
4131
#define LLDB_PROPERTIES_target_experimental
4132
#include "TargetPropertiesEnum.inc"
4133
};
4134
4135
class TargetExperimentalOptionValueProperties
4136
    : public Cloneable<TargetExperimentalOptionValueProperties,
4137
                       OptionValueProperties> {
4138
public:
4139
  TargetExperimentalOptionValueProperties()
4140
12.9k
      : Cloneable(Properties::GetExperimentalSettingsName()) {}
4141
};
4142
4143
TargetExperimentalProperties::TargetExperimentalProperties()
4144
12.9k
    : Properties(OptionValuePropertiesSP(
4145
12.9k
          new TargetExperimentalOptionValueProperties())) {
4146
12.9k
  m_collection_sp->Initialize(g_target_experimental_properties);
4147
12.9k
}
4148
4149
// TargetProperties
4150
TargetProperties::TargetProperties(Target *target)
4151
12.9k
    : Properties(), m_launch_info(), m_target(target) {
4152
12.9k
  if (target) {
4153
9.02k
    m_collection_sp =
4154
9.02k
        OptionValueProperties::CreateLocalCopy(Target::GetGlobalProperties());
4155
4156
    // Set callbacks to update launch_info whenever "settins set" updated any
4157
    // of these properties
4158
9.02k
    m_collection_sp->SetValueChangedCallback(
4159
9.02k
        ePropertyArg0, [this] 
{ Arg0ValueChangedCallback(); }1
);
4160
9.02k
    m_collection_sp->SetValueChangedCallback(
4161
9.02k
        ePropertyRunArgs, [this] 
{ RunArgsValueChangedCallback(); }20
);
4162
9.02k
    m_collection_sp->SetValueChangedCallback(
4163
9.02k
        ePropertyEnvVars, [this] 
{ EnvVarsValueChangedCallback(); }8
);
4164
9.02k
    m_collection_sp->SetValueChangedCallback(
4165
9.02k
        ePropertyUnsetEnvVars, [this] 
{ EnvVarsValueChangedCallback(); }3
);
4166
9.02k
    m_collection_sp->SetValueChangedCallback(
4167
9.02k
        ePropertyInheritEnv, [this] 
{ EnvVarsValueChangedCallback(); }2
);
4168
9.02k
    m_collection_sp->SetValueChangedCallback(
4169
9.02k
        ePropertyInputPath, [this] 
{ InputPathValueChangedCallback(); }0
);
4170
9.02k
    m_collection_sp->SetValueChangedCallback(
4171
9.02k
        ePropertyOutputPath, [this] 
{ OutputPathValueChangedCallback(); }1
);
4172
9.02k
    m_collection_sp->SetValueChangedCallback(
4173
9.02k
        ePropertyErrorPath, [this] 
{ ErrorPathValueChangedCallback(); }1
);
4174
9.02k
    m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4175
50
      DetachOnErrorValueChangedCallback();
4176
50
    });
4177
9.02k
    m_collection_sp->SetValueChangedCallback(
4178
9.02k
        ePropertyDisableASLR, [this] 
{ DisableASLRValueChangedCallback(); }1
);
4179
9.02k
    m_collection_sp->SetValueChangedCallback(
4180
9.02k
        ePropertyInheritTCC, [this] 
{ InheritTCCValueChangedCallback(); }50
);
4181
9.02k
    m_collection_sp->SetValueChangedCallback(
4182
9.02k
        ePropertyDisableSTDIO, [this] 
{ DisableSTDIOValueChangedCallback(); }1
);
4183
4184
9.02k
    m_collection_sp->SetValueChangedCallback(
4185
9.02k
        ePropertySaveObjectsDir, [this] 
{ CheckJITObjectsDir(); }2
);
4186
9.02k
    m_experimental_properties_up =
4187
9.02k
        std::make_unique<TargetExperimentalProperties>();
4188
9.02k
    m_collection_sp->AppendProperty(
4189
9.02k
        Properties::GetExperimentalSettingsName(),
4190
9.02k
        "Experimental settings - setting these won't produce "
4191
9.02k
        "errors if the setting is not present.",
4192
9.02k
        true, m_experimental_properties_up->GetValueProperties());
4193
9.02k
  } else {
4194
3.95k
    m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4195
3.95k
    m_collection_sp->Initialize(g_target_properties);
4196
3.95k
    m_experimental_properties_up =
4197
3.95k
        std::make_unique<TargetExperimentalProperties>();
4198
3.95k
    m_collection_sp->AppendProperty(
4199
3.95k
        Properties::GetExperimentalSettingsName(),
4200
3.95k
        "Experimental settings - setting these won't produce "
4201
3.95k
        "errors if the setting is not present.",
4202
3.95k
        true, m_experimental_properties_up->GetValueProperties());
4203
3.95k
    m_collection_sp->AppendProperty(
4204
3.95k
        "process", "Settings specific to processes.", true,
4205
3.95k
        Process::GetGlobalProperties().GetValueProperties());
4206
3.95k
    m_collection_sp->SetValueChangedCallback(
4207
3.95k
        ePropertySaveObjectsDir, [this] 
{ CheckJITObjectsDir(); }2
);
4208
3.95k
  }
4209
12.9k
}
4210
4211
8.87k
TargetProperties::~TargetProperties() = default;
4212
4213
9.02k
void TargetProperties::UpdateLaunchInfoFromProperties() {
4214
9.02k
  Arg0ValueChangedCallback();
4215
9.02k
  RunArgsValueChangedCallback();
4216
9.02k
  EnvVarsValueChangedCallback();
4217
9.02k
  InputPathValueChangedCallback();
4218
9.02k
  OutputPathValueChangedCallback();
4219
9.02k
  ErrorPathValueChangedCallback();
4220
9.02k
  DetachOnErrorValueChangedCallback();
4221
9.02k
  DisableASLRValueChangedCallback();
4222
9.02k
  InheritTCCValueChangedCallback();
4223
9.02k
  DisableSTDIOValueChangedCallback();
4224
9.02k
}
4225
4226
bool TargetProperties::GetInjectLocalVariables(
4227
6.84k
    ExecutionContext *exe_ctx) const {
4228
6.84k
  const Property *exp_property =
4229
6.84k
      m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4230
6.84k
  OptionValueProperties *exp_values =
4231
6.84k
      exp_property->GetValue()->GetAsProperties();
4232
6.84k
  if (exp_values)
4233
6.84k
    return exp_values
4234
6.84k
        ->GetPropertyAtIndexAs<bool>(ePropertyInjectLocalVars, exe_ctx)
4235
6.84k
        .value_or(true);
4236
0
  else
4237
0
    return true;
4238
6.84k
}
4239
4240
void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
4241
0
                                               bool b) {
4242
0
  const Property *exp_property =
4243
0
      m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4244
0
  OptionValueProperties *exp_values =
4245
0
      exp_property->GetValue()->GetAsProperties();
4246
0
  if (exp_values)
4247
0
    exp_values->SetPropertyAtIndex(ePropertyInjectLocalVars, true, exe_ctx);
4248
0
}
4249
4250
6.34k
ArchSpec TargetProperties::GetDefaultArchitecture() const {
4251
6.34k
  const uint32_t idx = ePropertyDefaultArch;
4252
6.34k
  return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4253
6.34k
}
4254
4255
4
void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
4256
4
  const uint32_t idx = ePropertyDefaultArch;
4257
4
  SetPropertyAtIndex(idx, arch);
4258
4
}
4259
4260
2.19k
bool TargetProperties::GetMoveToNearestCode() const {
4261
2.19k
  const uint32_t idx = ePropertyMoveToNearestCode;
4262
2.19k
  return GetPropertyAtIndexAs<bool>(
4263
2.19k
      idx, g_target_properties[idx].default_uint_value != 0);
4264
2.19k
}
4265
4266
51.6k
lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
4267
51.6k
  const uint32_t idx = ePropertyPreferDynamic;
4268
51.6k
  return GetPropertyAtIndexAs<lldb::DynamicValueType>(
4269
51.6k
      idx, static_cast<lldb::DynamicValueType>(
4270
51.6k
               g_target_properties[idx].default_uint_value));
4271
51.6k
}
4272
4273
32
bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
4274
32
  const uint32_t idx = ePropertyPreferDynamic;
4275
32
  return SetPropertyAtIndex(idx, d);
4276
32
}
4277
4278
229k
bool TargetProperties::GetPreloadSymbols() const {
4279
229k
  if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
4280
229k
                          "Interrupted checking preload symbols")) {
4281
0
    return false;
4282
0
  }
4283
229k
  const uint32_t idx = ePropertyPreloadSymbols;
4284
229k
  return GetPropertyAtIndexAs<bool>(
4285
229k
      idx, g_target_properties[idx].default_uint_value != 0);
4286
229k
}
4287
4288
0
void TargetProperties::SetPreloadSymbols(bool b) {
4289
0
  const uint32_t idx = ePropertyPreloadSymbols;
4290
0
  SetPropertyAtIndex(idx, b);
4291
0
}
4292
4293
9.81k
bool TargetProperties::GetDisableASLR() const {
4294
9.81k
  const uint32_t idx = ePropertyDisableASLR;
4295
9.81k
  return GetPropertyAtIndexAs<bool>(
4296
9.81k
      idx, g_target_properties[idx].default_uint_value != 0);
4297
9.81k
}
4298
4299
5
void TargetProperties::SetDisableASLR(bool b) {
4300
5
  const uint32_t idx = ePropertyDisableASLR;
4301
5
  SetPropertyAtIndex(idx, b);
4302
5
}
4303
4304
9.86k
bool TargetProperties::GetInheritTCC() const {
4305
9.86k
  const uint32_t idx = ePropertyInheritTCC;
4306
9.86k
  return GetPropertyAtIndexAs<bool>(
4307
9.86k
      idx, g_target_properties[idx].default_uint_value != 0);
4308
9.86k
}
4309
4310
5
void TargetProperties::SetInheritTCC(bool b) {
4311
5
  const uint32_t idx = ePropertyInheritTCC;
4312
5
  SetPropertyAtIndex(idx, b);
4313
5
}
4314
4315
9.86k
bool TargetProperties::GetDetachOnError() const {
4316
9.86k
  const uint32_t idx = ePropertyDetachOnError;
4317
9.86k
  return GetPropertyAtIndexAs<bool>(
4318
9.86k
      idx, g_target_properties[idx].default_uint_value != 0);
4319
9.86k
}
4320
4321
5
void TargetProperties::SetDetachOnError(bool b) {
4322
5
  const uint32_t idx = ePropertyDetachOnError;
4323
5
  SetPropertyAtIndex(idx, b);
4324
5
}
4325
4326
9.81k
bool TargetProperties::GetDisableSTDIO() const {
4327
9.81k
  const uint32_t idx = ePropertyDisableSTDIO;
4328
9.81k
  return GetPropertyAtIndexAs<bool>(
4329
9.81k
      idx, g_target_properties[idx].default_uint_value != 0);
4330
9.81k
}
4331
4332
5
void TargetProperties::SetDisableSTDIO(bool b) {
4333
5
  const uint32_t idx = ePropertyDisableSTDIO;
4334
5
  SetPropertyAtIndex(idx, b);
4335
5
}
4336
4337
46.4k
const char *TargetProperties::GetDisassemblyFlavor() const {
4338
46.4k
  const uint32_t idx = ePropertyDisassemblyFlavor;
4339
46.4k
  const char *return_value;
4340
4341
46.4k
  x86DisassemblyFlavor flavor_value =
4342
46.4k
      GetPropertyAtIndexAs<x86DisassemblyFlavor>(
4343
46.4k
          idx, static_cast<x86DisassemblyFlavor>(
4344
46.4k
                   g_target_properties[idx].default_uint_value));
4345
4346
46.4k
  return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4347
46.4k
  return return_value;
4348
46.4k
}
4349
4350
1.15k
InlineStrategy TargetProperties::GetInlineStrategy() const {
4351
1.15k
  const uint32_t idx = ePropertyInlineStrategy;
4352
1.15k
  return GetPropertyAtIndexAs<InlineStrategy>(
4353
1.15k
      idx,
4354
1.15k
      static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4355
1.15k
}
4356
4357
9.81k
llvm::StringRef TargetProperties::GetArg0() const {
4358
9.81k
  const uint32_t idx = ePropertyArg0;
4359
9.81k
  return GetPropertyAtIndexAs<llvm::StringRef>(
4360
9.81k
      idx, g_target_properties[idx].default_cstr_value);
4361
9.81k
}
4362
4363
2.55k
void TargetProperties::SetArg0(llvm::StringRef arg) {
4364
2.55k
  const uint32_t idx = ePropertyArg0;
4365
2.55k
  SetPropertyAtIndex(idx, arg);
4366
2.55k
  m_launch_info.SetArg0(arg);
4367
2.55k
}
4368
4369
9.04k
bool TargetProperties::GetRunArguments(Args &args) const {
4370
9.04k
  const uint32_t idx = ePropertyRunArgs;
4371
9.04k
  return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4372
9.04k
}
4373
4374
30
void TargetProperties::SetRunArguments(const Args &args) {
4375
30
  const uint32_t idx = ePropertyRunArgs;
4376
30
  m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4377
30
  m_launch_info.GetArguments() = args;
4378
30
}
4379
4380
9.84k
Environment TargetProperties::ComputeEnvironment() const {
4381
9.84k
  Environment env;
4382
4383
9.84k
  if (m_target &&
4384
9.84k
      GetPropertyAtIndexAs<bool>(
4385
9.84k
          ePropertyInheritEnv,
4386
9.84k
          g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4387
9.83k
    if (auto platform_sp = m_target->GetPlatform()) {
4388
9.83k
      Environment platform_env = platform_sp->GetEnvironment();
4389
9.83k
      for (const auto &KV : platform_env)
4390
188k
        env[KV.first()] = KV.second;
4391
9.83k
    }
4392
9.83k
  }
4393
4394
9.84k
  Args property_unset_env;
4395
9.84k
  m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4396
9.84k
                                            property_unset_env);
4397
9.84k
  for (const auto &var : property_unset_env)
4398
9
    env.erase(var.ref());
4399
4400
9.84k
  Args property_env;
4401
9.84k
  m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4402
9.84k
  for (const auto &KV : Environment(property_env))
4403
51
    env[KV.first()] = KV.second;
4404
4405
9.84k
  return env;
4406
9.84k
}
4407
4408
805
Environment TargetProperties::GetEnvironment() const {
4409
805
  return ComputeEnvironment();
4410
805
}
4411
4412
0
Environment TargetProperties::GetInheritedEnvironment() const {
4413
0
  Environment environment;
4414
4415
0
  if (m_target == nullptr)
4416
0
    return environment;
4417
4418
0
  if (!GetPropertyAtIndexAs<bool>(
4419
0
          ePropertyInheritEnv,
4420
0
          g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4421
0
    return environment;
4422
4423
0
  PlatformSP platform_sp = m_target->GetPlatform();
4424
0
  if (platform_sp == nullptr)
4425
0
    return environment;
4426
4427
0
  Environment platform_environment = platform_sp->GetEnvironment();
4428
0
  for (const auto &KV : platform_environment)
4429
0
    environment[KV.first()] = KV.second;
4430
4431
0
  Args property_unset_environment;
4432
0
  m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4433
0
                                            property_unset_environment);
4434
0
  for (const auto &var : property_unset_environment)
4435
0
    environment.erase(var.ref());
4436
4437
0
  return environment;
4438
0
}
4439
4440
0
Environment TargetProperties::GetTargetEnvironment() const {
4441
0
  Args property_environment;
4442
0
  m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4443
0
                                            property_environment);
4444
0
  Environment environment;
4445
0
  for (const auto &KV : Environment(property_environment))
4446
0
    environment[KV.first()] = KV.second;
4447
4448
0
  return environment;
4449
0
}
4450
4451
5
void TargetProperties::SetEnvironment(Environment env) {
4452
  // TODO: Get rid of the Args intermediate step
4453
5
  const uint32_t idx = ePropertyEnvVars;
4454
5
  m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4455
5
}
4456
4457
1.77k
bool TargetProperties::GetSkipPrologue() const {
4458
1.77k
  const uint32_t idx = ePropertySkipPrologue;
4459
1.77k
  return GetPropertyAtIndexAs<bool>(
4460
1.77k
      idx, g_target_properties[idx].default_uint_value != 0);
4461
1.77k
}
4462
4463
22.5k
PathMappingList &TargetProperties::GetSourcePathMap() const {
4464
22.5k
  const uint32_t idx = ePropertySourceMap;
4465
22.5k
  OptionValuePathMappings *option_value =
4466
22.5k
      m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4467
22.5k
  assert(option_value);
4468
22.5k
  return option_value->GetCurrentValue();
4469
22.5k
}
4470
4471
110k
bool TargetProperties::GetAutoSourceMapRelative() const {
4472
110k
  const uint32_t idx = ePropertyAutoSourceMapRelative;
4473
110k
  return GetPropertyAtIndexAs<bool>(
4474
110k
      idx, g_target_properties[idx].default_uint_value != 0);
4475
110k
}
4476
4477
2.64k
void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
4478
2.64k
  const uint32_t idx = ePropertyExecutableSearchPaths;
4479
2.64k
  OptionValueFileSpecList *option_value =
4480
2.64k
      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4481
2.64k
  assert(option_value);
4482
2.64k
  option_value->AppendCurrentValue(dir);
4483
2.64k
}
4484
4485
230k
FileSpecList TargetProperties::GetExecutableSearchPaths() {
4486
230k
  const uint32_t idx = ePropertyExecutableSearchPaths;
4487
230k
  return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4488
230k
}
4489
4490
117k
FileSpecList TargetProperties::GetDebugFileSearchPaths() {
4491
117k
  const uint32_t idx = ePropertyDebugFileSearchPaths;
4492
117k
  return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4493
117k
}
4494
4495
1.24k
FileSpecList TargetProperties::GetClangModuleSearchPaths() {
4496
1.24k
  const uint32_t idx = ePropertyClangModuleSearchPaths;
4497
1.24k
  return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4498
1.24k
}
4499
4500
14.3k
bool TargetProperties::GetEnableAutoImportClangModules() const {
4501
14.3k
  const uint32_t idx = ePropertyAutoImportClangModules;
4502
14.3k
  return GetPropertyAtIndexAs<bool>(
4503
14.3k
      idx, g_target_properties[idx].default_uint_value != 0);
4504
14.3k
}
4505
4506
7.52k
ImportStdModule TargetProperties::GetImportStdModule() const {
4507
7.52k
  const uint32_t idx = ePropertyImportStdModule;
4508
7.52k
  return GetPropertyAtIndexAs<ImportStdModule>(
4509
7.52k
      idx, static_cast<ImportStdModule>(
4510
7.52k
               g_target_properties[idx].default_uint_value));
4511
7.52k
}
4512
4513
992
DynamicClassInfoHelper TargetProperties::GetDynamicClassInfoHelper() const {
4514
992
  const uint32_t idx = ePropertyDynamicClassInfoHelper;
4515
992
  return GetPropertyAtIndexAs<DynamicClassInfoHelper>(
4516
992
      idx, static_cast<DynamicClassInfoHelper>(
4517
992
               g_target_properties[idx].default_uint_value));
4518
992
}
4519
4520
3.83k
bool TargetProperties::GetEnableAutoApplyFixIts() const {
4521
3.83k
  const uint32_t idx = ePropertyAutoApplyFixIts;
4522
3.83k
  return GetPropertyAtIndexAs<bool>(
4523
3.83k
      idx, g_target_properties[idx].default_uint_value != 0);
4524
3.83k
}
4525
4526
3.83k
uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
4527
3.83k
  const uint32_t idx = ePropertyRetriesWithFixIts;
4528
3.83k
  return GetPropertyAtIndexAs<uint64_t>(
4529
3.83k
      idx, g_target_properties[idx].default_uint_value);
4530
3.83k
}
4531
4532
314
bool TargetProperties::GetEnableNotifyAboutFixIts() const {
4533
314
  const uint32_t idx = ePropertyNotifyAboutFixIts;
4534
314
  return GetPropertyAtIndexAs<bool>(
4535
314
      idx, g_target_properties[idx].default_uint_value != 0);
4536
314
}
4537
4538
5.92k
FileSpec TargetProperties::GetSaveJITObjectsDir() const {
4539
5.92k
  const uint32_t idx = ePropertySaveObjectsDir;
4540
5.92k
  return GetPropertyAtIndexAs<FileSpec>(idx, {});
4541
5.92k
}
4542
4543
4
void TargetProperties::CheckJITObjectsDir() {
4544
4
  FileSpec new_dir = GetSaveJITObjectsDir();
4545
4
  if (!new_dir)
4546
2
    return;
4547
4548
2
  const FileSystem &instance = FileSystem::Instance();
4549
2
  bool exists = instance.Exists(new_dir);
4550
2
  bool is_directory = instance.IsDirectory(new_dir);
4551
2
  std::string path = new_dir.GetPath(true);
4552
2
  bool writable = llvm::sys::fs::can_write(path);
4553
2
  if (exists && is_directory && writable)
4554
2
    return;
4555
4556
0
  m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4557
0
      ->GetValue()
4558
0
      ->Clear();
4559
4560
0
  std::string buffer;
4561
0
  llvm::raw_string_ostream os(buffer);
4562
0
  os << "JIT object dir '" << path << "' ";
4563
0
  if (!exists)
4564
0
    os << "does not exist";
4565
0
  else if (!is_directory)
4566
0
    os << "is not a directory";
4567
0
  else if (!writable)
4568
0
    os << "is not writable";
4569
4570
0
  std::optional<lldb::user_id_t> debugger_id;
4571
0
  if (m_target)
4572
0
    debugger_id = m_target->GetDebugger().GetID();
4573
0
  Debugger::ReportError(os.str(), debugger_id);
4574
0
}
4575
4576
149k
bool TargetProperties::GetEnableSyntheticValue() const {
4577
149k
  const uint32_t idx = ePropertyEnableSynthetic;
4578
149k
  return GetPropertyAtIndexAs<bool>(
4579
149k
      idx, g_target_properties[idx].default_uint_value != 0);
4580
149k
}
4581
4582
47.2k
bool TargetProperties::ShowHexVariableValuesWithLeadingZeroes() const {
4583
47.2k
  const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4584
47.2k
  return GetPropertyAtIndexAs<bool>(
4585
47.2k
      idx, g_target_properties[idx].default_uint_value != 0);
4586
47.2k
}
4587
4588
1.84k
uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
4589
1.84k
  const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4590
1.84k
  return GetPropertyAtIndexAs<uint64_t>(
4591
1.84k
      idx, g_target_properties[idx].default_uint_value);
4592
1.84k
}
4593
4594
7.04k
uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
4595
7.04k
  const uint32_t idx = ePropertyMaxChildrenCount;
4596
7.04k
  return GetPropertyAtIndexAs<int64_t>(
4597
7.04k
      idx, g_target_properties[idx].default_uint_value);
4598
7.04k
}
4599
4600
std::pair<uint32_t, bool>
4601
8.44k
TargetProperties::GetMaximumDepthOfChildrenToDisplay() const {
4602
8.44k
  const uint32_t idx = ePropertyMaxChildrenDepth;
4603
8.44k
  auto *option_value =
4604
8.44k
      m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4605
8.44k
  bool is_default = !option_value->OptionWasSet();
4606
8.44k
  return {option_value->GetCurrentValue(), is_default};
4607
8.44k
}
4608
4609
3.58k
uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
4610
3.58k
  const uint32_t idx = ePropertyMaxSummaryLength;
4611
3.58k
  return GetPropertyAtIndexAs<uint64_t>(
4612
3.58k
      idx, g_target_properties[idx].default_uint_value);
4613
3.58k
}
4614
4615
40
uint32_t TargetProperties::GetMaximumMemReadSize() const {
4616
40
  const uint32_t idx = ePropertyMaxMemReadSize;
4617
40
  return GetPropertyAtIndexAs<uint64_t>(
4618
40
      idx, g_target_properties[idx].default_uint_value);
4619
40
}
4620
4621
11.1k
FileSpec TargetProperties::GetStandardInputPath() const {
4622
11.1k
  const uint32_t idx = ePropertyInputPath;
4623
11.1k
  return GetPropertyAtIndexAs<FileSpec>(idx, {});
4624
11.1k
}
4625
4626
0
void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4627
0
  const uint32_t idx = ePropertyInputPath;
4628
0
  SetPropertyAtIndex(idx, path);
4629
0
}
4630
4631
11.0k
FileSpec TargetProperties::GetStandardOutputPath() const {
4632
11.0k
  const uint32_t idx = ePropertyOutputPath;
4633
11.0k
  return GetPropertyAtIndexAs<FileSpec>(idx, {});
4634
11.0k
}
4635
4636
0
void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4637
0
  const uint32_t idx = ePropertyOutputPath;
4638
0
  SetPropertyAtIndex(idx, path);
4639
0
}
4640
4641
11.1k
FileSpec TargetProperties::GetStandardErrorPath() const {
4642
11.1k
  const uint32_t idx = ePropertyErrorPath;
4643
11.1k
  return GetPropertyAtIndexAs<FileSpec>(idx, {});
4644
11.1k
}
4645
4646
0
void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4647
0
  const uint32_t idx = ePropertyErrorPath;
4648
0
  SetPropertyAtIndex(idx, path);
4649
0
}
4650
4651
11.4k
LanguageType TargetProperties::GetLanguage() const {
4652
11.4k
  const uint32_t idx = ePropertyLanguage;
4653
11.4k
  return GetPropertyAtIndexAs<LanguageType>(idx, {});
4654
11.4k
}
4655
4656
7.11k
llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4657
7.11k
  const uint32_t idx = ePropertyExprPrefix;
4658
7.11k
  OptionValueFileSpec *file =
4659
7.11k
      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
4660
7.11k
  if (file) {
4661
7.11k
    DataBufferSP data_sp(file->GetFileContents());
4662
7.11k
    if (data_sp)
4663
0
      return llvm::StringRef(
4664
0
          reinterpret_cast<const char *>(data_sp->GetBytes()),
4665
0
          data_sp->GetByteSize());
4666
7.11k
  }
4667
7.11k
  return "";
4668
7.11k
}
4669
4670
11.9k
uint64_t TargetProperties::GetExprErrorLimit() const {
4671
11.9k
  const uint32_t idx = ePropertyExprErrorLimit;
4672
11.9k
  return GetPropertyAtIndexAs<uint64_t>(
4673
11.9k
      idx, g_target_properties[idx].default_uint_value);
4674
11.9k
}
4675
4676
279
uint64_t TargetProperties::GetExprAllocAddress() const {
4677
279
  const uint32_t idx = ePropertyExprAllocAddress;
4678
279
  return GetPropertyAtIndexAs<uint64_t>(
4679
279
      idx, g_target_properties[idx].default_uint_value);
4680
279
}
4681
4682
5.66k
uint64_t TargetProperties::GetExprAllocSize() const {
4683
5.66k
  const uint32_t idx = ePropertyExprAllocSize;
4684
5.66k
  return GetPropertyAtIndexAs<uint64_t>(
4685
5.66k
      idx, g_target_properties[idx].default_uint_value);
4686
5.66k
}
4687
4688
391
uint64_t TargetProperties::GetExprAllocAlign() const {
4689
391
  const uint32_t idx = ePropertyExprAllocAlign;
4690
391
  return GetPropertyAtIndexAs<uint64_t>(
4691
391
      idx, g_target_properties[idx].default_uint_value);
4692
391
}
4693
4694
273k
bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4695
273k
  const uint32_t idx = ePropertyBreakpointUseAvoidList;
4696
273k
  return GetPropertyAtIndexAs<bool>(
4697
273k
      idx, g_target_properties[idx].default_uint_value != 0);
4698
273k
}
4699
4700
975k
bool TargetProperties::GetUseHexImmediates() const {
4701
975k
  const uint32_t idx = ePropertyUseHexImmediates;
4702
975k
  return GetPropertyAtIndexAs<bool>(
4703
975k
      idx, g_target_properties[idx].default_uint_value != 0);
4704
975k
}
4705
4706
528
bool TargetProperties::GetUseFastStepping() const {
4707
528
  const uint32_t idx = ePropertyUseFastStepping;
4708
528
  return GetPropertyAtIndexAs<bool>(
4709
528
      idx, g_target_properties[idx].default_uint_value != 0);
4710
528
}
4711
4712
2.05k
bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4713
2.05k
  const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4714
2.05k
  return GetPropertyAtIndexAs<bool>(
4715
2.05k
      idx, g_target_properties[idx].default_uint_value != 0);
4716
2.05k
}
4717
4718
234k
LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4719
234k
  const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4720
234k
  return GetPropertyAtIndexAs<LoadScriptFromSymFile>(
4721
234k
      idx, static_cast<LoadScriptFromSymFile>(
4722
234k
               g_target_properties[idx].default_uint_value));
4723
234k
}
4724
4725
2
LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4726
2
  const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4727
2
  return GetPropertyAtIndexAs<LoadCWDlldbinitFile>(
4728
2
      idx, static_cast<LoadCWDlldbinitFile>(
4729
2
               g_target_properties[idx].default_uint_value));
4730
2
}
4731
4732
975k
Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4733
975k
  const uint32_t idx = ePropertyHexImmediateStyle;
4734
975k
  return GetPropertyAtIndexAs<Disassembler::HexImmediateStyle>(
4735
975k
      idx, static_cast<Disassembler::HexImmediateStyle>(
4736
975k
               g_target_properties[idx].default_uint_value));
4737
975k
}
4738
4739
6
MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4740
6
  const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4741
6
  return GetPropertyAtIndexAs<MemoryModuleLoadLevel>(
4742
6
      idx, static_cast<MemoryModuleLoadLevel>(
4743
6
               g_target_properties[idx].default_uint_value));
4744
6
}
4745
4746
2.79k
bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4747
2.79k
  const uint32_t idx = ePropertyTrapHandlerNames;
4748
2.79k
  return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4749
2.79k
}
4750
4751
0
void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4752
0
  const uint32_t idx = ePropertyTrapHandlerNames;
4753
0
  m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4754
0
}
4755
4756
1.88k
bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4757
1.88k
  const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4758
1.88k
  return GetPropertyAtIndexAs<bool>(
4759
1.88k
      idx, g_target_properties[idx].default_uint_value != 0);
4760
1.88k
}
4761
4762
0
void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4763
0
  const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4764
0
  SetPropertyAtIndex(idx, b);
4765
0
}
4766
4767
236
bool TargetProperties::GetDisplayRecognizedArguments() const {
4768
236
  const uint32_t idx = ePropertyDisplayRecognizedArguments;
4769
236
  return GetPropertyAtIndexAs<bool>(
4770
236
      idx, g_target_properties[idx].default_uint_value != 0);
4771
236
}
4772
4773
0
void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4774
0
  const uint32_t idx = ePropertyDisplayRecognizedArguments;
4775
0
  SetPropertyAtIndex(idx, b);
4776
0
}
4777
4778
2.30k
const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() const {
4779
2.30k
  return m_launch_info;
4780
2.30k
}
4781
4782
void TargetProperties::SetProcessLaunchInfo(
4783
5
    const ProcessLaunchInfo &launch_info) {
4784
5
  m_launch_info = launch_info;
4785
5
  SetArg0(launch_info.GetArg0());
4786
5
  SetRunArguments(launch_info.GetArguments());
4787
5
  SetEnvironment(launch_info.GetEnvironment());
4788
5
  const FileAction *input_file_action =
4789
5
      launch_info.GetFileActionForFD(STDIN_FILENO);
4790
5
  if (input_file_action) {
4791
0
    SetStandardInputPath(input_file_action->GetPath());
4792
0
  }
4793
5
  const FileAction *output_file_action =
4794
5
      launch_info.GetFileActionForFD(STDOUT_FILENO);
4795
5
  if (output_file_action) {
4796
0
    SetStandardOutputPath(output_file_action->GetPath());
4797
0
  }
4798
5
  const FileAction *error_file_action =
4799
5
      launch_info.GetFileActionForFD(STDERR_FILENO);
4800
5
  if (error_file_action) {
4801
0
    SetStandardErrorPath(error_file_action->GetPath());
4802
0
  }
4803
5
  SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4804
5
  SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4805
5
  SetInheritTCC(
4806
5
      launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4807
5
  SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4808
5
}
4809
4810
14.5k
bool TargetProperties::GetRequireHardwareBreakpoints() const {
4811
14.5k
  const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4812
14.5k
  return GetPropertyAtIndexAs<bool>(
4813
14.5k
      idx, g_target_properties[idx].default_uint_value != 0);
4814
14.5k
}
4815
4816
0
void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4817
0
  const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4818
0
  m_collection_sp->SetPropertyAtIndex(idx, b);
4819
0
}
4820
4821
1
bool TargetProperties::GetAutoInstallMainExecutable() const {
4822
1
  const uint32_t idx = ePropertyAutoInstallMainExecutable;
4823
1
  return GetPropertyAtIndexAs<bool>(
4824
1
      idx, g_target_properties[idx].default_uint_value != 0);
4825
1
}
4826
4827
9.02k
void TargetProperties::Arg0ValueChangedCallback() {
4828
9.02k
  m_launch_info.SetArg0(GetArg0());
4829
9.02k
}
4830
4831
9.04k
void TargetProperties::RunArgsValueChangedCallback() {
4832
9.04k
  Args args;
4833
9.04k
  if (GetRunArguments(args))
4834
9.04k
    m_launch_info.GetArguments() = args;
4835
9.04k
}
4836
4837
9.03k
void TargetProperties::EnvVarsValueChangedCallback() {
4838
9.03k
  m_launch_info.GetEnvironment() = ComputeEnvironment();
4839
9.03k
}
4840
4841
9.02k
void TargetProperties::InputPathValueChangedCallback() {
4842
9.02k
  m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
4843
9.02k
                                     false);
4844
9.02k
}
4845
4846
9.02k
void TargetProperties::OutputPathValueChangedCallback() {
4847
9.02k
  m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
4848
9.02k
                                     false, true);
4849
9.02k
}
4850
4851
9.02k
void TargetProperties::ErrorPathValueChangedCallback() {
4852
9.02k
  m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4853
9.02k
                                     false, true);
4854
9.02k
}
4855
4856
9.07k
void TargetProperties::DetachOnErrorValueChangedCallback() {
4857
9.07k
  if (GetDetachOnError())
4858
4.09k
    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4859
4.97k
  else
4860
4.97k
    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4861
9.07k
}
4862
4863
9.02k
void TargetProperties::DisableASLRValueChangedCallback() {
4864
9.02k
  if (GetDisableASLR())
4865
9.02k
    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4866
1
  else
4867
1
    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4868
9.02k
}
4869
4870
9.07k
void TargetProperties::InheritTCCValueChangedCallback() {
4871
9.07k
  if (GetInheritTCC())
4872
4.97k
    m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4873
4.09k
  else
4874
4.09k
    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4875
9.07k
}
4876
4877
9.02k
void TargetProperties::DisableSTDIOValueChangedCallback() {
4878
9.02k
  if (GetDisableSTDIO())
4879
1
    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4880
9.02k
  else
4881
9.02k
    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4882
9.02k
}
4883
4884
4.82k
bool TargetProperties::GetDebugUtilityExpression() const {
4885
4.82k
  const uint32_t idx = ePropertyDebugUtilityExpression;
4886
4.82k
  return GetPropertyAtIndexAs<bool>(
4887
4.82k
      idx, g_target_properties[idx].default_uint_value != 0);
4888
4.82k
}
4889
4890
0
void TargetProperties::SetDebugUtilityExpression(bool debug) {
4891
0
  const uint32_t idx = ePropertyDebugUtilityExpression;
4892
0
  SetPropertyAtIndex(idx, debug);
4893
0
}
4894
4895
// Target::TargetEventData
4896
4897
Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4898
0
    : EventData(), m_target_sp(target_sp), m_module_list() {}
4899
4900
Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4901
                                         const ModuleList &module_list)
4902
16.5k
    : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4903
4904
16.5k
Target::TargetEventData::~TargetEventData() = default;
4905
4906
180
llvm::StringRef Target::TargetEventData::GetFlavorString() {
4907
180
  return "Target::TargetEventData";
4908
180
}
4909
4910
0
void Target::TargetEventData::Dump(Stream *s) const {
4911
0
  for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4912
0
    if (i != 0)
4913
0
      *s << ", ";
4914
0
    m_module_list.GetModuleAtIndex(i)->GetDescription(
4915
0
        s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4916
0
  }
4917
0
}
4918
4919
const Target::TargetEventData *
4920
90
Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4921
90
  if (event_ptr) {
4922
90
    const EventData *event_data = event_ptr->GetData();
4923
90
    if (event_data &&
4924
90
        event_data->GetFlavor() == TargetEventData::GetFlavorString())
4925
90
      return static_cast<const TargetEventData *>(event_ptr->GetData());
4926
90
  }
4927
0
  return nullptr;
4928
90
}
4929
4930
0
TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4931
0
  TargetSP target_sp;
4932
0
  const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4933
0
  if (event_data)
4934
0
    target_sp = event_data->m_target_sp;
4935
0
  return target_sp;
4936
0
}
4937
4938
ModuleList
4939
87
Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4940
87
  ModuleList module_list;
4941
87
  const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4942
87
  if (event_data)
4943
87
    module_list = event_data->m_module_list;
4944
87
  return module_list;
4945
87
}
4946
4947
196k
std::recursive_mutex &Target::GetAPIMutex() {
4948
196k
  if (GetProcessSP() && 
GetProcessSP()->CurrentThreadIsPrivateStateThread()187k
)
4949
21
    return m_private_mutex;
4950
196k
  else
4951
196k
    return m_mutex;
4952
196k
}
4953
4954
/// Get metrics associated with this target in JSON format.
4955
26
llvm::json::Value Target::ReportStatistics() { return m_stats.ToJSON(*this); }