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