1254721Semaste//===-- Target.cpp ----------------------------------------------*- C++ -*-===//
2254721Semaste//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6254721Semaste//
7254721Semaste//===----------------------------------------------------------------------===//
8254721Semaste
9344779Sdim#include "lldb/Target/Target.h"
10314564Sdim#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
11314564Sdim#include "lldb/Breakpoint/BreakpointIDList.h"
12353358Sdim#include "lldb/Breakpoint/BreakpointPrecondition.h"
13254721Semaste#include "lldb/Breakpoint/BreakpointResolver.h"
14254721Semaste#include "lldb/Breakpoint/BreakpointResolverAddress.h"
15254721Semaste#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
16254721Semaste#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
17254721Semaste#include "lldb/Breakpoint/BreakpointResolverName.h"
18344779Sdim#include "lldb/Breakpoint/BreakpointResolverScripted.h"
19254721Semaste#include "lldb/Breakpoint/Watchpoint.h"
20254721Semaste#include "lldb/Core/Debugger.h"
21254721Semaste#include "lldb/Core/Module.h"
22254721Semaste#include "lldb/Core/ModuleSpec.h"
23327952Sdim#include "lldb/Core/PluginManager.h"
24344779Sdim#include "lldb/Core/SearchFilter.h"
25254721Semaste#include "lldb/Core/Section.h"
26254721Semaste#include "lldb/Core/SourceManager.h"
27262528Semaste#include "lldb/Core/StreamFile.h"
28344779Sdim#include "lldb/Core/StructuredDataImpl.h"
29254721Semaste#include "lldb/Core/ValueObject.h"
30296417Sdim#include "lldb/Expression/REPL.h"
31296417Sdim#include "lldb/Expression/UserExpression.h"
32254721Semaste#include "lldb/Host/Host.h"
33321369Sdim#include "lldb/Host/PosixApi.h"
34254721Semaste#include "lldb/Interpreter/CommandInterpreter.h"
35254721Semaste#include "lldb/Interpreter/CommandReturnObject.h"
36254721Semaste#include "lldb/Interpreter/OptionGroupWatchpoint.h"
37254721Semaste#include "lldb/Interpreter/OptionValues.h"
38254721Semaste#include "lldb/Interpreter/Property.h"
39288943Sdim#include "lldb/Symbol/ClangASTContext.h"
40353358Sdim#include "lldb/Symbol/ClangASTImporter.h"
41314564Sdim#include "lldb/Symbol/Function.h"
42254721Semaste#include "lldb/Symbol/ObjectFile.h"
43296417Sdim#include "lldb/Symbol/Symbol.h"
44296417Sdim#include "lldb/Target/Language.h"
45288943Sdim#include "lldb/Target/LanguageRuntime.h"
46254721Semaste#include "lldb/Target/Process.h"
47262528Semaste#include "lldb/Target/SectionLoadList.h"
48254721Semaste#include "lldb/Target/StackFrame.h"
49258054Semaste#include "lldb/Target/SystemRuntime.h"
50254721Semaste#include "lldb/Target/Thread.h"
51254721Semaste#include "lldb/Target/ThreadSpec.h"
52344779Sdim#include "lldb/Utility/Event.h"
53321369Sdim#include "lldb/Utility/FileSpec.h"
54296417Sdim#include "lldb/Utility/LLDBAssert.h"
55321369Sdim#include "lldb/Utility/Log.h"
56344779Sdim#include "lldb/Utility/State.h"
57321369Sdim#include "lldb/Utility/StreamString.h"
58321369Sdim#include "lldb/Utility/Timer.h"
59353358Sdim
60353358Sdim#include "llvm/ADT/ScopeExit.h"
61353358Sdim
62353358Sdim#include <memory>
63344779Sdim#include <mutex>
64254721Semaste
65254721Semasteusing namespace lldb;
66254721Semasteusing namespace lldb_private;
67254721Semaste
68314564Sdimconstexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
69314564Sdim
70327952SdimTarget::Arch::Arch(const ArchSpec &spec)
71327952Sdim    : m_spec(spec),
72327952Sdim      m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
73327952Sdim
74360784Sdimconst Target::Arch &Target::Arch::operator=(const ArchSpec &spec) {
75327952Sdim  m_spec = spec;
76327952Sdim  m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
77327952Sdim  return *this;
78327952Sdim}
79327952Sdim
80314564SdimConstString &Target::GetStaticBroadcasterClass() {
81314564Sdim  static ConstString class_name("lldb.target");
82314564Sdim  return class_name;
83254721Semaste}
84254721Semaste
85314564SdimTarget::Target(Debugger &debugger, const ArchSpec &target_arch,
86314564Sdim               const lldb::PlatformSP &platform_sp, bool is_dummy_target)
87309124Sdim    : TargetProperties(this),
88314564Sdim      Broadcaster(debugger.GetBroadcasterManager(),
89314564Sdim                  Target::GetStaticBroadcasterClass().AsCString()),
90314564Sdim      ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
91341825Sdim      m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
92341825Sdim      m_breakpoint_list(false), m_internal_breakpoint_list(true),
93341825Sdim      m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
94341825Sdim      m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
95353358Sdim      m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
96341825Sdim      m_valid(true), m_suppress_stop_hooks(false),
97341825Sdim      m_is_dummy_target(is_dummy_target),
98341825Sdim      m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
99280031Sdim
100254721Semaste{
101314564Sdim  SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
102314564Sdim  SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
103314564Sdim  SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
104314564Sdim  SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
105314564Sdim  SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
106276479Sdim
107314564Sdim  CheckInWithManager();
108254721Semaste
109360784Sdim  LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT),
110360784Sdim           "{0} Target::Target()", static_cast<void *>(this));
111327952Sdim  if (target_arch.IsValid()) {
112360784Sdim    LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
113360784Sdim             "Target::Target created with architecture {0} ({1})",
114360784Sdim             target_arch.GetArchitectureName(),
115360784Sdim             target_arch.GetTriple().getTriple().c_str());
116314564Sdim  }
117254721Semaste}
118254721Semaste
119314564SdimTarget::~Target() {
120314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
121360784Sdim  LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
122314564Sdim  DeleteCurrentProcess();
123296417Sdim}
124296417Sdim
125314564Sdimvoid Target::PrimeFromDummyTarget(Target *target) {
126314564Sdim  if (!target)
127314564Sdim    return;
128280031Sdim
129314564Sdim  m_stop_hooks = target->m_stop_hooks;
130314564Sdim
131314564Sdim  for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
132314564Sdim    if (breakpoint_sp->IsInternal())
133314564Sdim      continue;
134314564Sdim
135314564Sdim    BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
136314564Sdim    AddBreakpoint(new_bp, false);
137314564Sdim  }
138360784Sdim
139360784Sdim  for (auto bp_name_entry : target->m_breakpoint_names) {
140360784Sdim
141327952Sdim    BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
142327952Sdim    AddBreakpointName(new_bp_name);
143327952Sdim  }
144280031Sdim}
145280031Sdim
146314564Sdimvoid Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
147314564Sdim  //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
148314564Sdim  if (description_level != lldb::eDescriptionLevelBrief) {
149314564Sdim    s->Indent();
150314564Sdim    s->PutCString("Target\n");
151314564Sdim    s->IndentMore();
152314564Sdim    m_images.Dump(s);
153314564Sdim    m_breakpoint_list.Dump(s);
154314564Sdim    m_internal_breakpoint_list.Dump(s);
155314564Sdim    s->IndentLess();
156314564Sdim  } else {
157314564Sdim    Module *exe_module = GetExecutableModulePointer();
158314564Sdim    if (exe_module)
159314564Sdim      s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
160254721Semaste    else
161314564Sdim      s->PutCString("No executable module.");
162314564Sdim  }
163254721Semaste}
164254721Semaste
165314564Sdimvoid Target::CleanupProcess() {
166314564Sdim  // Do any cleanup of the target we need to do between process instances.
167314564Sdim  // NB It is better to do this before destroying the process in case the
168314564Sdim  // clean up needs some help from the process.
169314564Sdim  m_breakpoint_list.ClearAllBreakpointSites();
170314564Sdim  m_internal_breakpoint_list.ClearAllBreakpointSites();
171314564Sdim  // Disable watchpoints just on the debugger side.
172314564Sdim  std::unique_lock<std::recursive_mutex> lock;
173314564Sdim  this->GetWatchpointList().GetListMutex(lock);
174314564Sdim  DisableAllWatchpoints(false);
175314564Sdim  ClearAllWatchpointHitCounts();
176314564Sdim  ClearAllWatchpointHistoricValues();
177254721Semaste}
178254721Semaste
179314564Sdimvoid Target::DeleteCurrentProcess() {
180314564Sdim  if (m_process_sp) {
181314564Sdim    m_section_load_history.Clear();
182314564Sdim    if (m_process_sp->IsAlive())
183314564Sdim      m_process_sp->Destroy(false);
184254721Semaste
185314564Sdim    m_process_sp->Finalize();
186254721Semaste
187314564Sdim    CleanupProcess();
188254721Semaste
189314564Sdim    m_process_sp.reset();
190314564Sdim  }
191254721Semaste}
192254721Semaste
193314564Sdimconst lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
194314564Sdim                                             llvm::StringRef plugin_name,
195314564Sdim                                             const FileSpec *crash_file) {
196344779Sdim  if (!listener_sp)
197344779Sdim    listener_sp = GetDebugger().GetListener();
198314564Sdim  DeleteCurrentProcess();
199314564Sdim  m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
200314564Sdim                                     listener_sp, crash_file);
201314564Sdim  return m_process_sp;
202254721Semaste}
203254721Semaste
204314564Sdimconst lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
205314564Sdim
206321369Sdimlldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
207314564Sdim                             const char *repl_options, bool can_create) {
208314564Sdim  if (language == eLanguageTypeUnknown) {
209360784Sdim    LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
210314564Sdim
211360784Sdim    if (auto single_lang = repl_languages.GetSingularLanguage()) {
212360784Sdim      language = *single_lang;
213360784Sdim    } else if (repl_languages.Empty()) {
214314564Sdim      err.SetErrorStringWithFormat(
215314564Sdim          "LLDB isn't configured with REPL support for any languages.");
216314564Sdim      return REPLSP();
217314564Sdim    } else {
218314564Sdim      err.SetErrorStringWithFormat(
219314564Sdim          "Multiple possible REPL languages.  Please specify a language.");
220314564Sdim      return REPLSP();
221296417Sdim    }
222314564Sdim  }
223314564Sdim
224314564Sdim  REPLMap::iterator pos = m_repl_map.find(language);
225314564Sdim
226314564Sdim  if (pos != m_repl_map.end()) {
227314564Sdim    return pos->second;
228314564Sdim  }
229314564Sdim
230314564Sdim  if (!can_create) {
231314564Sdim    err.SetErrorStringWithFormat(
232314564Sdim        "Couldn't find an existing REPL for %s, and can't create a new one",
233314564Sdim        Language::GetNameForLanguageType(language));
234296417Sdim    return lldb::REPLSP();
235314564Sdim  }
236314564Sdim
237314564Sdim  Debugger *const debugger = nullptr;
238314564Sdim  lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
239314564Sdim
240314564Sdim  if (ret) {
241314564Sdim    m_repl_map[language] = ret;
242314564Sdim    return m_repl_map[language];
243314564Sdim  }
244314564Sdim
245314564Sdim  if (err.Success()) {
246314564Sdim    err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
247314564Sdim                                 Language::GetNameForLanguageType(language));
248314564Sdim  }
249314564Sdim
250314564Sdim  return lldb::REPLSP();
251296417Sdim}
252296417Sdim
253314564Sdimvoid Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
254314564Sdim  lldbassert(!m_repl_map.count(language));
255314564Sdim
256314564Sdim  m_repl_map[language] = repl_sp;
257296417Sdim}
258296417Sdim
259314564Sdimvoid Target::Destroy() {
260314564Sdim  std::lock_guard<std::recursive_mutex> guard(m_mutex);
261314564Sdim  m_valid = false;
262314564Sdim  DeleteCurrentProcess();
263314564Sdim  m_platform_sp.reset();
264327952Sdim  m_arch = ArchSpec();
265314564Sdim  ClearModules(true);
266314564Sdim  m_section_load_history.Clear();
267314564Sdim  const bool notify = false;
268314564Sdim  m_breakpoint_list.RemoveAll(notify);
269314564Sdim  m_internal_breakpoint_list.RemoveAll(notify);
270314564Sdim  m_last_created_breakpoint.reset();
271314564Sdim  m_last_created_watchpoint.reset();
272314564Sdim  m_search_filter_sp.reset();
273314564Sdim  m_image_search_paths.Clear(notify);
274314564Sdim  m_stop_hooks.clear();
275314564Sdim  m_stop_hook_next_id = 0;
276314564Sdim  m_suppress_stop_hooks = false;
277254721Semaste}
278254721Semaste
279314564SdimBreakpointList &Target::GetBreakpointList(bool internal) {
280314564Sdim  if (internal)
281314564Sdim    return m_internal_breakpoint_list;
282314564Sdim  else
283314564Sdim    return m_breakpoint_list;
284254721Semaste}
285254721Semaste
286314564Sdimconst BreakpointList &Target::GetBreakpointList(bool internal) const {
287314564Sdim  if (internal)
288314564Sdim    return m_internal_breakpoint_list;
289314564Sdim  else
290314564Sdim    return m_breakpoint_list;
291254721Semaste}
292254721Semaste
293314564SdimBreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
294314564Sdim  BreakpointSP bp_sp;
295254721Semaste
296314564Sdim  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
297314564Sdim    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
298314564Sdim  else
299314564Sdim    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
300254721Semaste
301314564Sdim  return bp_sp;
302254721Semaste}
303254721Semaste
304314564SdimBreakpointSP Target::CreateSourceRegexBreakpoint(
305314564Sdim    const FileSpecList *containingModules,
306314564Sdim    const FileSpecList *source_file_spec_list,
307314564Sdim    const std::unordered_set<std::string> &function_names,
308360784Sdim    RegularExpression source_regex, bool internal, bool hardware,
309314564Sdim    LazyBool move_to_nearest_code) {
310314564Sdim  SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
311314564Sdim      containingModules, source_file_spec_list));
312314564Sdim  if (move_to_nearest_code == eLazyBoolCalculate)
313314564Sdim    move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
314314564Sdim  BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
315360784Sdim      nullptr, std::move(source_regex), function_names,
316314564Sdim      !static_cast<bool>(move_to_nearest_code)));
317314564Sdim
318314564Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
319254721Semaste}
320254721Semaste
321314564SdimBreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
322314564Sdim                                      const FileSpec &file, uint32_t line_no,
323344779Sdim                                      uint32_t column, lldb::addr_t offset,
324314564Sdim                                      LazyBool check_inlines,
325314564Sdim                                      LazyBool skip_prologue, bool internal,
326314564Sdim                                      bool hardware,
327314564Sdim                                      LazyBool move_to_nearest_code) {
328314564Sdim  FileSpec remapped_file;
329341825Sdim  if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
330314564Sdim    remapped_file = file;
331309124Sdim
332314564Sdim  if (check_inlines == eLazyBoolCalculate) {
333314564Sdim    const InlineStrategy inline_strategy = GetInlineStrategy();
334314564Sdim    switch (inline_strategy) {
335314564Sdim    case eInlineBreakpointsNever:
336314564Sdim      check_inlines = eLazyBoolNo;
337314564Sdim      break;
338254721Semaste
339314564Sdim    case eInlineBreakpointsHeaders:
340314564Sdim      if (remapped_file.IsSourceImplementationFile())
341314564Sdim        check_inlines = eLazyBoolNo;
342314564Sdim      else
343314564Sdim        check_inlines = eLazyBoolYes;
344314564Sdim      break;
345314564Sdim
346314564Sdim    case eInlineBreakpointsAlways:
347314564Sdim      check_inlines = eLazyBoolYes;
348314564Sdim      break;
349254721Semaste    }
350314564Sdim  }
351314564Sdim  SearchFilterSP filter_sp;
352314564Sdim  if (check_inlines == eLazyBoolNo) {
353314564Sdim    // Not checking for inlines, we are looking only for matching compile units
354314564Sdim    FileSpecList compile_unit_list;
355314564Sdim    compile_unit_list.Append(remapped_file);
356314564Sdim    filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
357314564Sdim                                                  &compile_unit_list);
358314564Sdim  } else {
359314564Sdim    filter_sp = GetSearchFilterForModuleList(containingModules);
360314564Sdim  }
361314564Sdim  if (skip_prologue == eLazyBoolCalculate)
362314564Sdim    skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
363314564Sdim  if (move_to_nearest_code == eLazyBoolCalculate)
364314564Sdim    move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
365254721Semaste
366314564Sdim  BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
367344779Sdim      nullptr, remapped_file, line_no, column, offset, check_inlines,
368344779Sdim      skip_prologue, !static_cast<bool>(move_to_nearest_code)));
369314564Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
370254721Semaste}
371254721Semaste
372314564SdimBreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
373314564Sdim                                      bool hardware) {
374314564Sdim  Address so_addr;
375296417Sdim
376314564Sdim  // Check for any reason we want to move this breakpoint to other address.
377314564Sdim  addr = GetBreakableLoadAddress(addr);
378254721Semaste
379341825Sdim  // Attempt to resolve our load address if possible, though it is ok if it
380341825Sdim  // doesn't resolve to section/offset.
381314564Sdim
382314564Sdim  // Try and resolve as a load address if possible
383314564Sdim  GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
384314564Sdim  if (!so_addr.IsValid()) {
385314564Sdim    // The address didn't resolve, so just set this as an absolute address
386314564Sdim    so_addr.SetOffset(addr);
387314564Sdim  }
388314564Sdim  BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
389314564Sdim  return bp_sp;
390254721Semaste}
391254721Semaste
392314564SdimBreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
393314564Sdim                                      bool hardware) {
394314564Sdim  SearchFilterSP filter_sp(
395314564Sdim      new SearchFilterForUnconstrainedSearches(shared_from_this()));
396314564Sdim  BreakpointResolverSP resolver_sp(
397314564Sdim      new BreakpointResolverAddress(nullptr, addr));
398314564Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
399254721Semaste}
400254721Semaste
401296417Sdimlldb::BreakpointSP
402314564SdimTarget::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
403314564Sdim                                        const FileSpec *file_spec,
404314564Sdim                                        bool request_hardware) {
405314564Sdim  SearchFilterSP filter_sp(
406314564Sdim      new SearchFilterForUnconstrainedSearches(shared_from_this()));
407360784Sdim  BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(
408360784Sdim      nullptr, file_addr, file_spec ? *file_spec : FileSpec()));
409314564Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
410314564Sdim                          false);
411296417Sdim}
412296417Sdim
413344779SdimBreakpointSP Target::CreateBreakpoint(
414344779Sdim    const FileSpecList *containingModules,
415344779Sdim    const FileSpecList *containingSourceFiles, const char *func_name,
416344779Sdim    FunctionNameType func_name_type_mask, LanguageType language,
417344779Sdim    lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
418314564Sdim  BreakpointSP bp_sp;
419314564Sdim  if (func_name) {
420314564Sdim    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
421314564Sdim        containingModules, containingSourceFiles));
422254721Semaste
423314564Sdim    if (skip_prologue == eLazyBoolCalculate)
424314564Sdim      skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
425314564Sdim    if (language == lldb::eLanguageTypeUnknown)
426314564Sdim      language = GetLanguage();
427254721Semaste
428314564Sdim    BreakpointResolverSP resolver_sp(new BreakpointResolverName(
429314564Sdim        nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
430314564Sdim        offset, skip_prologue));
431314564Sdim    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
432314564Sdim  }
433314564Sdim  return bp_sp;
434254721Semaste}
435254721Semaste
436254721Semastelldb::BreakpointSP
437314564SdimTarget::CreateBreakpoint(const FileSpecList *containingModules,
438314564Sdim                         const FileSpecList *containingSourceFiles,
439314564Sdim                         const std::vector<std::string> &func_names,
440344779Sdim                         FunctionNameType func_name_type_mask,
441344779Sdim                         LanguageType language, lldb::addr_t offset,
442344779Sdim                         LazyBool skip_prologue, bool internal, bool hardware) {
443314564Sdim  BreakpointSP bp_sp;
444314564Sdim  size_t num_names = func_names.size();
445314564Sdim  if (num_names > 0) {
446314564Sdim    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
447314564Sdim        containingModules, containingSourceFiles));
448254721Semaste
449314564Sdim    if (skip_prologue == eLazyBoolCalculate)
450314564Sdim      skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
451314564Sdim    if (language == lldb::eLanguageTypeUnknown)
452314564Sdim      language = GetLanguage();
453254721Semaste
454314564Sdim    BreakpointResolverSP resolver_sp(
455314564Sdim        new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
456314564Sdim                                   language, offset, skip_prologue));
457314564Sdim    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
458314564Sdim  }
459314564Sdim  return bp_sp;
460254721Semaste}
461254721Semaste
462344779SdimBreakpointSP
463344779SdimTarget::CreateBreakpoint(const FileSpecList *containingModules,
464344779Sdim                         const FileSpecList *containingSourceFiles,
465344779Sdim                         const char *func_names[], size_t num_names,
466344779Sdim                         FunctionNameType func_name_type_mask,
467344779Sdim                         LanguageType language, lldb::addr_t offset,
468344779Sdim                         LazyBool skip_prologue, bool internal, bool hardware) {
469314564Sdim  BreakpointSP bp_sp;
470314564Sdim  if (num_names > 0) {
471314564Sdim    SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
472314564Sdim        containingModules, containingSourceFiles));
473254721Semaste
474314564Sdim    if (skip_prologue == eLazyBoolCalculate) {
475314564Sdim      if (offset == 0)
476314564Sdim        skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
477314564Sdim      else
478314564Sdim        skip_prologue = eLazyBoolNo;
479254721Semaste    }
480314564Sdim    if (language == lldb::eLanguageTypeUnknown)
481314564Sdim      language = GetLanguage();
482314564Sdim
483314564Sdim    BreakpointResolverSP resolver_sp(new BreakpointResolverName(
484314564Sdim        nullptr, func_names, num_names, func_name_type_mask, language, offset,
485314564Sdim        skip_prologue));
486314564Sdim    resolver_sp->SetOffset(offset);
487314564Sdim    bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
488314564Sdim  }
489314564Sdim  return bp_sp;
490254721Semaste}
491254721Semaste
492254721SemasteSearchFilterSP
493314564SdimTarget::GetSearchFilterForModule(const FileSpec *containingModule) {
494314564Sdim  SearchFilterSP filter_sp;
495314564Sdim  if (containingModule != nullptr) {
496314564Sdim    // TODO: We should look into sharing module based search filters
497314564Sdim    // across many breakpoints like we do for the simple target based one
498353358Sdim    filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
499353358Sdim                                                       *containingModule);
500314564Sdim  } else {
501314564Sdim    if (!m_search_filter_sp)
502353358Sdim      m_search_filter_sp =
503353358Sdim          std::make_shared<SearchFilterForUnconstrainedSearches>(
504353358Sdim              shared_from_this());
505314564Sdim    filter_sp = m_search_filter_sp;
506314564Sdim  }
507314564Sdim  return filter_sp;
508254721Semaste}
509254721Semaste
510254721SemasteSearchFilterSP
511314564SdimTarget::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
512314564Sdim  SearchFilterSP filter_sp;
513314564Sdim  if (containingModules && containingModules->GetSize() != 0) {
514314564Sdim    // TODO: We should look into sharing module based search filters
515314564Sdim    // across many breakpoints like we do for the simple target based one
516353358Sdim    filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
517353358Sdim                                                           *containingModules);
518314564Sdim  } else {
519314564Sdim    if (!m_search_filter_sp)
520353358Sdim      m_search_filter_sp =
521353358Sdim          std::make_shared<SearchFilterForUnconstrainedSearches>(
522353358Sdim              shared_from_this());
523314564Sdim    filter_sp = m_search_filter_sp;
524314564Sdim  }
525314564Sdim  return filter_sp;
526254721Semaste}
527254721Semaste
528314564SdimSearchFilterSP Target::GetSearchFilterForModuleAndCUList(
529314564Sdim    const FileSpecList *containingModules,
530314564Sdim    const FileSpecList *containingSourceFiles) {
531314564Sdim  if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
532314564Sdim    return GetSearchFilterForModuleList(containingModules);
533314564Sdim
534314564Sdim  SearchFilterSP filter_sp;
535314564Sdim  if (containingModules == nullptr) {
536314564Sdim    // We could make a special "CU List only SearchFilter".  Better yet was if
537341825Sdim    // these could be composable, but that will take a little reworking.
538314564Sdim
539353358Sdim    filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
540353358Sdim        shared_from_this(), FileSpecList(), *containingSourceFiles);
541314564Sdim  } else {
542353358Sdim    filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
543353358Sdim        shared_from_this(), *containingModules, *containingSourceFiles);
544314564Sdim  }
545314564Sdim  return filter_sp;
546254721Semaste}
547254721Semaste
548314564SdimBreakpointSP Target::CreateFuncRegexBreakpoint(
549314564Sdim    const FileSpecList *containingModules,
550360784Sdim    const FileSpecList *containingSourceFiles, RegularExpression func_regex,
551314564Sdim    lldb::LanguageType requested_language, LazyBool skip_prologue,
552314564Sdim    bool internal, bool hardware) {
553314564Sdim  SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
554314564Sdim      containingModules, containingSourceFiles));
555314564Sdim  bool skip = (skip_prologue == eLazyBoolCalculate)
556314564Sdim                  ? GetSkipPrologue()
557314564Sdim                  : static_cast<bool>(skip_prologue);
558314564Sdim  BreakpointResolverSP resolver_sp(new BreakpointResolverName(
559360784Sdim      nullptr, std::move(func_regex), requested_language, 0, skip));
560254721Semaste
561314564Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
562254721Semaste}
563254721Semaste
564254721Semastelldb::BreakpointSP
565314564SdimTarget::CreateExceptionBreakpoint(enum lldb::LanguageType language,
566314564Sdim                                  bool catch_bp, bool throw_bp, bool internal,
567321369Sdim                                  Args *additional_args, Status *error) {
568314564Sdim  BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
569314564Sdim      *this, language, catch_bp, throw_bp, internal);
570314564Sdim  if (exc_bkpt_sp && additional_args) {
571353358Sdim    BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
572314564Sdim    if (precondition_sp && additional_args) {
573314564Sdim      if (error)
574314564Sdim        *error = precondition_sp->ConfigurePrecondition(*additional_args);
575314564Sdim      else
576314564Sdim        precondition_sp->ConfigurePrecondition(*additional_args);
577288943Sdim    }
578314564Sdim  }
579314564Sdim  return exc_bkpt_sp;
580254721Semaste}
581288943Sdim
582360784Sdimlldb::BreakpointSP Target::CreateScriptedBreakpoint(
583360784Sdim    const llvm::StringRef class_name, const FileSpecList *containingModules,
584360784Sdim    const FileSpecList *containingSourceFiles, bool internal,
585360784Sdim    bool request_hardware, StructuredData::ObjectSP extra_args_sp,
586360784Sdim    Status *creation_error) {
587344779Sdim  SearchFilterSP filter_sp;
588360784Sdim
589344779Sdim  lldb::SearchDepth depth = lldb::eSearchDepthTarget;
590360784Sdim  bool has_files =
591360784Sdim      containingSourceFiles && containingSourceFiles->GetSize() > 0;
592344779Sdim  bool has_modules = containingModules && containingModules->GetSize() > 0;
593360784Sdim
594344779Sdim  if (has_files && has_modules) {
595360784Sdim    filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
596360784Sdim                                                  containingSourceFiles);
597344779Sdim  } else if (has_files) {
598360784Sdim    filter_sp =
599360784Sdim        GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
600344779Sdim  } else if (has_modules) {
601344779Sdim    filter_sp = GetSearchFilterForModuleList(containingModules);
602344779Sdim  } else {
603353358Sdim    filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
604353358Sdim        shared_from_this());
605344779Sdim  }
606360784Sdim
607344779Sdim  StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
608344779Sdim  if (extra_args_sp)
609344779Sdim    extra_args_impl->SetObjectSP(extra_args_sp);
610353358Sdim
611353358Sdim  BreakpointResolverSP resolver_sp(new BreakpointResolverScripted(
612360784Sdim      nullptr, class_name, depth, extra_args_impl));
613344779Sdim  return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
614344779Sdim}
615344779Sdim
616314564SdimBreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
617314564Sdim                                      BreakpointResolverSP &resolver_sp,
618314564Sdim                                      bool internal, bool request_hardware,
619314564Sdim                                      bool resolve_indirect_symbols) {
620314564Sdim  BreakpointSP bp_sp;
621314564Sdim  if (filter_sp && resolver_sp) {
622344779Sdim    const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
623344779Sdim    bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
624314564Sdim                               resolve_indirect_symbols));
625314564Sdim    resolver_sp->SetBreakpoint(bp_sp.get());
626314564Sdim    AddBreakpoint(bp_sp, internal);
627314564Sdim  }
628314564Sdim  return bp_sp;
629280031Sdim}
630254721Semaste
631314564Sdimvoid Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
632314564Sdim  if (!bp_sp)
633314564Sdim    return;
634314564Sdim  if (internal)
635314564Sdim    m_internal_breakpoint_list.Add(bp_sp, false);
636314564Sdim  else
637314564Sdim    m_breakpoint_list.Add(bp_sp, true);
638254721Semaste
639314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
640314564Sdim  if (log) {
641314564Sdim    StreamString s;
642314564Sdim    bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
643360784Sdim    LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
644360784Sdim              __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
645314564Sdim  }
646254721Semaste
647314564Sdim  bp_sp->ResolveBreakpoint();
648280031Sdim
649314564Sdim  if (!internal) {
650314564Sdim    m_last_created_breakpoint = bp_sp;
651314564Sdim  }
652254721Semaste}
653254721Semaste
654360784Sdimvoid Target::AddNameToBreakpoint(BreakpointID &id, const char *name,
655360784Sdim                                 Status &error) {
656360784Sdim  BreakpointSP bp_sp =
657360784Sdim      m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
658360784Sdim  if (!bp_sp) {
659360784Sdim    StreamString s;
660360784Sdim    id.GetDescription(&s, eDescriptionLevelBrief);
661360784Sdim    error.SetErrorStringWithFormat("Could not find breakpoint %s", s.GetData());
662360784Sdim    return;
663360784Sdim  }
664360784Sdim  AddNameToBreakpoint(bp_sp, name, error);
665360784Sdim}
666327952Sdim
667360784Sdimvoid Target::AddNameToBreakpoint(BreakpointSP &bp_sp, const char *name,
668360784Sdim                                 Status &error) {
669360784Sdim  if (!bp_sp)
670360784Sdim    return;
671327952Sdim
672360784Sdim  BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
673360784Sdim  if (!bp_name)
674360784Sdim    return;
675327952Sdim
676360784Sdim  bp_name->ConfigureBreakpoint(bp_sp);
677360784Sdim  bp_sp->AddName(name);
678360784Sdim}
679360784Sdim
680327952Sdimvoid Target::AddBreakpointName(BreakpointName *bp_name) {
681327952Sdim  m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
682327952Sdim}
683327952Sdim
684360784SdimBreakpointName *Target::FindBreakpointName(ConstString name, bool can_create,
685360784Sdim                                           Status &error) {
686327952Sdim  BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
687327952Sdim  if (!error.Success())
688327952Sdim    return nullptr;
689327952Sdim
690327952Sdim  BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
691327952Sdim  if (iter == m_breakpoint_names.end()) {
692360784Sdim    if (!can_create) {
693327952Sdim      error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
694360784Sdim                                     "can_create is false.",
695360784Sdim                                     name.AsCString());
696327952Sdim      return nullptr;
697327952Sdim    }
698327952Sdim
699360784Sdim    iter = m_breakpoint_names
700360784Sdim               .insert(std::make_pair(name, new BreakpointName(name)))
701360784Sdim               .first;
702327952Sdim  }
703327952Sdim  return (iter->second);
704327952Sdim}
705327952Sdim
706360784Sdimvoid Target::DeleteBreakpointName(ConstString name) {
707327952Sdim  BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
708360784Sdim
709327952Sdim  if (iter != m_breakpoint_names.end()) {
710327952Sdim    const char *name_cstr = name.AsCString();
711327952Sdim    m_breakpoint_names.erase(iter);
712327952Sdim    for (auto bp_sp : m_breakpoint_list.Breakpoints())
713327952Sdim      bp_sp->RemoveName(name_cstr);
714327952Sdim  }
715327952Sdim}
716327952Sdim
717327952Sdimvoid Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
718360784Sdim                                      ConstString name) {
719327952Sdim  bp_sp->RemoveName(name.AsCString());
720327952Sdim}
721327952Sdim
722360784Sdimvoid Target::ConfigureBreakpointName(
723360784Sdim    BreakpointName &bp_name, const BreakpointOptions &new_options,
724360784Sdim    const BreakpointName::Permissions &new_permissions) {
725327952Sdim  bp_name.GetOptions().CopyOverSetOptions(new_options);
726327952Sdim  bp_name.GetPermissions().MergeInto(new_permissions);
727327952Sdim  ApplyNameToBreakpoints(bp_name);
728327952Sdim}
729327952Sdim
730327952Sdimvoid Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
731360784Sdim  llvm::Expected<std::vector<BreakpointSP>> expected_vector =
732360784Sdim      m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString());
733327952Sdim
734360784Sdim  if (!expected_vector) {
735360784Sdim    LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS),
736360784Sdim             "invalid breakpoint name: {}",
737360784Sdim             llvm::toString(expected_vector.takeError()));
738360784Sdim    return;
739360784Sdim  }
740360784Sdim
741360784Sdim  for (auto bp_sp : *expected_vector)
742327952Sdim    bp_name.ConfigureBreakpoint(bp_sp);
743327952Sdim}
744327952Sdim
745360784Sdimvoid Target::GetBreakpointNames(std::vector<std::string> &names) {
746327952Sdim  names.clear();
747327952Sdim  for (auto bp_name : m_breakpoint_names) {
748327952Sdim    names.push_back(bp_name.first.AsCString());
749327952Sdim  }
750344779Sdim  llvm::sort(names.begin(), names.end());
751327952Sdim}
752327952Sdim
753314564Sdimbool Target::ProcessIsValid() {
754314564Sdim  return (m_process_sp && m_process_sp->IsAlive());
755254721Semaste}
756254721Semaste
757344779Sdimstatic bool CheckIfWatchpointsSupported(Target *target, Status &error) {
758314564Sdim  uint32_t num_supported_hardware_watchpoints;
759321369Sdim  Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
760314564Sdim      num_supported_hardware_watchpoints);
761344779Sdim
762344779Sdim  // If unable to determine the # of watchpoints available,
763344779Sdim  // assume they are supported.
764344779Sdim  if (rc.Fail())
765344779Sdim    return true;
766344779Sdim
767314564Sdim  if (num_supported_hardware_watchpoints == 0) {
768314564Sdim    error.SetErrorStringWithFormat(
769314564Sdim        "Target supports (%u) hardware watchpoint slots.\n",
770314564Sdim        num_supported_hardware_watchpoints);
771314564Sdim    return false;
772314564Sdim  }
773314564Sdim  return true;
774254721Semaste}
775254721Semaste
776341825Sdim// See also Watchpoint::SetWatchpointType(uint32_t type) and the
777341825Sdim// OptionGroupWatchpoint::WatchType enum type.
778314564SdimWatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
779314564Sdim                                      const CompilerType *type, uint32_t kind,
780321369Sdim                                      Status &error) {
781314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
782360784Sdim  LLDB_LOGF(log,
783360784Sdim            "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
784360784Sdim            " type = %u)\n",
785360784Sdim            __FUNCTION__, addr, (uint64_t)size, kind);
786254721Semaste
787314564Sdim  WatchpointSP wp_sp;
788314564Sdim  if (!ProcessIsValid()) {
789314564Sdim    error.SetErrorString("process is not alive");
790314564Sdim    return wp_sp;
791314564Sdim  }
792254721Semaste
793314564Sdim  if (addr == LLDB_INVALID_ADDRESS || size == 0) {
794314564Sdim    if (size == 0)
795314564Sdim      error.SetErrorString("cannot set a watchpoint with watch_size of 0");
796314564Sdim    else
797314564Sdim      error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
798314564Sdim    return wp_sp;
799314564Sdim  }
800309124Sdim
801314564Sdim  if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
802314564Sdim    error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
803314564Sdim  }
804254721Semaste
805344779Sdim  if (!CheckIfWatchpointsSupported(this, error))
806314564Sdim    return wp_sp;
807254721Semaste
808341825Sdim  // Currently we only support one watchpoint per address, with total number of
809341825Sdim  // watchpoints limited by the hardware which the inferior is running on.
810314564Sdim
811314564Sdim  // Grab the list mutex while doing operations.
812314564Sdim  const bool notify = false; // Don't notify about all the state changes we do
813314564Sdim                             // on creating the watchpoint.
814314564Sdim  std::unique_lock<std::recursive_mutex> lock;
815314564Sdim  this->GetWatchpointList().GetListMutex(lock);
816314564Sdim  WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
817314564Sdim  if (matched_sp) {
818314564Sdim    size_t old_size = matched_sp->GetByteSize();
819314564Sdim    uint32_t old_type =
820314564Sdim        (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
821314564Sdim        (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
822314564Sdim    // Return the existing watchpoint if both size and type match.
823314564Sdim    if (size == old_size && kind == old_type) {
824314564Sdim      wp_sp = matched_sp;
825314564Sdim      wp_sp->SetEnabled(false, notify);
826314564Sdim    } else {
827314564Sdim      // Nil the matched watchpoint; we will be creating a new one.
828314564Sdim      m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
829314564Sdim      m_watchpoint_list.Remove(matched_sp->GetID(), true);
830254721Semaste    }
831314564Sdim  }
832254721Semaste
833314564Sdim  if (!wp_sp) {
834353358Sdim    wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
835314564Sdim    wp_sp->SetWatchpointType(kind, notify);
836314564Sdim    m_watchpoint_list.Add(wp_sp, true);
837314564Sdim  }
838254721Semaste
839314564Sdim  error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
840360784Sdim  LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
841360784Sdim            __FUNCTION__, error.Success() ? "succeeded" : "failed",
842360784Sdim            wp_sp->GetID());
843309124Sdim
844314564Sdim  if (error.Fail()) {
845341825Sdim    // Enabling the watchpoint on the device side failed. Remove the said
846341825Sdim    // watchpoint from the list maintained by the target instance.
847314564Sdim    m_watchpoint_list.Remove(wp_sp->GetID(), true);
848314564Sdim    // See if we could provide more helpful error message.
849314564Sdim    if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
850314564Sdim      error.SetErrorStringWithFormat(
851314564Sdim          "watch size of %" PRIu64 " is not supported", (uint64_t)size);
852314564Sdim
853314564Sdim    wp_sp.reset();
854314564Sdim  } else
855314564Sdim    m_last_created_watchpoint = wp_sp;
856314564Sdim  return wp_sp;
857254721Semaste}
858254721Semaste
859360784Sdimvoid Target::RemoveAllowedBreakpoints() {
860327952Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
861360784Sdim  LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
862327952Sdim
863327952Sdim  m_breakpoint_list.RemoveAllowed(true);
864360784Sdim
865327952Sdim  m_last_created_breakpoint.reset();
866327952Sdim}
867327952Sdim
868314564Sdimvoid Target::RemoveAllBreakpoints(bool internal_also) {
869314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
870360784Sdim  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
871360784Sdim            internal_also ? "yes" : "no");
872254721Semaste
873314564Sdim  m_breakpoint_list.RemoveAll(true);
874314564Sdim  if (internal_also)
875314564Sdim    m_internal_breakpoint_list.RemoveAll(false);
876314564Sdim
877314564Sdim  m_last_created_breakpoint.reset();
878254721Semaste}
879254721Semaste
880314564Sdimvoid Target::DisableAllBreakpoints(bool internal_also) {
881314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
882360784Sdim  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
883360784Sdim            internal_also ? "yes" : "no");
884254721Semaste
885314564Sdim  m_breakpoint_list.SetEnabledAll(false);
886314564Sdim  if (internal_also)
887314564Sdim    m_internal_breakpoint_list.SetEnabledAll(false);
888254721Semaste}
889254721Semaste
890327952Sdimvoid Target::DisableAllowedBreakpoints() {
891327952Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
892360784Sdim  LLDB_LOGF(log, "Target::%s", __FUNCTION__);
893327952Sdim
894327952Sdim  m_breakpoint_list.SetEnabledAllowed(false);
895327952Sdim}
896327952Sdim
897314564Sdimvoid Target::EnableAllBreakpoints(bool internal_also) {
898314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
899360784Sdim  LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
900360784Sdim            internal_also ? "yes" : "no");
901254721Semaste
902314564Sdim  m_breakpoint_list.SetEnabledAll(true);
903314564Sdim  if (internal_also)
904314564Sdim    m_internal_breakpoint_list.SetEnabledAll(true);
905254721Semaste}
906254721Semaste
907327952Sdimvoid Target::EnableAllowedBreakpoints() {
908327952Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
909360784Sdim  LLDB_LOGF(log, "Target::%s", __FUNCTION__);
910327952Sdim
911327952Sdim  m_breakpoint_list.SetEnabledAllowed(true);
912327952Sdim}
913327952Sdim
914314564Sdimbool Target::RemoveBreakpointByID(break_id_t break_id) {
915314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
916360784Sdim  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
917360784Sdim            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
918254721Semaste
919314564Sdim  if (DisableBreakpointByID(break_id)) {
920314564Sdim    if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
921314564Sdim      m_internal_breakpoint_list.Remove(break_id, false);
922314564Sdim    else {
923314564Sdim      if (m_last_created_breakpoint) {
924314564Sdim        if (m_last_created_breakpoint->GetID() == break_id)
925314564Sdim          m_last_created_breakpoint.reset();
926314564Sdim      }
927314564Sdim      m_breakpoint_list.Remove(break_id, true);
928254721Semaste    }
929314564Sdim    return true;
930314564Sdim  }
931314564Sdim  return false;
932254721Semaste}
933254721Semaste
934314564Sdimbool Target::DisableBreakpointByID(break_id_t break_id) {
935314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
936360784Sdim  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
937360784Sdim            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
938254721Semaste
939314564Sdim  BreakpointSP bp_sp;
940254721Semaste
941314564Sdim  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
942314564Sdim    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
943314564Sdim  else
944314564Sdim    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
945314564Sdim  if (bp_sp) {
946314564Sdim    bp_sp->SetEnabled(false);
947314564Sdim    return true;
948314564Sdim  }
949314564Sdim  return false;
950314564Sdim}
951314564Sdim
952314564Sdimbool Target::EnableBreakpointByID(break_id_t break_id) {
953314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
954360784Sdim  LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
955360784Sdim            break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
956314564Sdim
957314564Sdim  BreakpointSP bp_sp;
958314564Sdim
959314564Sdim  if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
960314564Sdim    bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
961314564Sdim  else
962314564Sdim    bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
963314564Sdim
964314564Sdim  if (bp_sp) {
965314564Sdim    bp_sp->SetEnabled(true);
966314564Sdim    return true;
967314564Sdim  }
968314564Sdim  return false;
969314564Sdim}
970314564Sdim
971321369SdimStatus Target::SerializeBreakpointsToFile(const FileSpec &file,
972321369Sdim                                          const BreakpointIDList &bp_ids,
973321369Sdim                                          bool append) {
974321369Sdim  Status error;
975314564Sdim
976314564Sdim  if (!file) {
977314564Sdim    error.SetErrorString("Invalid FileSpec.");
978314564Sdim    return error;
979314564Sdim  }
980314564Sdim
981314564Sdim  std::string path(file.GetPath());
982314564Sdim  StructuredData::ObjectSP input_data_sp;
983314564Sdim
984314564Sdim  StructuredData::ArraySP break_store_sp;
985314564Sdim  StructuredData::Array *break_store_ptr = nullptr;
986314564Sdim
987314564Sdim  if (append) {
988314564Sdim    input_data_sp = StructuredData::ParseJSONFromFile(file, error);
989314564Sdim    if (error.Success()) {
990314564Sdim      break_store_ptr = input_data_sp->GetAsArray();
991314564Sdim      if (!break_store_ptr) {
992314564Sdim        error.SetErrorStringWithFormat(
993314564Sdim            "Tried to append to invalid input file %s", path.c_str());
994314564Sdim        return error;
995314564Sdim      }
996254721Semaste    }
997314564Sdim  }
998314564Sdim
999314564Sdim  if (!break_store_ptr) {
1000353358Sdim    break_store_sp = std::make_shared<StructuredData::Array>();
1001314564Sdim    break_store_ptr = break_store_sp.get();
1002314564Sdim  }
1003314564Sdim
1004314564Sdim  StreamFile out_file(path.c_str(),
1005360784Sdim                      File::eOpenOptionTruncate | File::eOpenOptionWrite |
1006360784Sdim                          File::eOpenOptionCanCreate |
1007360784Sdim                          File::eOpenOptionCloseOnExec,
1008314564Sdim                      lldb::eFilePermissionsFileDefault);
1009314564Sdim  if (!out_file.GetFile().IsValid()) {
1010314564Sdim    error.SetErrorStringWithFormat("Unable to open output file: %s.",
1011314564Sdim                                   path.c_str());
1012314564Sdim    return error;
1013314564Sdim  }
1014314564Sdim
1015314564Sdim  std::unique_lock<std::recursive_mutex> lock;
1016314564Sdim  GetBreakpointList().GetListMutex(lock);
1017314564Sdim
1018314564Sdim  if (bp_ids.GetSize() == 0) {
1019314564Sdim    const BreakpointList &breakpoints = GetBreakpointList();
1020314564Sdim
1021314564Sdim    size_t num_breakpoints = breakpoints.GetSize();
1022314564Sdim    for (size_t i = 0; i < num_breakpoints; i++) {
1023314564Sdim      Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1024314564Sdim      StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1025314564Sdim      // If a breakpoint can't serialize it, just ignore it for now:
1026314564Sdim      if (bkpt_save_sp)
1027314564Sdim        break_store_ptr->AddItem(bkpt_save_sp);
1028314564Sdim    }
1029314564Sdim  } else {
1030314564Sdim
1031314564Sdim    std::unordered_set<lldb::break_id_t> processed_bkpts;
1032314564Sdim    const size_t count = bp_ids.GetSize();
1033314564Sdim    for (size_t i = 0; i < count; ++i) {
1034314564Sdim      BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1035314564Sdim      lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1036314564Sdim
1037314564Sdim      if (bp_id != LLDB_INVALID_BREAK_ID) {
1038314564Sdim        // Only do each breakpoint once:
1039314564Sdim        std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1040314564Sdim            insert_result = processed_bkpts.insert(bp_id);
1041314564Sdim        if (!insert_result.second)
1042314564Sdim          continue;
1043314564Sdim
1044314564Sdim        Breakpoint *bp = GetBreakpointByID(bp_id).get();
1045314564Sdim        StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1046314564Sdim        // If the user explicitly asked to serialize a breakpoint, and we
1047341825Sdim        // can't, then raise an error:
1048314564Sdim        if (!bkpt_save_sp) {
1049314564Sdim          error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1050314564Sdim                                         bp_id);
1051314564Sdim          return error;
1052314564Sdim        }
1053314564Sdim        break_store_ptr->AddItem(bkpt_save_sp);
1054314564Sdim      }
1055314564Sdim    }
1056314564Sdim  }
1057314564Sdim
1058314564Sdim  break_store_ptr->Dump(out_file, false);
1059314564Sdim  out_file.PutChar('\n');
1060314564Sdim  return error;
1061254721Semaste}
1062254721Semaste
1063321369SdimStatus Target::CreateBreakpointsFromFile(const FileSpec &file,
1064321369Sdim                                         BreakpointIDList &new_bps) {
1065314564Sdim  std::vector<std::string> no_names;
1066314564Sdim  return CreateBreakpointsFromFile(file, no_names, new_bps);
1067314564Sdim}
1068254721Semaste
1069321369SdimStatus Target::CreateBreakpointsFromFile(const FileSpec &file,
1070321369Sdim                                         std::vector<std::string> &names,
1071321369Sdim                                         BreakpointIDList &new_bps) {
1072314564Sdim  std::unique_lock<std::recursive_mutex> lock;
1073314564Sdim  GetBreakpointList().GetListMutex(lock);
1074254721Semaste
1075321369Sdim  Status error;
1076314564Sdim  StructuredData::ObjectSP input_data_sp =
1077314564Sdim      StructuredData::ParseJSONFromFile(file, error);
1078314564Sdim  if (!error.Success()) {
1079314564Sdim    return error;
1080314564Sdim  } else if (!input_data_sp || !input_data_sp->IsValid()) {
1081314564Sdim    error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1082314564Sdim                                   file.GetPath().c_str());
1083314564Sdim    return error;
1084314564Sdim  }
1085254721Semaste
1086314564Sdim  StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1087314564Sdim  if (!bkpt_array) {
1088314564Sdim    error.SetErrorStringWithFormat(
1089314564Sdim        "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1090314564Sdim    return error;
1091314564Sdim  }
1092314564Sdim
1093314564Sdim  size_t num_bkpts = bkpt_array->GetSize();
1094314564Sdim  size_t num_names = names.size();
1095314564Sdim
1096314564Sdim  for (size_t i = 0; i < num_bkpts; i++) {
1097314564Sdim    StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1098314564Sdim    // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1099314564Sdim    StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1100314564Sdim    if (!bkpt_dict) {
1101314564Sdim      error.SetErrorStringWithFormat(
1102314564Sdim          "Invalid breakpoint data for element %zu from input file: %s.", i,
1103314564Sdim          file.GetPath().c_str());
1104314564Sdim      return error;
1105254721Semaste    }
1106314564Sdim    StructuredData::ObjectSP bkpt_data_sp =
1107314564Sdim        bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1108314564Sdim    if (num_names &&
1109314564Sdim        !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1110314564Sdim      continue;
1111314564Sdim
1112314564Sdim    BreakpointSP bkpt_sp =
1113314564Sdim        Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1114314564Sdim    if (!error.Success()) {
1115314564Sdim      error.SetErrorStringWithFormat(
1116314564Sdim          "Error restoring breakpoint %zu from %s: %s.", i,
1117314564Sdim          file.GetPath().c_str(), error.AsCString());
1118314564Sdim      return error;
1119314564Sdim    }
1120314564Sdim    new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1121314564Sdim  }
1122314564Sdim  return error;
1123254721Semaste}
1124254721Semaste
1125254721Semaste// The flag 'end_to_end', default to true, signifies that the operation is
1126254721Semaste// performed end to end, for both the debugger and the debuggee.
1127254721Semaste
1128254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1129254721Semaste// to end operations.
1130314564Sdimbool Target::RemoveAllWatchpoints(bool end_to_end) {
1131314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1132360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1133254721Semaste
1134314564Sdim  if (!end_to_end) {
1135314564Sdim    m_watchpoint_list.RemoveAll(true);
1136314564Sdim    return true;
1137314564Sdim  }
1138254721Semaste
1139314564Sdim  // Otherwise, it's an end to end operation.
1140254721Semaste
1141314564Sdim  if (!ProcessIsValid())
1142314564Sdim    return false;
1143254721Semaste
1144314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1145314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1146314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1147314564Sdim    if (!wp_sp)
1148314564Sdim      return false;
1149254721Semaste
1150321369Sdim    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1151314564Sdim    if (rc.Fail())
1152314564Sdim      return false;
1153314564Sdim  }
1154314564Sdim  m_watchpoint_list.RemoveAll(true);
1155314564Sdim  m_last_created_watchpoint.reset();
1156314564Sdim  return true; // Success!
1157254721Semaste}
1158254721Semaste
1159341825Sdim// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1160341825Sdim// to end operations.
1161314564Sdimbool Target::DisableAllWatchpoints(bool end_to_end) {
1162314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1163360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1164254721Semaste
1165314564Sdim  if (!end_to_end) {
1166314564Sdim    m_watchpoint_list.SetEnabledAll(false);
1167314564Sdim    return true;
1168314564Sdim  }
1169254721Semaste
1170314564Sdim  // Otherwise, it's an end to end operation.
1171254721Semaste
1172314564Sdim  if (!ProcessIsValid())
1173314564Sdim    return false;
1174254721Semaste
1175314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1176314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1177314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1178314564Sdim    if (!wp_sp)
1179314564Sdim      return false;
1180254721Semaste
1181321369Sdim    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1182314564Sdim    if (rc.Fail())
1183314564Sdim      return false;
1184314564Sdim  }
1185314564Sdim  return true; // Success!
1186254721Semaste}
1187254721Semaste
1188341825Sdim// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1189341825Sdim// to end operations.
1190314564Sdimbool Target::EnableAllWatchpoints(bool end_to_end) {
1191314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1192360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1193254721Semaste
1194314564Sdim  if (!end_to_end) {
1195314564Sdim    m_watchpoint_list.SetEnabledAll(true);
1196314564Sdim    return true;
1197314564Sdim  }
1198254721Semaste
1199314564Sdim  // Otherwise, it's an end to end operation.
1200254721Semaste
1201314564Sdim  if (!ProcessIsValid())
1202314564Sdim    return false;
1203254721Semaste
1204314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1205314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1206314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1207314564Sdim    if (!wp_sp)
1208314564Sdim      return false;
1209254721Semaste
1210321369Sdim    Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1211314564Sdim    if (rc.Fail())
1212314564Sdim      return false;
1213314564Sdim  }
1214314564Sdim  return true; // Success!
1215254721Semaste}
1216254721Semaste
1217254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1218314564Sdimbool Target::ClearAllWatchpointHitCounts() {
1219314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1220360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1221254721Semaste
1222314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1223314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1224314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1225314564Sdim    if (!wp_sp)
1226314564Sdim      return false;
1227254721Semaste
1228314564Sdim    wp_sp->ResetHitCount();
1229314564Sdim  }
1230314564Sdim  return true; // Success!
1231254721Semaste}
1232254721Semaste
1233288943Sdim// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1234314564Sdimbool Target::ClearAllWatchpointHistoricValues() {
1235314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1236360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1237314564Sdim
1238314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1239314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1240314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1241314564Sdim    if (!wp_sp)
1242314564Sdim      return false;
1243314564Sdim
1244314564Sdim    wp_sp->ResetHistoricValues();
1245314564Sdim  }
1246314564Sdim  return true; // Success!
1247288943Sdim}
1248288943Sdim
1249341825Sdim// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1250341825Sdim// these operations.
1251314564Sdimbool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1252314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1253360784Sdim  LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1254254721Semaste
1255314564Sdim  if (!ProcessIsValid())
1256314564Sdim    return false;
1257254721Semaste
1258314564Sdim  size_t num_watchpoints = m_watchpoint_list.GetSize();
1259314564Sdim  for (size_t i = 0; i < num_watchpoints; ++i) {
1260314564Sdim    WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1261314564Sdim    if (!wp_sp)
1262314564Sdim      return false;
1263254721Semaste
1264314564Sdim    wp_sp->SetIgnoreCount(ignore_count);
1265314564Sdim  }
1266314564Sdim  return true; // Success!
1267254721Semaste}
1268254721Semaste
1269254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1270314564Sdimbool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1271314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1272360784Sdim  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1273254721Semaste
1274314564Sdim  if (!ProcessIsValid())
1275314564Sdim    return false;
1276254721Semaste
1277314564Sdim  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1278314564Sdim  if (wp_sp) {
1279321369Sdim    Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1280314564Sdim    if (rc.Success())
1281314564Sdim      return true;
1282254721Semaste
1283314564Sdim    // Else, fallthrough.
1284314564Sdim  }
1285314564Sdim  return false;
1286254721Semaste}
1287254721Semaste
1288254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1289314564Sdimbool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1290314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1291360784Sdim  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1292254721Semaste
1293314564Sdim  if (!ProcessIsValid())
1294314564Sdim    return false;
1295254721Semaste
1296314564Sdim  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1297314564Sdim  if (wp_sp) {
1298321369Sdim    Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1299314564Sdim    if (rc.Success())
1300314564Sdim      return true;
1301254721Semaste
1302314564Sdim    // Else, fallthrough.
1303314564Sdim  }
1304314564Sdim  return false;
1305254721Semaste}
1306254721Semaste
1307254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1308314564Sdimbool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1309314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1310360784Sdim  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1311254721Semaste
1312314564Sdim  WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1313314564Sdim  if (watch_to_remove_sp == m_last_created_watchpoint)
1314314564Sdim    m_last_created_watchpoint.reset();
1315314564Sdim
1316314564Sdim  if (DisableWatchpointByID(watch_id)) {
1317314564Sdim    m_watchpoint_list.Remove(watch_id, true);
1318314564Sdim    return true;
1319314564Sdim  }
1320314564Sdim  return false;
1321254721Semaste}
1322254721Semaste
1323254721Semaste// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1324314564Sdimbool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1325314564Sdim                                  uint32_t ignore_count) {
1326314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1327360784Sdim  LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1328254721Semaste
1329314564Sdim  if (!ProcessIsValid())
1330314564Sdim    return false;
1331254721Semaste
1332314564Sdim  WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1333314564Sdim  if (wp_sp) {
1334314564Sdim    wp_sp->SetIgnoreCount(ignore_count);
1335314564Sdim    return true;
1336314564Sdim  }
1337314564Sdim  return false;
1338254721Semaste}
1339254721Semaste
1340314564SdimModuleSP Target::GetExecutableModule() {
1341314564Sdim  // search for the first executable in the module list
1342314564Sdim  for (size_t i = 0; i < m_images.GetSize(); ++i) {
1343314564Sdim    ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1344314564Sdim    lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1345314564Sdim    if (obj == nullptr)
1346314564Sdim      continue;
1347314564Sdim    if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1348314564Sdim      return module_sp;
1349314564Sdim  }
1350314564Sdim  // as fall back return the first module loaded
1351314564Sdim  return m_images.GetModuleAtIndex(0);
1352254721Semaste}
1353254721Semaste
1354314564SdimModule *Target::GetExecutableModulePointer() {
1355314564Sdim  return GetExecutableModule().get();
1356254721Semaste}
1357254721Semaste
1358314564Sdimstatic void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1359314564Sdim                                           Target *target) {
1360321369Sdim  Status error;
1361314564Sdim  StreamString feedback_stream;
1362360784Sdim  if (module_sp && !module_sp->LoadScriptingResourceInTarget(
1363360784Sdim                       target, error, &feedback_stream)) {
1364314564Sdim    if (error.AsCString())
1365360784Sdim      target->GetDebugger().GetErrorStream().Printf(
1366314564Sdim          "unable to load scripting data for module %s - error reported was "
1367314564Sdim          "%s\n",
1368314564Sdim          module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1369314564Sdim          error.AsCString());
1370314564Sdim  }
1371314564Sdim  if (feedback_stream.GetSize())
1372360784Sdim    target->GetDebugger().GetErrorStream().Printf("%s\n",
1373360784Sdim                                                  feedback_stream.GetData());
1374254721Semaste}
1375254721Semaste
1376314564Sdimvoid Target::ClearModules(bool delete_locations) {
1377314564Sdim  ModulesDidUnload(m_images, delete_locations);
1378314564Sdim  m_section_load_history.Clear();
1379314564Sdim  m_images.Clear();
1380314564Sdim  m_scratch_type_system_map.Clear();
1381314564Sdim  m_ast_importer_sp.reset();
1382258054Semaste}
1383258054Semaste
1384314564Sdimvoid Target::DidExec() {
1385314564Sdim  // When a process exec's we need to know about it so we can do some cleanup.
1386327952Sdim  m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1387327952Sdim  m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1388258884Semaste}
1389258884Semaste
1390314564Sdimvoid Target::SetExecutableModule(ModuleSP &executable_sp,
1391344779Sdim                                 LoadDependentFiles load_dependent_files) {
1392314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1393314564Sdim  ClearModules(false);
1394254721Semaste
1395314564Sdim  if (executable_sp) {
1396321369Sdim    static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1397321369Sdim    Timer scoped_timer(func_cat,
1398314564Sdim                       "Target::SetExecutableModule (executable = '%s')",
1399314564Sdim                       executable_sp->GetFileSpec().GetPath().c_str());
1400254721Semaste
1401353358Sdim    const bool notify = true;
1402360784Sdim    m_images.Append(executable_sp,
1403360784Sdim                    notify); // The first image is our executable file
1404254721Semaste
1405314564Sdim    // If we haven't set an architecture yet, reset our architecture based on
1406314564Sdim    // what we found in the executable module.
1407327952Sdim    if (!m_arch.GetSpec().IsValid()) {
1408314564Sdim      m_arch = executable_sp->GetArchitecture();
1409327952Sdim      LLDB_LOG(log,
1410327952Sdim               "setting architecture to {0} ({1}) based on executable file",
1411327952Sdim               m_arch.GetSpec().GetArchitectureName(),
1412327952Sdim               m_arch.GetSpec().GetTriple().getTriple());
1413314564Sdim    }
1414254721Semaste
1415314564Sdim    FileSpecList dependent_files;
1416314564Sdim    ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1417344779Sdim    bool load_dependents = true;
1418344779Sdim    switch (load_dependent_files) {
1419344779Sdim    case eLoadDependentsDefault:
1420344779Sdim      load_dependents = executable_sp->IsExecutable();
1421344779Sdim      break;
1422344779Sdim    case eLoadDependentsYes:
1423344779Sdim      load_dependents = true;
1424344779Sdim      break;
1425344779Sdim    case eLoadDependentsNo:
1426344779Sdim      load_dependents = false;
1427344779Sdim      break;
1428344779Sdim    }
1429254721Semaste
1430344779Sdim    if (executable_objfile && load_dependents) {
1431353358Sdim      ModuleList added_modules;
1432314564Sdim      executable_objfile->GetDependentModules(dependent_files);
1433314564Sdim      for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1434360784Sdim        FileSpec dependent_file_spec(dependent_files.GetFileSpecAtIndex(i));
1435314564Sdim        FileSpec platform_dependent_file_spec;
1436314564Sdim        if (m_platform_sp)
1437314564Sdim          m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1438314564Sdim                                         platform_dependent_file_spec);
1439314564Sdim        else
1440314564Sdim          platform_dependent_file_spec = dependent_file_spec;
1441314564Sdim
1442327952Sdim        ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1443360784Sdim        ModuleSP image_module_sp(
1444360784Sdim            GetOrCreateModule(module_spec, false /* notify */));
1445314564Sdim        if (image_module_sp) {
1446360784Sdim          added_modules.AppendIfNeeded(image_module_sp, false);
1447314564Sdim          ObjectFile *objfile = image_module_sp->GetObjectFile();
1448314564Sdim          if (objfile)
1449314564Sdim            objfile->GetDependentModules(dependent_files);
1450254721Semaste        }
1451314564Sdim      }
1452353358Sdim      ModulesDidLoad(added_modules);
1453254721Semaste    }
1454314564Sdim  }
1455254721Semaste}
1456254721Semaste
1457344779Sdimbool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
1458314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1459327952Sdim  bool missing_local_arch = !m_arch.GetSpec().IsValid();
1460314564Sdim  bool replace_local_arch = true;
1461314564Sdim  bool compatible_local_arch = false;
1462314564Sdim  ArchSpec other(arch_spec);
1463296417Sdim
1464344779Sdim  // Changing the architecture might mean that the currently selected platform
1465344779Sdim  // isn't compatible. Set the platform correctly if we are asked to do so,
1466344779Sdim  // otherwise assume the user will set the platform manually.
1467344779Sdim  if (set_platform) {
1468344779Sdim    if (other.IsValid()) {
1469344779Sdim      auto platform_sp = GetPlatform();
1470344779Sdim      if (!platform_sp ||
1471344779Sdim          !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1472344779Sdim        ArchSpec platform_arch;
1473344779Sdim        auto arch_platform_sp =
1474344779Sdim            Platform::GetPlatformForArchitecture(other, &platform_arch);
1475344779Sdim        if (arch_platform_sp) {
1476344779Sdim          SetPlatform(arch_platform_sp);
1477344779Sdim          if (platform_arch.IsValid())
1478344779Sdim            other = platform_arch;
1479344779Sdim        }
1480344779Sdim      }
1481344779Sdim    }
1482344779Sdim  }
1483344779Sdim
1484314564Sdim  if (!missing_local_arch) {
1485327952Sdim    if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1486327952Sdim      other.MergeFrom(m_arch.GetSpec());
1487314564Sdim
1488327952Sdim      if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1489314564Sdim        compatible_local_arch = true;
1490314564Sdim        bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1491314564Sdim            env_changed;
1492314564Sdim
1493360784Sdim        m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed,
1494360784Sdim                                                vendor_changed, os_changed,
1495360784Sdim                                                os_ver_changed, env_changed);
1496314564Sdim
1497314564Sdim        if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1498314564Sdim          replace_local_arch = false;
1499314564Sdim      }
1500296417Sdim    }
1501314564Sdim  }
1502296417Sdim
1503314564Sdim  if (compatible_local_arch || missing_local_arch) {
1504314564Sdim    // If we haven't got a valid arch spec, or the architectures are compatible
1505341825Sdim    // update the architecture, unless the one we already have is more
1506341825Sdim    // specified
1507314564Sdim    if (replace_local_arch)
1508314564Sdim      m_arch = other;
1509327952Sdim    LLDB_LOG(log, "set architecture to {0} ({1})",
1510327952Sdim             m_arch.GetSpec().GetArchitectureName(),
1511327952Sdim             m_arch.GetSpec().GetTriple().getTriple());
1512314564Sdim    return true;
1513314564Sdim  }
1514296417Sdim
1515314564Sdim  // If we have an executable file, try to reset the executable to the desired
1516314564Sdim  // architecture
1517360784Sdim  LLDB_LOGF(log, "Target::SetArchitecture changing architecture to %s (%s)",
1518360784Sdim            arch_spec.GetArchitectureName(),
1519360784Sdim            arch_spec.GetTriple().getTriple().c_str());
1520314564Sdim  m_arch = other;
1521314564Sdim  ModuleSP executable_sp = GetExecutableModule();
1522314564Sdim
1523314564Sdim  ClearModules(true);
1524314564Sdim  // Need to do something about unsetting breakpoints.
1525314564Sdim
1526314564Sdim  if (executable_sp) {
1527360784Sdim    LLDB_LOGF(log,
1528360784Sdim              "Target::SetArchitecture Trying to select executable file "
1529360784Sdim              "architecture %s (%s)",
1530360784Sdim              arch_spec.GetArchitectureName(),
1531360784Sdim              arch_spec.GetTriple().getTriple().c_str());
1532314564Sdim    ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1533353358Sdim    FileSpecList search_paths = GetExecutableSearchPaths();
1534321369Sdim    Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1535360784Sdim                                               &search_paths, nullptr, nullptr);
1536314564Sdim
1537314564Sdim    if (!error.Fail() && executable_sp) {
1538344779Sdim      SetExecutableModule(executable_sp, eLoadDependentsYes);
1539314564Sdim      return true;
1540254721Semaste    }
1541314564Sdim  }
1542314564Sdim  return false;
1543254721Semaste}
1544254721Semaste
1545314564Sdimbool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1546344779Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1547314564Sdim  if (arch_spec.IsValid()) {
1548327952Sdim    if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1549341825Sdim      // The current target arch is compatible with "arch_spec", see if we can
1550341825Sdim      // improve our current architecture using bits from "arch_spec"
1551288943Sdim
1552360784Sdim      LLDB_LOGF(log,
1553360784Sdim                "Target::MergeArchitecture target has arch %s, merging with "
1554360784Sdim                "arch %s",
1555360784Sdim                m_arch.GetSpec().GetTriple().getTriple().c_str(),
1556360784Sdim                arch_spec.GetTriple().getTriple().c_str());
1557344779Sdim
1558314564Sdim      // Merge bits from arch_spec into "merged_arch" and set our architecture
1559327952Sdim      ArchSpec merged_arch(m_arch.GetSpec());
1560314564Sdim      merged_arch.MergeFrom(arch_spec);
1561314564Sdim      return SetArchitecture(merged_arch);
1562314564Sdim    } else {
1563314564Sdim      // The new architecture is different, we just need to replace it
1564314564Sdim      return SetArchitecture(arch_spec);
1565288943Sdim    }
1566314564Sdim  }
1567314564Sdim  return false;
1568288943Sdim}
1569288943Sdim
1570353358Sdimvoid Target::NotifyWillClearList(const ModuleList &module_list) {}
1571314564Sdim
1572353358Sdimvoid Target::NotifyModuleAdded(const ModuleList &module_list,
1573360784Sdim                               const ModuleSP &module_sp) {
1574314564Sdim  // A module is being added to this target for the first time
1575314564Sdim  if (m_valid) {
1576314564Sdim    ModuleList my_module_list;
1577314564Sdim    my_module_list.Append(module_sp);
1578314564Sdim    ModulesDidLoad(my_module_list);
1579314564Sdim  }
1580254721Semaste}
1581254721Semaste
1582353358Sdimvoid Target::NotifyModuleRemoved(const ModuleList &module_list,
1583360784Sdim                                 const ModuleSP &module_sp) {
1584314564Sdim  // A module is being removed from this target.
1585314564Sdim  if (m_valid) {
1586314564Sdim    ModuleList my_module_list;
1587314564Sdim    my_module_list.Append(module_sp);
1588314564Sdim    ModulesDidUnload(my_module_list, false);
1589314564Sdim  }
1590254721Semaste}
1591254721Semaste
1592353358Sdimvoid Target::NotifyModuleUpdated(const ModuleList &module_list,
1593360784Sdim                                 const ModuleSP &old_module_sp,
1594360784Sdim                                 const ModuleSP &new_module_sp) {
1595314564Sdim  // A module is replacing an already added module
1596314564Sdim  if (m_valid) {
1597314564Sdim    m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1598314564Sdim                                                            new_module_sp);
1599314564Sdim    m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1600314564Sdim        old_module_sp, new_module_sp);
1601314564Sdim  }
1602254721Semaste}
1603254721Semaste
1604353358Sdimvoid Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1605360784Sdim  ModulesDidUnload(module_list, false);
1606353358Sdim}
1607353358Sdim
1608314564Sdimvoid Target::ModulesDidLoad(ModuleList &module_list) {
1609353358Sdim  const size_t num_images = module_list.GetSize();
1610353358Sdim  if (m_valid && num_images) {
1611353358Sdim    for (size_t idx = 0; idx < num_images; ++idx) {
1612353358Sdim      ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1613353358Sdim      LoadScriptingResourceForModule(module_sp, this);
1614353358Sdim    }
1615314564Sdim    m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1616314564Sdim    m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1617314564Sdim    if (m_process_sp) {
1618314564Sdim      m_process_sp->ModulesDidLoad(module_list);
1619296417Sdim    }
1620314564Sdim    BroadcastEvent(eBroadcastBitModulesLoaded,
1621314564Sdim                   new TargetEventData(this->shared_from_this(), module_list));
1622314564Sdim  }
1623254721Semaste}
1624254721Semaste
1625314564Sdimvoid Target::SymbolsDidLoad(ModuleList &module_list) {
1626314564Sdim  if (m_valid && module_list.GetSize()) {
1627314564Sdim    if (m_process_sp) {
1628353358Sdim      for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1629353358Sdim        runtime->SymbolsDidLoad(module_list);
1630314564Sdim      }
1631254721Semaste    }
1632314564Sdim
1633314564Sdim    m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1634314564Sdim    m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1635314564Sdim    BroadcastEvent(eBroadcastBitSymbolsLoaded,
1636314564Sdim                   new TargetEventData(this->shared_from_this(), module_list));
1637314564Sdim  }
1638254721Semaste}
1639254721Semaste
1640314564Sdimvoid Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1641314564Sdim  if (m_valid && module_list.GetSize()) {
1642314564Sdim    UnloadModuleSections(module_list);
1643314564Sdim    m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1644314564Sdim    m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1645314564Sdim                                                 delete_locations);
1646314564Sdim    BroadcastEvent(eBroadcastBitModulesUnloaded,
1647314564Sdim                   new TargetEventData(this->shared_from_this(), module_list));
1648314564Sdim  }
1649254721Semaste}
1650254721Semaste
1651314564Sdimbool Target::ModuleIsExcludedForUnconstrainedSearches(
1652314564Sdim    const FileSpec &module_file_spec) {
1653314564Sdim  if (GetBreakpointsConsultPlatformAvoidList()) {
1654314564Sdim    ModuleList matchingModules;
1655314564Sdim    ModuleSpec module_spec(module_file_spec);
1656360784Sdim    GetImages().FindModules(module_spec, matchingModules);
1657360784Sdim    size_t num_modules = matchingModules.GetSize();
1658314564Sdim
1659360784Sdim    // If there is more than one module for this file spec, only
1660360784Sdim    // return true if ALL the modules are on the black list.
1661314564Sdim    if (num_modules > 0) {
1662314564Sdim      for (size_t i = 0; i < num_modules; i++) {
1663314564Sdim        if (!ModuleIsExcludedForUnconstrainedSearches(
1664314564Sdim                matchingModules.GetModuleAtIndex(i)))
1665314564Sdim          return false;
1666314564Sdim      }
1667314564Sdim      return true;
1668254721Semaste    }
1669314564Sdim  }
1670314564Sdim  return false;
1671254721Semaste}
1672254721Semaste
1673314564Sdimbool Target::ModuleIsExcludedForUnconstrainedSearches(
1674314564Sdim    const lldb::ModuleSP &module_sp) {
1675314564Sdim  if (GetBreakpointsConsultPlatformAvoidList()) {
1676314564Sdim    if (m_platform_sp)
1677314564Sdim      return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1678314564Sdim                                                                     module_sp);
1679314564Sdim  }
1680314564Sdim  return false;
1681254721Semaste}
1682254721Semaste
1683314564Sdimsize_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1684321369Sdim                                       size_t dst_len, Status &error) {
1685314564Sdim  SectionSP section_sp(addr.GetSection());
1686314564Sdim  if (section_sp) {
1687314564Sdim    // If the contents of this section are encrypted, the on-disk file is
1688314564Sdim    // unusable.  Read only from live memory.
1689314564Sdim    if (section_sp->IsEncrypted()) {
1690314564Sdim      error.SetErrorString("section is encrypted");
1691314564Sdim      return 0;
1692254721Semaste    }
1693314564Sdim    ModuleSP module_sp(section_sp->GetModule());
1694314564Sdim    if (module_sp) {
1695314564Sdim      ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1696314564Sdim      if (objfile) {
1697314564Sdim        size_t bytes_read = objfile->ReadSectionData(
1698314564Sdim            section_sp.get(), addr.GetOffset(), dst, dst_len);
1699314564Sdim        if (bytes_read > 0)
1700314564Sdim          return bytes_read;
1701254721Semaste        else
1702314564Sdim          error.SetErrorStringWithFormat("error reading data from section %s",
1703314564Sdim                                         section_sp->GetName().GetCString());
1704314564Sdim      } else
1705314564Sdim        error.SetErrorString("address isn't from a object file");
1706314564Sdim    } else
1707314564Sdim      error.SetErrorString("address isn't in a module");
1708314564Sdim  } else
1709314564Sdim    error.SetErrorString("address doesn't contain a section that points to a "
1710314564Sdim                         "section in a object file");
1711254721Semaste
1712314564Sdim  return 0;
1713254721Semaste}
1714254721Semaste
1715314564Sdimsize_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1716321369Sdim                          void *dst, size_t dst_len, Status &error,
1717314564Sdim                          lldb::addr_t *load_addr_ptr) {
1718314564Sdim  error.Clear();
1719254721Semaste
1720341825Sdim  // if we end up reading this from process memory, we will fill this with the
1721341825Sdim  // actual load address
1722314564Sdim  if (load_addr_ptr)
1723314564Sdim    *load_addr_ptr = LLDB_INVALID_ADDRESS;
1724254721Semaste
1725314564Sdim  size_t bytes_read = 0;
1726314564Sdim
1727314564Sdim  addr_t load_addr = LLDB_INVALID_ADDRESS;
1728314564Sdim  addr_t file_addr = LLDB_INVALID_ADDRESS;
1729314564Sdim  Address resolved_addr;
1730314564Sdim  if (!addr.IsSectionOffset()) {
1731314564Sdim    SectionLoadList &section_load_list = GetSectionLoadList();
1732314564Sdim    if (section_load_list.IsEmpty()) {
1733341825Sdim      // No sections are loaded, so we must assume we are not running yet and
1734341825Sdim      // anything we are given is a file address.
1735314564Sdim      file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1736314564Sdim                                    // offset is the file address
1737314564Sdim      m_images.ResolveFileAddress(file_addr, resolved_addr);
1738314564Sdim    } else {
1739341825Sdim      // We have at least one section loaded. This can be because we have
1740341825Sdim      // manually loaded some sections with "target modules load ..." or
1741341825Sdim      // because we have have a live process that has sections loaded through
1742341825Sdim      // the dynamic loader
1743314564Sdim      load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1744314564Sdim                                    // offset is the load address
1745314564Sdim      section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1746254721Semaste    }
1747314564Sdim  }
1748314564Sdim  if (!resolved_addr.IsValid())
1749314564Sdim    resolved_addr = addr;
1750254721Semaste
1751314564Sdim  if (prefer_file_cache) {
1752314564Sdim    bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1753314564Sdim    if (bytes_read > 0)
1754314564Sdim      return bytes_read;
1755314564Sdim  }
1756314564Sdim
1757314564Sdim  if (ProcessIsValid()) {
1758314564Sdim    if (load_addr == LLDB_INVALID_ADDRESS)
1759314564Sdim      load_addr = resolved_addr.GetLoadAddress(this);
1760314564Sdim
1761314564Sdim    if (load_addr == LLDB_INVALID_ADDRESS) {
1762314564Sdim      ModuleSP addr_module_sp(resolved_addr.GetModule());
1763314564Sdim      if (addr_module_sp && addr_module_sp->GetFileSpec())
1764314564Sdim        error.SetErrorStringWithFormatv(
1765314564Sdim            "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1766314564Sdim            addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1767314564Sdim      else
1768314564Sdim        error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1769314564Sdim                                       resolved_addr.GetFileAddress());
1770314564Sdim    } else {
1771314564Sdim      bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1772314564Sdim      if (bytes_read != dst_len) {
1773314564Sdim        if (error.Success()) {
1774314564Sdim          if (bytes_read == 0)
1775314564Sdim            error.SetErrorStringWithFormat(
1776314564Sdim                "read memory from 0x%" PRIx64 " failed", load_addr);
1777314564Sdim          else
1778314564Sdim            error.SetErrorStringWithFormat(
1779314564Sdim                "only %" PRIu64 " of %" PRIu64
1780314564Sdim                " bytes were read from memory at 0x%" PRIx64,
1781314564Sdim                (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1782254721Semaste        }
1783314564Sdim      }
1784314564Sdim      if (bytes_read) {
1785314564Sdim        if (load_addr_ptr)
1786314564Sdim          *load_addr_ptr = load_addr;
1787314564Sdim        return bytes_read;
1788314564Sdim      }
1789341825Sdim      // If the address is not section offset we have an address that doesn't
1790341825Sdim      // resolve to any address in any currently loaded shared libraries and we
1791341825Sdim      // failed to read memory so there isn't anything more we can do. If it is
1792341825Sdim      // section offset, we might be able to read cached memory from the object
1793341825Sdim      // file.
1794314564Sdim      if (!resolved_addr.IsSectionOffset())
1795314564Sdim        return 0;
1796254721Semaste    }
1797314564Sdim  }
1798314564Sdim
1799314564Sdim  if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1800341825Sdim    // If we didn't already try and read from the object file cache, then try
1801341825Sdim    // it after failing to read from the process.
1802314564Sdim    return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1803314564Sdim  }
1804314564Sdim  return 0;
1805254721Semaste}
1806254721Semaste
1807314564Sdimsize_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1808321369Sdim                                     Status &error) {
1809314564Sdim  char buf[256];
1810314564Sdim  out_str.clear();
1811314564Sdim  addr_t curr_addr = addr.GetLoadAddress(this);
1812314564Sdim  Address address(addr);
1813353358Sdim  while (true) {
1814314564Sdim    size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1815314564Sdim    if (length == 0)
1816314564Sdim      break;
1817314564Sdim    out_str.append(buf, length);
1818341825Sdim    // If we got "length - 1" bytes, we didn't get the whole C string, we need
1819341825Sdim    // to read some more characters
1820314564Sdim    if (length == sizeof(buf) - 1)
1821314564Sdim      curr_addr += length;
1822314564Sdim    else
1823314564Sdim      break;
1824314564Sdim    address = Address(curr_addr);
1825314564Sdim  }
1826314564Sdim  return out_str.size();
1827314564Sdim}
1828314564Sdim
1829314564Sdimsize_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1830321369Sdim                                     size_t dst_max_len, Status &result_error) {
1831314564Sdim  size_t total_cstr_len = 0;
1832314564Sdim  if (dst && dst_max_len) {
1833314564Sdim    result_error.Clear();
1834314564Sdim    // NULL out everything just to be safe
1835314564Sdim    memset(dst, 0, dst_max_len);
1836321369Sdim    Status error;
1837254721Semaste    addr_t curr_addr = addr.GetLoadAddress(this);
1838254721Semaste    Address address(addr);
1839254721Semaste
1840341825Sdim    // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1841341825Sdim    // this really needs to be tied to the memory cache subsystem's cache line
1842341825Sdim    // size, so leave this as a fixed constant.
1843314564Sdim    const size_t cache_line_size = 512;
1844280031Sdim
1845314564Sdim    size_t bytes_left = dst_max_len - 1;
1846314564Sdim    char *curr_dst = dst;
1847280031Sdim
1848314564Sdim    while (bytes_left > 0) {
1849314564Sdim      addr_t cache_line_bytes_left =
1850314564Sdim          cache_line_size - (curr_addr % cache_line_size);
1851314564Sdim      addr_t bytes_to_read =
1852314564Sdim          std::min<addr_t>(bytes_left, cache_line_bytes_left);
1853314564Sdim      size_t bytes_read =
1854314564Sdim          ReadMemory(address, false, curr_dst, bytes_to_read, error);
1855314564Sdim
1856314564Sdim      if (bytes_read == 0) {
1857314564Sdim        result_error = error;
1858314564Sdim        dst[total_cstr_len] = '\0';
1859314564Sdim        break;
1860314564Sdim      }
1861314564Sdim      const size_t len = strlen(curr_dst);
1862314564Sdim
1863314564Sdim      total_cstr_len += len;
1864314564Sdim
1865314564Sdim      if (len < bytes_to_read)
1866314564Sdim        break;
1867314564Sdim
1868314564Sdim      curr_dst += bytes_read;
1869314564Sdim      curr_addr += bytes_read;
1870314564Sdim      bytes_left -= bytes_read;
1871314564Sdim      address = Address(curr_addr);
1872254721Semaste    }
1873314564Sdim  } else {
1874314564Sdim    if (dst == nullptr)
1875314564Sdim      result_error.SetErrorString("invalid arguments");
1876254721Semaste    else
1877314564Sdim      result_error.Clear();
1878314564Sdim  }
1879314564Sdim  return total_cstr_len;
1880254721Semaste}
1881254721Semaste
1882314564Sdimsize_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1883314564Sdim                                           bool prefer_file_cache,
1884314564Sdim                                           uint32_t byte_size, bool is_signed,
1885321369Sdim                                           Scalar &scalar, Status &error) {
1886314564Sdim  uint64_t uval;
1887314564Sdim
1888314564Sdim  if (byte_size <= sizeof(uval)) {
1889314564Sdim    size_t bytes_read =
1890314564Sdim        ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1891314564Sdim    if (bytes_read == byte_size) {
1892327952Sdim      DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1893327952Sdim                         m_arch.GetSpec().GetAddressByteSize());
1894314564Sdim      lldb::offset_t offset = 0;
1895314564Sdim      if (byte_size <= 4)
1896314564Sdim        scalar = data.GetMaxU32(&offset, byte_size);
1897314564Sdim      else
1898314564Sdim        scalar = data.GetMaxU64(&offset, byte_size);
1899314564Sdim
1900314564Sdim      if (is_signed)
1901314564Sdim        scalar.SignExtend(byte_size * 8);
1902314564Sdim      return bytes_read;
1903254721Semaste    }
1904314564Sdim  } else {
1905314564Sdim    error.SetErrorStringWithFormat(
1906314564Sdim        "byte size of %u is too large for integer scalar type", byte_size);
1907314564Sdim  }
1908314564Sdim  return 0;
1909254721Semaste}
1910254721Semaste
1911314564Sdimuint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1912314564Sdim                                               bool prefer_file_cache,
1913314564Sdim                                               size_t integer_byte_size,
1914314564Sdim                                               uint64_t fail_value,
1915321369Sdim                                               Status &error) {
1916314564Sdim  Scalar scalar;
1917314564Sdim  if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1918314564Sdim                                  false, scalar, error))
1919314564Sdim    return scalar.ULongLong(fail_value);
1920314564Sdim  return fail_value;
1921254721Semaste}
1922254721Semaste
1923314564Sdimbool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1924321369Sdim                                   Status &error, Address &pointer_addr) {
1925314564Sdim  Scalar scalar;
1926314564Sdim  if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1927360784Sdim                                  m_arch.GetSpec().GetAddressByteSize(), false,
1928360784Sdim                                  scalar, error)) {
1929314564Sdim    addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1930314564Sdim    if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1931314564Sdim      SectionLoadList &section_load_list = GetSectionLoadList();
1932314564Sdim      if (section_load_list.IsEmpty()) {
1933341825Sdim        // No sections are loaded, so we must assume we are not running yet and
1934341825Sdim        // anything we are given is a file address.
1935314564Sdim        m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1936314564Sdim      } else {
1937341825Sdim        // We have at least one section loaded. This can be because we have
1938341825Sdim        // manually loaded some sections with "target modules load ..." or
1939341825Sdim        // because we have have a live process that has sections loaded through
1940341825Sdim        // the dynamic loader
1941314564Sdim        section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1942314564Sdim      }
1943341825Sdim      // We weren't able to resolve the pointer value, so just return an
1944341825Sdim      // address with no section
1945314564Sdim      if (!pointer_addr.IsValid())
1946314564Sdim        pointer_addr.SetOffset(pointer_vm_addr);
1947314564Sdim      return true;
1948254721Semaste    }
1949314564Sdim  }
1950314564Sdim  return false;
1951254721Semaste}
1952254721Semaste
1953353358SdimModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
1954353358Sdim                                   Status *error_ptr) {
1955314564Sdim  ModuleSP module_sp;
1956254721Semaste
1957321369Sdim  Status error;
1958254721Semaste
1959314564Sdim  // First see if we already have this module in our module list.  If we do,
1960341825Sdim  // then we're done, we don't need to consult the shared modules list.  But
1961341825Sdim  // only do this if we are passed a UUID.
1962314564Sdim
1963314564Sdim  if (module_spec.GetUUID().IsValid())
1964314564Sdim    module_sp = m_images.FindFirstModule(module_spec);
1965314564Sdim
1966314564Sdim  if (!module_sp) {
1967314564Sdim    ModuleSP old_module_sp; // This will get filled in if we have a new version
1968314564Sdim                            // of the library
1969314564Sdim    bool did_create_module = false;
1970353358Sdim    FileSpecList search_paths = GetExecutableSearchPaths();
1971314564Sdim    // If there are image search path entries, try to use them first to acquire
1972314564Sdim    // a suitable image.
1973314564Sdim    if (m_image_search_paths.GetSize()) {
1974314564Sdim      ModuleSpec transformed_spec(module_spec);
1975314564Sdim      if (m_image_search_paths.RemapPath(
1976314564Sdim              module_spec.GetFileSpec().GetDirectory(),
1977314564Sdim              transformed_spec.GetFileSpec().GetDirectory())) {
1978314564Sdim        transformed_spec.GetFileSpec().GetFilename() =
1979314564Sdim            module_spec.GetFileSpec().GetFilename();
1980314564Sdim        error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1981360784Sdim                                            &search_paths, &old_module_sp,
1982360784Sdim                                            &did_create_module);
1983314564Sdim      }
1984314564Sdim    }
1985314564Sdim
1986314564Sdim    if (!module_sp) {
1987314564Sdim      // If we have a UUID, we can check our global shared module list in case
1988314564Sdim      // we already have it. If we don't have a valid UUID, then we can't since
1989314564Sdim      // the path in "module_spec" will be a platform path, and we will need to
1990314564Sdim      // let the platform find that file. For example, we could be asking for
1991314564Sdim      // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1992314564Sdim      // the local copy of "/usr/lib/dyld" since our platform could be a remote
1993314564Sdim      // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1994314564Sdim      // cache.
1995314564Sdim      if (module_spec.GetUUID().IsValid()) {
1996314564Sdim        // We have a UUID, it is OK to check the global module list...
1997360784Sdim        error =
1998360784Sdim            ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
1999360784Sdim                                        &old_module_sp, &did_create_module);
2000314564Sdim      }
2001314564Sdim
2002314564Sdim      if (!module_sp) {
2003314564Sdim        // The platform is responsible for finding and caching an appropriate
2004314564Sdim        // module in the shared module cache.
2005314564Sdim        if (m_platform_sp) {
2006314564Sdim          error = m_platform_sp->GetSharedModule(
2007360784Sdim              module_spec, m_process_sp.get(), module_sp, &search_paths,
2008360784Sdim              &old_module_sp, &did_create_module);
2009314564Sdim        } else {
2010314564Sdim          error.SetErrorString("no platform is currently set");
2011254721Semaste        }
2012314564Sdim      }
2013314564Sdim    }
2014254721Semaste
2015314564Sdim    // We found a module that wasn't in our target list.  Let's make sure that
2016341825Sdim    // there wasn't an equivalent module in the list already, and if there was,
2017341825Sdim    // let's remove it.
2018314564Sdim    if (module_sp) {
2019314564Sdim      ObjectFile *objfile = module_sp->GetObjectFile();
2020314564Sdim      if (objfile) {
2021314564Sdim        switch (objfile->GetType()) {
2022314564Sdim        case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2023314564Sdim                                        /// a program's execution state
2024314564Sdim        case ObjectFile::eTypeExecutable:    /// A normal executable
2025314564Sdim        case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2026314564Sdim                                             /// executable
2027314564Sdim        case ObjectFile::eTypeObjectFile:    /// An intermediate object file
2028314564Sdim        case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2029314564Sdim                                             /// used during execution
2030314564Sdim          break;
2031314564Sdim        case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2032314564Sdim                                         /// debug information
2033314564Sdim          if (error_ptr)
2034314564Sdim            error_ptr->SetErrorString("debug info files aren't valid target "
2035314564Sdim                                      "modules, please specify an executable");
2036314564Sdim          return ModuleSP();
2037314564Sdim        case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2038314564Sdim                                           /// against but not used for
2039314564Sdim                                           /// execution
2040314564Sdim          if (error_ptr)
2041314564Sdim            error_ptr->SetErrorString("stub libraries aren't valid target "
2042314564Sdim                                      "modules, please specify an executable");
2043314564Sdim          return ModuleSP();
2044314564Sdim        default:
2045314564Sdim          if (error_ptr)
2046314564Sdim            error_ptr->SetErrorString(
2047314564Sdim                "unsupported file type, please specify an executable");
2048314564Sdim          return ModuleSP();
2049254721Semaste        }
2050314564Sdim        // GetSharedModule is not guaranteed to find the old shared module, for
2051341825Sdim        // instance in the common case where you pass in the UUID, it is only
2052341825Sdim        // going to find the one module matching the UUID.  In fact, it has no
2053341825Sdim        // good way to know what the "old module" relevant to this target is,
2054341825Sdim        // since there might be many copies of a module with this file spec in
2055341825Sdim        // various running debug sessions, but only one of them will belong to
2056341825Sdim        // this target. So let's remove the UUID from the module list, and look
2057341825Sdim        // in the target's module list. Only do this if there is SOMETHING else
2058341825Sdim        // in the module spec...
2059314564Sdim        if (!old_module_sp) {
2060314564Sdim          if (module_spec.GetUUID().IsValid() &&
2061314564Sdim              !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2062314564Sdim              !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2063314564Sdim            ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2064314564Sdim            module_spec_copy.GetUUID().Clear();
2065254721Semaste
2066314564Sdim            ModuleList found_modules;
2067360784Sdim            m_images.FindModules(module_spec_copy, found_modules);
2068360784Sdim            if (found_modules.GetSize() == 1)
2069314564Sdim              old_module_sp = found_modules.GetModuleAtIndex(0);
2070314564Sdim          }
2071254721Semaste        }
2072314564Sdim
2073321369Sdim        // Preload symbols outside of any lock, so hopefully we can do this for
2074321369Sdim        // each library in parallel.
2075321369Sdim        if (GetPreloadSymbols())
2076321369Sdim          module_sp->PreloadSymbols();
2077321369Sdim
2078360784Sdim        if (old_module_sp && m_images.GetIndexForModule(old_module_sp.get()) !=
2079360784Sdim                                 LLDB_INVALID_INDEX32) {
2080314564Sdim          m_images.ReplaceModule(old_module_sp, module_sp);
2081314564Sdim          Module *old_module_ptr = old_module_sp.get();
2082314564Sdim          old_module_sp.reset();
2083314564Sdim          ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2084353358Sdim        } else {
2085353358Sdim          m_images.Append(module_sp, notify);
2086353358Sdim        }
2087314564Sdim      } else
2088314564Sdim        module_sp.reset();
2089254721Semaste    }
2090314564Sdim  }
2091314564Sdim  if (error_ptr)
2092314564Sdim    *error_ptr = error;
2093314564Sdim  return module_sp;
2094254721Semaste}
2095254721Semaste
2096314564SdimTargetSP Target::CalculateTarget() { return shared_from_this(); }
2097254721Semaste
2098314564SdimProcessSP Target::CalculateProcess() { return m_process_sp; }
2099254721Semaste
2100314564SdimThreadSP Target::CalculateThread() { return ThreadSP(); }
2101254721Semaste
2102314564SdimStackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2103254721Semaste
2104314564Sdimvoid Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2105314564Sdim  exe_ctx.Clear();
2106314564Sdim  exe_ctx.SetTargetPtr(this);
2107254721Semaste}
2108254721Semaste
2109314564SdimPathMappingList &Target::GetImageSearchPathList() {
2110314564Sdim  return m_image_search_paths;
2111254721Semaste}
2112254721Semaste
2113314564Sdimvoid Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2114314564Sdim                                     void *baton) {
2115314564Sdim  Target *target = (Target *)baton;
2116314564Sdim  ModuleSP exe_module_sp(target->GetExecutableModule());
2117314564Sdim  if (exe_module_sp)
2118344779Sdim    target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2119254721Semaste}
2120254721Semaste
2121360784Sdimllvm::Expected<TypeSystem &>
2122360784SdimTarget::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2123360784Sdim                                        bool create_on_demand) {
2124314564Sdim  if (!m_valid)
2125360784Sdim    return llvm::make_error<llvm::StringError>("Invalid Target",
2126360784Sdim                                               llvm::inconvertibleErrorCode());
2127314564Sdim
2128314564Sdim  if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2129314564Sdim                                             // assembly code
2130314564Sdim      || language == eLanguageTypeUnknown) {
2131360784Sdim    LanguageSet languages_for_expressions =
2132360784Sdim        Language::GetLanguagesSupportingTypeSystemsForExpressions();
2133314564Sdim
2134360784Sdim    if (languages_for_expressions[eLanguageTypeC]) {
2135314564Sdim      language = eLanguageTypeC; // LLDB's default.  Override by setting the
2136314564Sdim                                 // target language.
2137314564Sdim    } else {
2138360784Sdim      if (languages_for_expressions.Empty())
2139360784Sdim        return llvm::make_error<llvm::StringError>(
2140360784Sdim            "No expression support for any languages",
2141360784Sdim            llvm::inconvertibleErrorCode());
2142360784Sdim      language = (LanguageType)languages_for_expressions.bitvector.find_first();
2143296417Sdim    }
2144314564Sdim  }
2145296417Sdim
2146314564Sdim  return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2147314564Sdim                                                            create_on_demand);
2148296417Sdim}
2149296417Sdim
2150360784Sdimstd::vector<TypeSystem *> Target::GetScratchTypeSystems(bool create_on_demand) {
2151360784Sdim  if (!m_valid)
2152360784Sdim    return {};
2153360784Sdim
2154360784Sdim  std::vector<TypeSystem *> scratch_type_systems;
2155360784Sdim
2156360784Sdim  LanguageSet languages_for_expressions =
2157360784Sdim      Language::GetLanguagesSupportingTypeSystemsForExpressions();
2158360784Sdim
2159360784Sdim  for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2160360784Sdim    auto language = (LanguageType)bit;
2161360784Sdim    auto type_system_or_err =
2162360784Sdim        GetScratchTypeSystemForLanguage(language, create_on_demand);
2163360784Sdim    if (!type_system_or_err)
2164360784Sdim      LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2165360784Sdim                     type_system_or_err.takeError(),
2166360784Sdim                     "Language '{}' has expression support but no scratch type "
2167360784Sdim                     "system available",
2168360784Sdim                     Language::GetNameForLanguageType(language));
2169360784Sdim    else
2170360784Sdim      scratch_type_systems.emplace_back(&type_system_or_err.get());
2171360784Sdim  }
2172360784Sdim
2173360784Sdim  return scratch_type_systems;
2174360784Sdim}
2175360784Sdim
2176296417SdimPersistentExpressionState *
2177314564SdimTarget::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2178360784Sdim  auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2179314564Sdim
2180360784Sdim  if (auto err = type_system_or_err.takeError()) {
2181360784Sdim    LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2182360784Sdim                   std::move(err),
2183360784Sdim                   "Unable to get persistent expression state for language {}",
2184360784Sdim                   Language::GetNameForLanguageType(language));
2185314564Sdim    return nullptr;
2186314564Sdim  }
2187360784Sdim
2188360784Sdim  return type_system_or_err->GetPersistentExpressionState();
2189296417Sdim}
2190296417Sdim
2191314564SdimUserExpression *Target::GetUserExpressionForLanguage(
2192314564Sdim    llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2193314564Sdim    Expression::ResultType desired_type,
2194360784Sdim    const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2195360784Sdim    Status &error) {
2196360784Sdim  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2197360784Sdim  if (auto err = type_system_or_err.takeError()) {
2198314564Sdim    error.SetErrorStringWithFormat(
2199314564Sdim        "Could not find type system for language %s: %s",
2200314564Sdim        Language::GetNameForLanguageType(language),
2201360784Sdim        llvm::toString(std::move(err)).c_str());
2202314564Sdim    return nullptr;
2203314564Sdim  }
2204314564Sdim
2205360784Sdim  auto *user_expr = type_system_or_err->GetUserExpression(
2206360784Sdim      expr, prefix, language, desired_type, options, ctx_obj);
2207314564Sdim  if (!user_expr)
2208314564Sdim    error.SetErrorStringWithFormat(
2209314564Sdim        "Could not create an expression for language %s",
2210314564Sdim        Language::GetNameForLanguageType(language));
2211314564Sdim
2212314564Sdim  return user_expr;
2213296417Sdim}
2214296417Sdim
2215314564SdimFunctionCaller *Target::GetFunctionCallerForLanguage(
2216314564Sdim    lldb::LanguageType language, const CompilerType &return_type,
2217314564Sdim    const Address &function_address, const ValueList &arg_value_list,
2218321369Sdim    const char *name, Status &error) {
2219360784Sdim  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2220360784Sdim  if (auto err = type_system_or_err.takeError()) {
2221314564Sdim    error.SetErrorStringWithFormat(
2222314564Sdim        "Could not find type system for language %s: %s",
2223314564Sdim        Language::GetNameForLanguageType(language),
2224360784Sdim        llvm::toString(std::move(err)).c_str());
2225360784Sdim    return nullptr;
2226314564Sdim  }
2227314564Sdim
2228360784Sdim  auto *persistent_fn = type_system_or_err->GetFunctionCaller(
2229360784Sdim      return_type, function_address, arg_value_list, name);
2230314564Sdim  if (!persistent_fn)
2231314564Sdim    error.SetErrorStringWithFormat(
2232314564Sdim        "Could not create an expression for language %s",
2233314564Sdim        Language::GetNameForLanguageType(language));
2234314564Sdim
2235314564Sdim  return persistent_fn;
2236296417Sdim}
2237296417Sdim
2238296417SdimUtilityFunction *
2239314564SdimTarget::GetUtilityFunctionForLanguage(const char *text,
2240314564Sdim                                      lldb::LanguageType language,
2241321369Sdim                                      const char *name, Status &error) {
2242360784Sdim  auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2243314564Sdim
2244360784Sdim  if (auto err = type_system_or_err.takeError()) {
2245314564Sdim    error.SetErrorStringWithFormat(
2246314564Sdim        "Could not find type system for language %s: %s",
2247314564Sdim        Language::GetNameForLanguageType(language),
2248360784Sdim        llvm::toString(std::move(err)).c_str());
2249360784Sdim    return nullptr;
2250314564Sdim  }
2251314564Sdim
2252360784Sdim  auto *utility_fn = type_system_or_err->GetUtilityFunction(text, name);
2253314564Sdim  if (!utility_fn)
2254314564Sdim    error.SetErrorStringWithFormat(
2255314564Sdim        "Could not create an expression for language %s",
2256314564Sdim        Language::GetNameForLanguageType(language));
2257314564Sdim
2258314564Sdim  return utility_fn;
2259296417Sdim}
2260296417Sdim
2261314564SdimClangASTImporterSP Target::GetClangASTImporter() {
2262314564Sdim  if (m_valid) {
2263314564Sdim    if (!m_ast_importer_sp) {
2264353358Sdim      m_ast_importer_sp = std::make_shared<ClangASTImporter>();
2265254721Semaste    }
2266314564Sdim    return m_ast_importer_sp;
2267314564Sdim  }
2268314564Sdim  return ClangASTImporterSP();
2269254721Semaste}
2270254721Semaste
2271314564Sdimvoid Target::SettingsInitialize() { Process::SettingsInitialize(); }
2272254721Semaste
2273314564Sdimvoid Target::SettingsTerminate() { Process::SettingsTerminate(); }
2274254721Semaste
2275314564SdimFileSpecList Target::GetDefaultExecutableSearchPaths() {
2276314564Sdim  TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2277314564Sdim  if (properties_sp)
2278314564Sdim    return properties_sp->GetExecutableSearchPaths();
2279314564Sdim  return FileSpecList();
2280254721Semaste}
2281254721Semaste
2282314564SdimFileSpecList Target::GetDefaultDebugFileSearchPaths() {
2283314564Sdim  TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2284314564Sdim  if (properties_sp)
2285314564Sdim    return properties_sp->GetDebugFileSearchPaths();
2286314564Sdim  return FileSpecList();
2287254721Semaste}
2288254721Semaste
2289314564SdimArchSpec Target::GetDefaultArchitecture() {
2290314564Sdim  TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2291314564Sdim  if (properties_sp)
2292314564Sdim    return properties_sp->GetDefaultArchitecture();
2293314564Sdim  return ArchSpec();
2294254721Semaste}
2295254721Semaste
2296314564Sdimvoid Target::SetDefaultArchitecture(const ArchSpec &arch) {
2297314564Sdim  TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2298314564Sdim  if (properties_sp) {
2299360784Sdim    LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
2300360784Sdim             "Target::SetDefaultArchitecture setting target's "
2301360784Sdim             "default architecture to  {0} ({1})",
2302360784Sdim             arch.GetArchitectureName(), arch.GetTriple().getTriple());
2303314564Sdim    return properties_sp->SetDefaultArchitecture(arch);
2304314564Sdim  }
2305254721Semaste}
2306254721Semaste
2307314564SdimTarget *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2308314564Sdim                                      const SymbolContext *sc_ptr) {
2309314564Sdim  // The target can either exist in the "process" of ExecutionContext, or in
2310314564Sdim  // the "target_sp" member of SymbolContext. This accessor helper function
2311314564Sdim  // will get the target from one of these locations.
2312254721Semaste
2313314564Sdim  Target *target = nullptr;
2314314564Sdim  if (sc_ptr != nullptr)
2315314564Sdim    target = sc_ptr->target_sp.get();
2316314564Sdim  if (target == nullptr && exe_ctx_ptr)
2317314564Sdim    target = exe_ctx_ptr->GetTargetPtr();
2318314564Sdim  return target;
2319254721Semaste}
2320254721Semaste
2321314564SdimExpressionResults Target::EvaluateExpression(
2322314564Sdim    llvm::StringRef expr, ExecutionContextScope *exe_scope,
2323314564Sdim    lldb::ValueObjectSP &result_valobj_sp,
2324353358Sdim    const EvaluateExpressionOptions &options, std::string *fixed_expression,
2325353358Sdim    ValueObject *ctx_obj) {
2326314564Sdim  result_valobj_sp.reset();
2327254721Semaste
2328314564Sdim  ExpressionResults execution_results = eExpressionSetupError;
2329254721Semaste
2330314564Sdim  if (expr.empty())
2331314564Sdim    return execution_results;
2332254721Semaste
2333353358Sdim  // We shouldn't run stop hooks in expressions.
2334314564Sdim  bool old_suppress_value = m_suppress_stop_hooks;
2335314564Sdim  m_suppress_stop_hooks = true;
2336353358Sdim  auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2337360784Sdim    m_suppress_stop_hooks = old_suppress_value;
2338360784Sdim  });
2339254721Semaste
2340314564Sdim  ExecutionContext exe_ctx;
2341314564Sdim
2342314564Sdim  if (exe_scope) {
2343314564Sdim    exe_scope->CalculateExecutionContext(exe_ctx);
2344314564Sdim  } else if (m_process_sp) {
2345314564Sdim    m_process_sp->CalculateExecutionContext(exe_ctx);
2346314564Sdim  } else {
2347314564Sdim    CalculateExecutionContext(exe_ctx);
2348314564Sdim  }
2349314564Sdim
2350341825Sdim  // Make sure we aren't just trying to see the value of a persistent variable
2351341825Sdim  // (something like "$0")
2352360784Sdim  // Only check for persistent variables the expression starts with a '$'
2353314564Sdim  lldb::ExpressionVariableSP persistent_var_sp;
2354360784Sdim  if (expr[0] == '$') {
2355360784Sdim    auto type_system_or_err =
2356360784Sdim            GetScratchTypeSystemForLanguage(eLanguageTypeC);
2357360784Sdim    if (auto err = type_system_or_err.takeError()) {
2358360784Sdim      LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2359360784Sdim                     std::move(err), "Unable to get scratch type system");
2360360784Sdim    } else {
2361360784Sdim      persistent_var_sp =
2362360784Sdim          type_system_or_err->GetPersistentExpressionState()->GetVariable(expr);
2363360784Sdim    }
2364360784Sdim  }
2365314564Sdim  if (persistent_var_sp) {
2366314564Sdim    result_valobj_sp = persistent_var_sp->GetValueObject();
2367314564Sdim    execution_results = eExpressionCompleted;
2368314564Sdim  } else {
2369327952Sdim    llvm::StringRef prefix = GetExpressionPrefixContents();
2370321369Sdim    Status error;
2371353358Sdim    execution_results =
2372353358Sdim        UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2373353358Sdim                                 result_valobj_sp, error, fixed_expression,
2374353358Sdim                                 nullptr, // Module
2375353358Sdim                                 ctx_obj);
2376314564Sdim  }
2377314564Sdim
2378314564Sdim  return execution_results;
2379254721Semaste}
2380254721Semaste
2381360784Sdimlldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2382314564Sdim  lldb::ExpressionVariableSP variable_sp;
2383314564Sdim  m_scratch_type_system_map.ForEach(
2384321369Sdim      [name, &variable_sp](TypeSystem *type_system) -> bool {
2385314564Sdim        if (PersistentExpressionState *persistent_state =
2386314564Sdim                type_system->GetPersistentExpressionState()) {
2387314564Sdim          variable_sp = persistent_state->GetVariable(name);
2388296417Sdim
2389314564Sdim          if (variable_sp)
2390314564Sdim            return false; // Stop iterating the ForEach
2391296417Sdim        }
2392314564Sdim        return true; // Keep iterating the ForEach
2393314564Sdim      });
2394314564Sdim  return variable_sp;
2395288943Sdim}
2396288943Sdim
2397353358Sdimlldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2398314564Sdim  lldb::addr_t address = LLDB_INVALID_ADDRESS;
2399314564Sdim
2400314564Sdim  m_scratch_type_system_map.ForEach(
2401321369Sdim      [name, &address](TypeSystem *type_system) -> bool {
2402314564Sdim        if (PersistentExpressionState *persistent_state =
2403314564Sdim                type_system->GetPersistentExpressionState()) {
2404314564Sdim          address = persistent_state->LookupSymbol(name);
2405314564Sdim          if (address != LLDB_INVALID_ADDRESS)
2406314564Sdim            return false; // Stop iterating the ForEach
2407296417Sdim        }
2408314564Sdim        return true; // Keep iterating the ForEach
2409314564Sdim      });
2410314564Sdim  return address;
2411296417Sdim}
2412296417Sdim
2413360784Sdimllvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2414360784Sdim  Module *exe_module = GetExecutableModulePointer();
2415360784Sdim
2416367228Sdim  // Try to find the entry point address in the primary executable.
2417367228Sdim  const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2418367228Sdim  if (has_primary_executable) {
2419360784Sdim    Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2420360784Sdim    if (entry_addr.IsValid())
2421360784Sdim      return entry_addr;
2422360784Sdim  }
2423360784Sdim
2424360784Sdim  const ModuleList &modules = GetImages();
2425360784Sdim  const size_t num_images = modules.GetSize();
2426360784Sdim  for (size_t idx = 0; idx < num_images; ++idx) {
2427360784Sdim    ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2428360784Sdim    if (!module_sp || !module_sp->GetObjectFile())
2429360784Sdim      continue;
2430360784Sdim
2431360784Sdim    Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2432367228Sdim    if (entry_addr.IsValid())
2433360784Sdim      return entry_addr;
2434360784Sdim  }
2435360784Sdim
2436367228Sdim  // We haven't found the entry point address. Return an appropriate error.
2437367228Sdim  if (!has_primary_executable)
2438367228Sdim    return llvm::make_error<llvm::StringError>(
2439367228Sdim        "No primary executable found and could not find entry point address in "
2440367228Sdim        "any executable module",
2441367228Sdim        llvm::inconvertibleErrorCode());
2442367228Sdim
2443367228Sdim  return llvm::make_error<llvm::StringError>(
2444367228Sdim      "Could not find entry point address for primary executable module \"" +
2445367228Sdim          exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2446367228Sdim      llvm::inconvertibleErrorCode());
2447360784Sdim}
2448360784Sdim
2449314564Sdimlldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2450314564Sdim                                            AddressClass addr_class) const {
2451344779Sdim  auto arch_plugin = GetArchitecturePlugin();
2452360784Sdim  return arch_plugin
2453360784Sdim             ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2454360784Sdim             : load_addr;
2455254721Semaste}
2456254721Semaste
2457314564Sdimlldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2458314564Sdim                                          AddressClass addr_class) const {
2459344779Sdim  auto arch_plugin = GetArchitecturePlugin();
2460360784Sdim  return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2461360784Sdim                     : load_addr;
2462254721Semaste}
2463254721Semaste
2464314564Sdimlldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2465344779Sdim  auto arch_plugin = GetArchitecturePlugin();
2466360784Sdim  return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2467296417Sdim}
2468296417Sdim
2469314564SdimSourceManager &Target::GetSourceManager() {
2470353358Sdim  if (!m_source_manager_up)
2471353358Sdim    m_source_manager_up.reset(new SourceManager(shared_from_this()));
2472353358Sdim  return *m_source_manager_up;
2473254721Semaste}
2474254721Semaste
2475314564SdimClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2476314564Sdim  static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2477314564Sdim                                                       // we can make it
2478314564Sdim                                                       // per-target
2479309124Sdim
2480314564Sdim  {
2481314564Sdim    std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2482309124Sdim
2483353358Sdim    if (!m_clang_modules_decl_vendor_up) {
2484353358Sdim      m_clang_modules_decl_vendor_up.reset(
2485314564Sdim          ClangModulesDeclVendor::Create(*this));
2486280031Sdim    }
2487314564Sdim  }
2488314564Sdim
2489353358Sdim  return m_clang_modules_decl_vendor_up.get();
2490280031Sdim}
2491254721Semaste
2492314564SdimTarget::StopHookSP Target::CreateStopHook() {
2493314564Sdim  lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2494314564Sdim  Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2495314564Sdim  m_stop_hooks[new_uid] = stop_hook_sp;
2496314564Sdim  return stop_hook_sp;
2497254721Semaste}
2498254721Semaste
2499314564Sdimbool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2500314564Sdim  size_t num_removed = m_stop_hooks.erase(user_id);
2501314564Sdim  return (num_removed != 0);
2502254721Semaste}
2503254721Semaste
2504314564Sdimvoid Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2505314564Sdim
2506314564SdimTarget::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2507314564Sdim  StopHookSP found_hook;
2508314564Sdim
2509314564Sdim  StopHookCollection::iterator specified_hook_iter;
2510314564Sdim  specified_hook_iter = m_stop_hooks.find(user_id);
2511314564Sdim  if (specified_hook_iter != m_stop_hooks.end())
2512314564Sdim    found_hook = (*specified_hook_iter).second;
2513314564Sdim  return found_hook;
2514254721Semaste}
2515254721Semaste
2516314564Sdimbool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2517314564Sdim                                        bool active_state) {
2518314564Sdim  StopHookCollection::iterator specified_hook_iter;
2519314564Sdim  specified_hook_iter = m_stop_hooks.find(user_id);
2520314564Sdim  if (specified_hook_iter == m_stop_hooks.end())
2521314564Sdim    return false;
2522314564Sdim
2523314564Sdim  (*specified_hook_iter).second->SetIsActive(active_state);
2524314564Sdim  return true;
2525254721Semaste}
2526254721Semaste
2527314564Sdimvoid Target::SetAllStopHooksActiveState(bool active_state) {
2528314564Sdim  StopHookCollection::iterator pos, end = m_stop_hooks.end();
2529314564Sdim  for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2530314564Sdim    (*pos).second->SetIsActive(active_state);
2531314564Sdim  }
2532254721Semaste}
2533254721Semaste
2534314564Sdimvoid Target::RunStopHooks() {
2535314564Sdim  if (m_suppress_stop_hooks)
2536314564Sdim    return;
2537314564Sdim
2538314564Sdim  if (!m_process_sp)
2539314564Sdim    return;
2540360784Sdim
2541327952Sdim  // Somebody might have restarted the process:
2542327952Sdim  if (m_process_sp->GetState() != eStateStopped)
2543327952Sdim    return;
2544314564Sdim
2545314564Sdim  // <rdar://problem/12027563> make sure we check that we are not stopped
2546341825Sdim  // because of us running a user expression since in that case we do not want
2547341825Sdim  // to run the stop-hooks
2548314564Sdim  if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2549314564Sdim    return;
2550314564Sdim
2551314564Sdim  if (m_stop_hooks.empty())
2552314564Sdim    return;
2553314564Sdim
2554314564Sdim  StopHookCollection::iterator pos, end = m_stop_hooks.end();
2555314564Sdim
2556353358Sdim  // If there aren't any active stop hooks, don't bother either.
2557353358Sdim  // Also see if any of the active hooks want to auto-continue.
2558314564Sdim  bool any_active_hooks = false;
2559353358Sdim  bool auto_continue = false;
2560353358Sdim  for (auto hook : m_stop_hooks) {
2561353358Sdim    if (hook.second->IsActive()) {
2562314564Sdim      any_active_hooks = true;
2563353358Sdim      auto_continue |= hook.second->GetAutoContinue();
2564254721Semaste    }
2565314564Sdim  }
2566314564Sdim  if (!any_active_hooks)
2567314564Sdim    return;
2568254721Semaste
2569314564Sdim  CommandReturnObject result;
2570314564Sdim
2571314564Sdim  std::vector<ExecutionContext> exc_ctx_with_reasons;
2572314564Sdim  std::vector<SymbolContext> sym_ctx_with_reasons;
2573314564Sdim
2574314564Sdim  ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2575314564Sdim  size_t num_threads = cur_threadlist.GetSize();
2576314564Sdim  for (size_t i = 0; i < num_threads; i++) {
2577314564Sdim    lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2578314564Sdim    if (cur_thread_sp->ThreadStoppedForAReason()) {
2579314564Sdim      lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2580314564Sdim      exc_ctx_with_reasons.push_back(ExecutionContext(
2581314564Sdim          m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2582314564Sdim      sym_ctx_with_reasons.push_back(
2583314564Sdim          cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2584254721Semaste    }
2585314564Sdim  }
2586314564Sdim
2587314564Sdim  // If no threads stopped for a reason, don't run the stop-hooks.
2588314564Sdim  size_t num_exe_ctx = exc_ctx_with_reasons.size();
2589314564Sdim  if (num_exe_ctx == 0)
2590314564Sdim    return;
2591314564Sdim
2592314564Sdim  result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2593314564Sdim  result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2594314564Sdim
2595314564Sdim  bool keep_going = true;
2596314564Sdim  bool hooks_ran = false;
2597314564Sdim  bool print_hook_header = (m_stop_hooks.size() != 1);
2598314564Sdim  bool print_thread_header = (num_exe_ctx != 1);
2599353358Sdim  bool did_restart = false;
2600314564Sdim
2601314564Sdim  for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2602314564Sdim    // result.Clear();
2603314564Sdim    StopHookSP cur_hook_sp = (*pos).second;
2604314564Sdim    if (!cur_hook_sp->IsActive())
2605314564Sdim      continue;
2606314564Sdim
2607314564Sdim    bool any_thread_matched = false;
2608314564Sdim    for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2609314564Sdim      if ((cur_hook_sp->GetSpecifier() == nullptr ||
2610314564Sdim           cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2611314564Sdim               sym_ctx_with_reasons[i])) &&
2612314564Sdim          (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2613314564Sdim           cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2614314564Sdim               exc_ctx_with_reasons[i].GetThreadRef()))) {
2615314564Sdim        if (!hooks_ran) {
2616314564Sdim          hooks_ran = true;
2617254721Semaste        }
2618314564Sdim        if (print_hook_header && !any_thread_matched) {
2619314564Sdim          const char *cmd =
2620314564Sdim              (cur_hook_sp->GetCommands().GetSize() == 1
2621314564Sdim                   ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2622314564Sdim                   : nullptr);
2623314564Sdim          if (cmd)
2624314564Sdim            result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2625314564Sdim                                           cur_hook_sp->GetID(), cmd);
2626314564Sdim          else
2627314564Sdim            result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2628314564Sdim                                           cur_hook_sp->GetID());
2629314564Sdim          any_thread_matched = true;
2630314564Sdim        }
2631280031Sdim
2632314564Sdim        if (print_thread_header)
2633314564Sdim          result.AppendMessageWithFormat(
2634314564Sdim              "-- Thread %d\n",
2635314564Sdim              exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2636280031Sdim
2637314564Sdim        CommandInterpreterRunOptions options;
2638314564Sdim        options.SetStopOnContinue(true);
2639314564Sdim        options.SetStopOnError(true);
2640314564Sdim        options.SetEchoCommands(false);
2641314564Sdim        options.SetPrintResults(true);
2642353358Sdim        options.SetPrintErrors(true);
2643314564Sdim        options.SetAddToHistory(false);
2644254721Semaste
2645353358Sdim        // Force Async:
2646353358Sdim        bool old_async = GetDebugger().GetAsyncExecution();
2647353358Sdim        GetDebugger().SetAsyncExecution(true);
2648314564Sdim        GetDebugger().GetCommandInterpreter().HandleCommands(
2649314564Sdim            cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2650314564Sdim            result);
2651353358Sdim        GetDebugger().SetAsyncExecution(old_async);
2652314564Sdim        // If the command started the target going again, we should bag out of
2653314564Sdim        // running the stop hooks.
2654314564Sdim        if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2655314564Sdim            (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2656327952Sdim          // But only complain if there were more stop hooks to do:
2657327952Sdim          StopHookCollection::iterator tmp = pos;
2658327952Sdim          if (++tmp != end)
2659360784Sdim            result.AppendMessageWithFormat(
2660360784Sdim                "\nAborting stop hooks, hook %" PRIu64
2661360784Sdim                " set the program running.\n"
2662360784Sdim                "  Consider using '-G true' to make "
2663360784Sdim                "stop hooks auto-continue.\n",
2664360784Sdim                cur_hook_sp->GetID());
2665314564Sdim          keep_going = false;
2666353358Sdim          did_restart = true;
2667254721Semaste        }
2668314564Sdim      }
2669254721Semaste    }
2670314564Sdim  }
2671353358Sdim  // Finally, if auto-continue was requested, do it now:
2672353358Sdim  if (!did_restart && auto_continue)
2673353358Sdim    m_process_sp->PrivateResume();
2674254721Semaste
2675314564Sdim  result.GetImmediateOutputStream()->Flush();
2676314564Sdim  result.GetImmediateErrorStream()->Flush();
2677254721Semaste}
2678254721Semaste
2679314564Sdimconst TargetPropertiesSP &Target::GetGlobalProperties() {
2680314564Sdim  // NOTE: intentional leak so we don't crash if global destructor chain gets
2681314564Sdim  // called as other threads still use the result of this function
2682314564Sdim  static TargetPropertiesSP *g_settings_sp_ptr =
2683314564Sdim      new TargetPropertiesSP(new TargetProperties(nullptr));
2684314564Sdim  return *g_settings_sp_ptr;
2685258884Semaste}
2686254721Semaste
2687321369SdimStatus Target::Install(ProcessLaunchInfo *launch_info) {
2688321369Sdim  Status error;
2689314564Sdim  PlatformSP platform_sp(GetPlatform());
2690314564Sdim  if (platform_sp) {
2691314564Sdim    if (platform_sp->IsRemote()) {
2692314564Sdim      if (platform_sp->IsConnected()) {
2693314564Sdim        // Install all files that have an install path, and always install the
2694314564Sdim        // main executable when connected to a remote platform
2695314564Sdim        const ModuleList &modules = GetImages();
2696314564Sdim        const size_t num_images = modules.GetSize();
2697314564Sdim        for (size_t idx = 0; idx < num_images; ++idx) {
2698314564Sdim          ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2699314564Sdim          if (module_sp) {
2700314564Sdim            const bool is_main_executable = module_sp == GetExecutableModule();
2701314564Sdim            FileSpec local_file(module_sp->GetFileSpec());
2702314564Sdim            if (local_file) {
2703314564Sdim              FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2704314564Sdim              if (!remote_file) {
2705314564Sdim                if (is_main_executable) // TODO: add setting for always
2706314564Sdim                                        // installing main executable???
2707258884Semaste                {
2708314564Sdim                  // Always install the main executable
2709314564Sdim                  remote_file = platform_sp->GetRemoteWorkingDirectory();
2710314564Sdim                  remote_file.AppendPathComponent(
2711314564Sdim                      module_sp->GetFileSpec().GetFilename().GetCString());
2712258884Semaste                }
2713314564Sdim              }
2714314564Sdim              if (remote_file) {
2715314564Sdim                error = platform_sp->Install(local_file, remote_file);
2716314564Sdim                if (error.Success()) {
2717314564Sdim                  module_sp->SetPlatformFileSpec(remote_file);
2718314564Sdim                  if (is_main_executable) {
2719314564Sdim                    platform_sp->SetFilePermissions(remote_file, 0700);
2720314564Sdim                    if (launch_info)
2721314564Sdim                      launch_info->SetExecutableFile(remote_file, false);
2722314564Sdim                  }
2723314564Sdim                } else
2724314564Sdim                  break;
2725314564Sdim              }
2726258884Semaste            }
2727314564Sdim          }
2728258884Semaste        }
2729314564Sdim      }
2730258884Semaste    }
2731314564Sdim  }
2732314564Sdim  return error;
2733258884Semaste}
2734258884Semaste
2735314564Sdimbool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2736314564Sdim                                uint32_t stop_id) {
2737314564Sdim  return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2738262528Semaste}
2739262528Semaste
2740314564Sdimbool Target::ResolveFileAddress(lldb::addr_t file_addr,
2741314564Sdim                                Address &resolved_addr) {
2742314564Sdim  return m_images.ResolveFileAddress(file_addr, resolved_addr);
2743280031Sdim}
2744280031Sdim
2745314564Sdimbool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2746314564Sdim                                   addr_t new_section_load_addr,
2747314564Sdim                                   bool warn_multiple) {
2748314564Sdim  const addr_t old_section_load_addr =
2749314564Sdim      m_section_load_history.GetSectionLoadAddress(
2750314564Sdim          SectionLoadHistory::eStopIDNow, section_sp);
2751314564Sdim  if (old_section_load_addr != new_section_load_addr) {
2752280031Sdim    uint32_t stop_id = 0;
2753280031Sdim    ProcessSP process_sp(GetProcessSP());
2754280031Sdim    if (process_sp)
2755314564Sdim      stop_id = process_sp->GetStopID();
2756280031Sdim    else
2757314564Sdim      stop_id = m_section_load_history.GetLastStopID();
2758314564Sdim    if (m_section_load_history.SetSectionLoadAddress(
2759314564Sdim            stop_id, section_sp, new_section_load_addr, warn_multiple))
2760314564Sdim      return true; // Return true if the section load address was changed...
2761314564Sdim  }
2762314564Sdim  return false; // Return false to indicate nothing changed
2763280031Sdim}
2764280031Sdim
2765314564Sdimsize_t Target::UnloadModuleSections(const ModuleList &module_list) {
2766314564Sdim  size_t section_unload_count = 0;
2767314564Sdim  size_t num_modules = module_list.GetSize();
2768314564Sdim  for (size_t i = 0; i < num_modules; ++i) {
2769314564Sdim    section_unload_count +=
2770314564Sdim        UnloadModuleSections(module_list.GetModuleAtIndex(i));
2771314564Sdim  }
2772314564Sdim  return section_unload_count;
2773262528Semaste}
2774262528Semaste
2775314564Sdimsize_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2776314564Sdim  uint32_t stop_id = 0;
2777314564Sdim  ProcessSP process_sp(GetProcessSP());
2778314564Sdim  if (process_sp)
2779314564Sdim    stop_id = process_sp->GetStopID();
2780314564Sdim  else
2781314564Sdim    stop_id = m_section_load_history.GetLastStopID();
2782314564Sdim  SectionList *sections = module_sp->GetSectionList();
2783314564Sdim  size_t section_unload_count = 0;
2784314564Sdim  if (sections) {
2785314564Sdim    const uint32_t num_sections = sections->GetNumSections(0);
2786314564Sdim    for (uint32_t i = 0; i < num_sections; ++i) {
2787314564Sdim      section_unload_count += m_section_load_history.SetSectionUnloaded(
2788314564Sdim          stop_id, sections->GetSectionAtIndex(i));
2789314564Sdim    }
2790314564Sdim  }
2791314564Sdim  return section_unload_count;
2792262528Semaste}
2793262528Semaste
2794314564Sdimbool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2795314564Sdim  uint32_t stop_id = 0;
2796314564Sdim  ProcessSP process_sp(GetProcessSP());
2797314564Sdim  if (process_sp)
2798314564Sdim    stop_id = process_sp->GetStopID();
2799314564Sdim  else
2800314564Sdim    stop_id = m_section_load_history.GetLastStopID();
2801314564Sdim  return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2802262528Semaste}
2803262528Semaste
2804314564Sdimbool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2805314564Sdim                                addr_t load_addr) {
2806314564Sdim  uint32_t stop_id = 0;
2807314564Sdim  ProcessSP process_sp(GetProcessSP());
2808314564Sdim  if (process_sp)
2809314564Sdim    stop_id = process_sp->GetStopID();
2810314564Sdim  else
2811314564Sdim    stop_id = m_section_load_history.GetLastStopID();
2812314564Sdim  return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2813314564Sdim                                                   load_addr);
2814314564Sdim}
2815280031Sdim
2816314564Sdimvoid Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2817280031Sdim
2818321369SdimStatus Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2819321369Sdim  Status error;
2820314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2821262528Semaste
2822360784Sdim  LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2823360784Sdim            launch_info.GetExecutableFile().GetPath().c_str());
2824280031Sdim
2825314564Sdim  StateType state = eStateInvalid;
2826314564Sdim
2827314564Sdim  // Scope to temporarily get the process state in case someone has manually
2828314564Sdim  // remotely connected already to a process and we can skip the platform
2829314564Sdim  // launching.
2830314564Sdim  {
2831314564Sdim    ProcessSP process_sp(GetProcessSP());
2832314564Sdim
2833314564Sdim    if (process_sp) {
2834314564Sdim      state = process_sp->GetState();
2835360784Sdim      LLDB_LOGF(log,
2836360784Sdim                "Target::%s the process exists, and its current state is %s",
2837360784Sdim                __FUNCTION__, StateAsCString(state));
2838314564Sdim    } else {
2839360784Sdim      LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2840360784Sdim                __FUNCTION__);
2841262528Semaste    }
2842314564Sdim  }
2843276479Sdim
2844314564Sdim  launch_info.GetFlags().Set(eLaunchFlagDebug);
2845280031Sdim
2846314564Sdim  // Get the value of synchronous execution here.  If you wait till after you
2847341825Sdim  // have started to run, then you could have hit a breakpoint, whose command
2848341825Sdim  // might switch the value, and then you'll pick up that incorrect value.
2849314564Sdim  Debugger &debugger = GetDebugger();
2850314564Sdim  const bool synchronous_execution =
2851314564Sdim      debugger.GetCommandInterpreter().GetSynchronous();
2852288943Sdim
2853314564Sdim  PlatformSP platform_sp(GetPlatform());
2854288943Sdim
2855344779Sdim  FinalizeFileActions(launch_info);
2856314564Sdim
2857314564Sdim  if (state == eStateConnected) {
2858314564Sdim    if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2859314564Sdim      error.SetErrorString(
2860314564Sdim          "can't launch in tty when launching through a remote connection");
2861314564Sdim      return error;
2862262528Semaste    }
2863314564Sdim  }
2864280031Sdim
2865314564Sdim  if (!launch_info.GetArchitecture().IsValid())
2866314564Sdim    launch_info.GetArchitecture() = GetArchitecture();
2867276479Sdim
2868314564Sdim  // If we're not already connected to the process, and if we have a platform
2869314564Sdim  // that can launch a process for debugging, go ahead and do that here.
2870314564Sdim  if (state != eStateConnected && platform_sp &&
2871314564Sdim      platform_sp->CanDebugProcess()) {
2872360784Sdim    LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2873360784Sdim              __FUNCTION__);
2874314564Sdim
2875344779Sdim    // If there was a previous process, delete it before we make the new one.
2876344779Sdim    // One subtle point, we delete the process before we release the reference
2877344779Sdim    // to m_process_sp.  That way even if we are the last owner, the process
2878344779Sdim    // will get Finalized before it gets destroyed.
2879344779Sdim    DeleteCurrentProcess();
2880360784Sdim
2881314564Sdim    m_process_sp =
2882314564Sdim        GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2883314564Sdim
2884314564Sdim  } else {
2885360784Sdim    LLDB_LOGF(log,
2886360784Sdim              "Target::%s the platform doesn't know how to debug a "
2887360784Sdim              "process, getting a process plugin to do this for us.",
2888360784Sdim              __FUNCTION__);
2889314564Sdim
2890314564Sdim    if (state == eStateConnected) {
2891314564Sdim      assert(m_process_sp);
2892314564Sdim    } else {
2893314564Sdim      // Use a Process plugin to construct the process.
2894314564Sdim      const char *plugin_name = launch_info.GetProcessPluginName();
2895344779Sdim      CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2896262528Semaste    }
2897262528Semaste
2898314564Sdim    // Since we didn't have a platform launch the process, launch it here.
2899314564Sdim    if (m_process_sp)
2900314564Sdim      error = m_process_sp->Launch(launch_info);
2901314564Sdim  }
2902314564Sdim
2903314564Sdim  if (!m_process_sp) {
2904262528Semaste    if (error.Success())
2905314564Sdim      error.SetErrorString("failed to launch or debug process");
2906314564Sdim    return error;
2907314564Sdim  }
2908280031Sdim
2909314564Sdim  if (error.Success()) {
2910314564Sdim    if (synchronous_execution ||
2911314564Sdim        !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2912314564Sdim      ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2913314564Sdim      if (!hijack_listener_sp) {
2914314564Sdim        hijack_listener_sp =
2915314564Sdim            Listener::MakeListener("lldb.Target.Launch.hijack");
2916314564Sdim        launch_info.SetHijackListener(hijack_listener_sp);
2917314564Sdim        m_process_sp->HijackProcessEvents(hijack_listener_sp);
2918314564Sdim      }
2919314564Sdim
2920314564Sdim      StateType state = m_process_sp->WaitForProcessToStop(
2921314564Sdim          llvm::None, nullptr, false, hijack_listener_sp, nullptr);
2922314564Sdim
2923314564Sdim      if (state == eStateStopped) {
2924314564Sdim        if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2925314564Sdim          if (synchronous_execution) {
2926360784Sdim            // Now we have handled the stop-from-attach, and we are just
2927360784Sdim            // switching to a synchronous resume.  So we should switch to the
2928360784Sdim            // SyncResume hijacker.
2929353358Sdim            m_process_sp->RestoreProcessEvents();
2930353358Sdim            m_process_sp->ResumeSynchronous(stream);
2931314564Sdim          } else {
2932314564Sdim            m_process_sp->RestoreProcessEvents();
2933314564Sdim            error = m_process_sp->PrivateResume();
2934314564Sdim          }
2935314564Sdim          if (!error.Success()) {
2936321369Sdim            Status error2;
2937314564Sdim            error2.SetErrorStringWithFormat(
2938314564Sdim                "process resume at entry point failed: %s", error.AsCString());
2939314564Sdim            error = error2;
2940314564Sdim          }
2941262528Semaste        }
2942314564Sdim      } else if (state == eStateExited) {
2943314564Sdim        bool with_shell = !!launch_info.GetShell();
2944314564Sdim        const int exit_status = m_process_sp->GetExitStatus();
2945314564Sdim        const char *exit_desc = m_process_sp->GetExitDescription();
2946314564Sdim#define LAUNCH_SHELL_MESSAGE                                                   \
2947314564Sdim  "\n'r' and 'run' are aliases that default to launching through a "           \
2948314564Sdim  "shell.\nTry launching without going through a shell by using 'process "     \
2949314564Sdim  "launch'."
2950314564Sdim        if (exit_desc && exit_desc[0]) {
2951314564Sdim          if (with_shell)
2952314564Sdim            error.SetErrorStringWithFormat(
2953314564Sdim                "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2954314564Sdim                exit_status, exit_desc);
2955314564Sdim          else
2956314564Sdim            error.SetErrorStringWithFormat("process exited with status %i (%s)",
2957314564Sdim                                           exit_status, exit_desc);
2958314564Sdim        } else {
2959314564Sdim          if (with_shell)
2960314564Sdim            error.SetErrorStringWithFormat(
2961314564Sdim                "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2962314564Sdim                exit_status);
2963314564Sdim          else
2964314564Sdim            error.SetErrorStringWithFormat("process exited with status %i",
2965314564Sdim                                           exit_status);
2966314564Sdim        }
2967314564Sdim      } else {
2968314564Sdim        error.SetErrorStringWithFormat(
2969314564Sdim            "initial process state wasn't stopped: %s", StateAsCString(state));
2970314564Sdim      }
2971262528Semaste    }
2972314564Sdim    m_process_sp->RestoreProcessEvents();
2973314564Sdim  } else {
2974321369Sdim    Status error2;
2975314564Sdim    error2.SetErrorStringWithFormat("process launch failed: %s",
2976314564Sdim                                    error.AsCString());
2977314564Sdim    error = error2;
2978314564Sdim  }
2979314564Sdim  return error;
2980262528Semaste}
2981288943Sdim
2982321369SdimStatus Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2983314564Sdim  auto state = eStateInvalid;
2984314564Sdim  auto process_sp = GetProcessSP();
2985314564Sdim  if (process_sp) {
2986314564Sdim    state = process_sp->GetState();
2987314564Sdim    if (process_sp->IsAlive() && state != eStateConnected) {
2988314564Sdim      if (state == eStateAttaching)
2989321369Sdim        return Status("process attach is in progress");
2990321369Sdim      return Status("a process is already being debugged");
2991288943Sdim    }
2992314564Sdim  }
2993288943Sdim
2994314564Sdim  const ModuleSP old_exec_module_sp = GetExecutableModule();
2995288943Sdim
2996341825Sdim  // If no process info was specified, then use the target executable name as
2997341825Sdim  // the process to attach to by default
2998314564Sdim  if (!attach_info.ProcessInfoSpecified()) {
2999314564Sdim    if (old_exec_module_sp)
3000314564Sdim      attach_info.GetExecutableFile().GetFilename() =
3001314564Sdim          old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3002288943Sdim
3003314564Sdim    if (!attach_info.ProcessInfoSpecified()) {
3004321369Sdim      return Status("no process specified, create a target with a file, or "
3005321369Sdim                    "specify the --pid or --name");
3006288943Sdim    }
3007314564Sdim  }
3008288943Sdim
3009314564Sdim  const auto platform_sp =
3010314564Sdim      GetDebugger().GetPlatformList().GetSelectedPlatform();
3011314564Sdim  ListenerSP hijack_listener_sp;
3012314564Sdim  const bool async = attach_info.GetAsync();
3013314564Sdim  if (!async) {
3014314564Sdim    hijack_listener_sp =
3015314564Sdim        Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3016314564Sdim    attach_info.SetHijackListener(hijack_listener_sp);
3017314564Sdim  }
3018288943Sdim
3019321369Sdim  Status error;
3020314564Sdim  if (state != eStateConnected && platform_sp != nullptr &&
3021314564Sdim      platform_sp->CanDebugProcess()) {
3022314564Sdim    SetPlatform(platform_sp);
3023314564Sdim    process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3024314564Sdim  } else {
3025314564Sdim    if (state != eStateConnected) {
3026314564Sdim      const char *plugin_name = attach_info.GetProcessPluginName();
3027314564Sdim      process_sp =
3028314564Sdim          CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3029314564Sdim                        plugin_name, nullptr);
3030314564Sdim      if (process_sp == nullptr) {
3031314564Sdim        error.SetErrorStringWithFormat(
3032314564Sdim            "failed to create process using plugin %s",
3033314564Sdim            (plugin_name) ? plugin_name : "null");
3034314564Sdim        return error;
3035314564Sdim      }
3036288943Sdim    }
3037314564Sdim    if (hijack_listener_sp)
3038314564Sdim      process_sp->HijackProcessEvents(hijack_listener_sp);
3039314564Sdim    error = process_sp->Attach(attach_info);
3040314564Sdim  }
3041288943Sdim
3042314564Sdim  if (error.Success() && process_sp) {
3043314564Sdim    if (async) {
3044314564Sdim      process_sp->RestoreProcessEvents();
3045314564Sdim    } else {
3046314564Sdim      state = process_sp->WaitForProcessToStop(
3047314564Sdim          llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3048314564Sdim      process_sp->RestoreProcessEvents();
3049314564Sdim
3050314564Sdim      if (state != eStateStopped) {
3051314564Sdim        const char *exit_desc = process_sp->GetExitDescription();
3052314564Sdim        if (exit_desc)
3053314564Sdim          error.SetErrorStringWithFormat("%s", exit_desc);
3054296417Sdim        else
3055314564Sdim          error.SetErrorString(
3056314564Sdim              "process did not stop (no such process or permission problem?)");
3057314564Sdim        process_sp->Destroy(false);
3058314564Sdim      }
3059288943Sdim    }
3060314564Sdim  }
3061314564Sdim  return error;
3062288943Sdim}
3063288943Sdim
3064344779Sdimvoid Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3065344779Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3066344779Sdim
3067344779Sdim  // Finalize the file actions, and if none were given, default to opening up a
3068344779Sdim  // pseudo terminal
3069344779Sdim  PlatformSP platform_sp = GetPlatform();
3070344779Sdim  const bool default_to_use_pty =
3071344779Sdim      m_platform_sp ? m_platform_sp->IsHost() : false;
3072344779Sdim  LLDB_LOG(
3073344779Sdim      log,
3074344779Sdim      "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3075344779Sdim      bool(platform_sp),
3076344779Sdim      platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3077344779Sdim      default_to_use_pty);
3078344779Sdim
3079344779Sdim  // If nothing for stdin or stdout or stderr was specified, then check the
3080344779Sdim  // process for any default settings that were set with "settings set"
3081344779Sdim  if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3082344779Sdim      info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3083344779Sdim      info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3084344779Sdim    LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3085344779Sdim                  "default handling");
3086344779Sdim
3087344779Sdim    if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3088344779Sdim      // Do nothing, if we are launching in a remote terminal no file actions
3089344779Sdim      // should be done at all.
3090344779Sdim      return;
3091344779Sdim    }
3092344779Sdim
3093344779Sdim    if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3094344779Sdim      LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3095344779Sdim                    "for stdin, stdout and stderr");
3096344779Sdim      info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3097344779Sdim      info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3098344779Sdim      info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3099344779Sdim    } else {
3100344779Sdim      // Check for any values that might have gotten set with any of: (lldb)
3101344779Sdim      // settings set target.input-path (lldb) settings set target.output-path
3102344779Sdim      // (lldb) settings set target.error-path
3103344779Sdim      FileSpec in_file_spec;
3104344779Sdim      FileSpec out_file_spec;
3105344779Sdim      FileSpec err_file_spec;
3106344779Sdim      // Only override with the target settings if we don't already have an
3107344779Sdim      // action for in, out or error
3108344779Sdim      if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3109344779Sdim        in_file_spec = GetStandardInputPath();
3110344779Sdim      if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3111344779Sdim        out_file_spec = GetStandardOutputPath();
3112344779Sdim      if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3113344779Sdim        err_file_spec = GetStandardErrorPath();
3114344779Sdim
3115344779Sdim      LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3116344779Sdim               in_file_spec, out_file_spec, err_file_spec);
3117344779Sdim
3118344779Sdim      if (in_file_spec) {
3119344779Sdim        info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3120344779Sdim        LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3121344779Sdim      }
3122344779Sdim
3123344779Sdim      if (out_file_spec) {
3124344779Sdim        info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3125344779Sdim        LLDB_LOG(log, "appended stdout open file action for {0}",
3126344779Sdim                 out_file_spec);
3127344779Sdim      }
3128344779Sdim
3129344779Sdim      if (err_file_spec) {
3130344779Sdim        info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3131344779Sdim        LLDB_LOG(log, "appended stderr open file action for {0}",
3132344779Sdim                 err_file_spec);
3133344779Sdim      }
3134344779Sdim
3135344779Sdim      if (default_to_use_pty &&
3136344779Sdim          (!in_file_spec || !out_file_spec || !err_file_spec)) {
3137344779Sdim        llvm::Error Err = info.SetUpPtyRedirection();
3138344779Sdim        LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3139344779Sdim      }
3140344779Sdim    }
3141344779Sdim  }
3142344779Sdim}
3143344779Sdim
3144258884Semaste// Target::StopHook
3145314564SdimTarget::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3146314564Sdim    : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3147353358Sdim      m_thread_spec_up() {}
3148314564Sdim
3149314564SdimTarget::StopHook::StopHook(const StopHook &rhs)
3150314564Sdim    : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3151314564Sdim      m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3152353358Sdim      m_thread_spec_up(), m_active(rhs.m_active),
3153353358Sdim      m_auto_continue(rhs.m_auto_continue) {
3154353358Sdim  if (rhs.m_thread_spec_up)
3155353358Sdim    m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up));
3156254721Semaste}
3157254721Semaste
3158296417SdimTarget::StopHook::~StopHook() = default;
3159254721Semaste
3160314564Sdimvoid Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3161314564Sdim  m_specifier_sp.reset(specifier);
3162288943Sdim}
3163288943Sdim
3164314564Sdimvoid Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3165353358Sdim  m_thread_spec_up.reset(specifier);
3166254721Semaste}
3167254721Semaste
3168314564Sdimvoid Target::StopHook::GetDescription(Stream *s,
3169314564Sdim                                      lldb::DescriptionLevel level) const {
3170360784Sdim  unsigned indent_level = s->GetIndentLevel();
3171254721Semaste
3172314564Sdim  s->SetIndentLevel(indent_level + 2);
3173314564Sdim
3174314564Sdim  s->Printf("Hook: %" PRIu64 "\n", GetID());
3175314564Sdim  if (m_active)
3176314564Sdim    s->Indent("State: enabled\n");
3177314564Sdim  else
3178314564Sdim    s->Indent("State: disabled\n");
3179314564Sdim
3180353358Sdim  if (m_auto_continue)
3181353358Sdim    s->Indent("AutoContinue on\n");
3182353358Sdim
3183314564Sdim  if (m_specifier_sp) {
3184314564Sdim    s->Indent();
3185314564Sdim    s->PutCString("Specifier:\n");
3186314564Sdim    s->SetIndentLevel(indent_level + 4);
3187314564Sdim    m_specifier_sp->GetDescription(s, level);
3188254721Semaste    s->SetIndentLevel(indent_level + 2);
3189314564Sdim  }
3190254721Semaste
3191353358Sdim  if (m_thread_spec_up) {
3192314564Sdim    StreamString tmp;
3193314564Sdim    s->Indent("Thread:\n");
3194353358Sdim    m_thread_spec_up->GetDescription(&tmp, level);
3195314564Sdim    s->SetIndentLevel(indent_level + 4);
3196314564Sdim    s->Indent(tmp.GetString());
3197314564Sdim    s->PutCString("\n");
3198314564Sdim    s->SetIndentLevel(indent_level + 2);
3199314564Sdim  }
3200254721Semaste
3201314564Sdim  s->Indent("Commands: \n");
3202314564Sdim  s->SetIndentLevel(indent_level + 4);
3203314564Sdim  uint32_t num_commands = m_commands.GetSize();
3204314564Sdim  for (uint32_t i = 0; i < num_commands; i++) {
3205314564Sdim    s->Indent(m_commands.GetStringAtIndex(i));
3206314564Sdim    s->PutCString("\n");
3207314564Sdim  }
3208314564Sdim  s->SetIndentLevel(indent_level);
3209254721Semaste}
3210254721Semaste
3211344779Sdimstatic constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3212360784Sdim    {
3213360784Sdim        eNoDynamicValues,
3214360784Sdim        "no-dynamic-values",
3215360784Sdim        "Don't calculate the dynamic type of values",
3216360784Sdim    },
3217360784Sdim    {
3218360784Sdim        eDynamicCanRunTarget,
3219360784Sdim        "run-target",
3220360784Sdim        "Calculate the dynamic type of values "
3221360784Sdim        "even if you have to run the target.",
3222360784Sdim    },
3223360784Sdim    {
3224360784Sdim        eDynamicDontRunTarget,
3225360784Sdim        "no-run-target",
3226360784Sdim        "Calculate the dynamic type of values, but don't run the target.",
3227360784Sdim    },
3228360784Sdim};
3229254721Semaste
3230344779SdimOptionEnumValues lldb_private::GetDynamicValueTypes() {
3231344779Sdim  return OptionEnumValues(g_dynamic_value_types);
3232344779Sdim}
3233344779Sdim
3234344779Sdimstatic constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3235360784Sdim    {
3236360784Sdim        eInlineBreakpointsNever,
3237360784Sdim        "never",
3238360784Sdim        "Never look for inline breakpoint locations (fastest). This setting "
3239360784Sdim        "should only be used if you know that no inlining occurs in your"
3240360784Sdim        "programs.",
3241360784Sdim    },
3242360784Sdim    {
3243360784Sdim        eInlineBreakpointsHeaders,
3244360784Sdim        "headers",
3245360784Sdim        "Only check for inline breakpoint locations when setting breakpoints "
3246360784Sdim        "in header files, but not when setting breakpoint in implementation "
3247360784Sdim        "source files (default).",
3248360784Sdim    },
3249360784Sdim    {
3250360784Sdim        eInlineBreakpointsAlways,
3251360784Sdim        "always",
3252360784Sdim        "Always look for inline breakpoint locations when setting file and "
3253360784Sdim        "line breakpoints (slower but most accurate).",
3254360784Sdim    },
3255360784Sdim};
3256254721Semaste
3257353358Sdimenum x86DisassemblyFlavor {
3258314564Sdim  eX86DisFlavorDefault,
3259314564Sdim  eX86DisFlavorIntel,
3260314564Sdim  eX86DisFlavorATT
3261353358Sdim};
3262254721Semaste
3263344779Sdimstatic constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3264360784Sdim    {
3265360784Sdim        eX86DisFlavorDefault,
3266360784Sdim        "default",
3267360784Sdim        "Disassembler default (currently att).",
3268360784Sdim    },
3269360784Sdim    {
3270360784Sdim        eX86DisFlavorIntel,
3271360784Sdim        "intel",
3272360784Sdim        "Intel disassembler flavor.",
3273360784Sdim    },
3274360784Sdim    {
3275360784Sdim        eX86DisFlavorATT,
3276360784Sdim        "att",
3277360784Sdim        "AT&T disassembler flavor.",
3278360784Sdim    },
3279360784Sdim};
3280254721Semaste
3281344779Sdimstatic constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3282360784Sdim    {
3283360784Sdim        Disassembler::eHexStyleC,
3284360784Sdim        "c",
3285360784Sdim        "C-style (0xffff).",
3286360784Sdim    },
3287360784Sdim    {
3288360784Sdim        Disassembler::eHexStyleAsm,
3289360784Sdim        "asm",
3290360784Sdim        "Asm-style (0ffffh).",
3291360784Sdim    },
3292360784Sdim};
3293254721Semaste
3294344779Sdimstatic constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3295360784Sdim    {
3296360784Sdim        eLoadScriptFromSymFileTrue,
3297360784Sdim        "true",
3298360784Sdim        "Load debug scripts inside symbol files",
3299360784Sdim    },
3300360784Sdim    {
3301360784Sdim        eLoadScriptFromSymFileFalse,
3302360784Sdim        "false",
3303360784Sdim        "Do not load debug scripts inside symbol files.",
3304360784Sdim    },
3305360784Sdim    {
3306360784Sdim        eLoadScriptFromSymFileWarn,
3307360784Sdim        "warn",
3308360784Sdim        "Warn about debug scripts inside symbol files but do not load them.",
3309360784Sdim    },
3310360784Sdim};
3311254721Semaste
3312360784Sdimstatic constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3313360784Sdim    {
3314360784Sdim        eLoadCWDlldbinitTrue,
3315360784Sdim        "true",
3316360784Sdim        "Load .lldbinit files from current directory",
3317360784Sdim    },
3318360784Sdim    {
3319360784Sdim        eLoadCWDlldbinitFalse,
3320360784Sdim        "false",
3321360784Sdim        "Do not load .lldbinit files from current directory",
3322360784Sdim    },
3323360784Sdim    {
3324360784Sdim        eLoadCWDlldbinitWarn,
3325360784Sdim        "warn",
3326360784Sdim        "Warn about loading .lldbinit files from current directory",
3327360784Sdim    },
3328360784Sdim};
3329309124Sdim
3330344779Sdimstatic constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3331360784Sdim    {
3332360784Sdim        eMemoryModuleLoadLevelMinimal,
3333360784Sdim        "minimal",
3334360784Sdim        "Load minimal information when loading modules from memory. Currently "
3335360784Sdim        "this setting loads sections only.",
3336360784Sdim    },
3337360784Sdim    {
3338360784Sdim        eMemoryModuleLoadLevelPartial,
3339360784Sdim        "partial",
3340360784Sdim        "Load partial information when loading modules from memory. Currently "
3341360784Sdim        "this setting loads sections and function bounds.",
3342360784Sdim    },
3343360784Sdim    {
3344360784Sdim        eMemoryModuleLoadLevelComplete,
3345360784Sdim        "complete",
3346360784Sdim        "Load complete information when loading modules from memory. Currently "
3347360784Sdim        "this setting loads sections and all symbols.",
3348360784Sdim    },
3349360784Sdim};
3350254721Semaste
3351360784Sdim#define LLDB_PROPERTIES_target
3352360784Sdim#include "TargetProperties.inc"
3353288943Sdim
3354314564Sdimenum {
3355360784Sdim#define LLDB_PROPERTIES_target
3356360784Sdim#include "TargetPropertiesEnum.inc"
3357344779Sdim  ePropertyExperimental,
3358254721Semaste};
3359254721Semaste
3360314564Sdimclass TargetOptionValueProperties : public OptionValueProperties {
3361254721Semastepublic:
3362353358Sdim  TargetOptionValueProperties(ConstString name)
3363314564Sdim      : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3364254721Semaste
3365314564Sdim  // This constructor is used when creating TargetOptionValueProperties when it
3366314564Sdim  // is part of a new lldb_private::Target instance. It will copy all current
3367314564Sdim  // global property values as needed
3368314564Sdim  TargetOptionValueProperties(Target *target,
3369314564Sdim                              const TargetPropertiesSP &target_properties_sp)
3370314564Sdim      : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3371314564Sdim        m_target(target), m_got_host_env(false) {}
3372314564Sdim
3373314564Sdim  const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3374314564Sdim                                     bool will_modify,
3375314564Sdim                                     uint32_t idx) const override {
3376314564Sdim    // When getting the value for a key from the target options, we will always
3377341825Sdim    // try and grab the setting from the current target if there is one. Else
3378341825Sdim    // we just use the one from this instance.
3379314564Sdim    if (idx == ePropertyEnvVars)
3380314564Sdim      GetHostEnvironmentIfNeeded();
3381314564Sdim
3382314564Sdim    if (exe_ctx) {
3383314564Sdim      Target *target = exe_ctx->GetTargetPtr();
3384314564Sdim      if (target) {
3385314564Sdim        TargetOptionValueProperties *target_properties =
3386314564Sdim            static_cast<TargetOptionValueProperties *>(
3387314564Sdim                target->GetValueProperties().get());
3388314564Sdim        if (this != target_properties)
3389314564Sdim          return target_properties->ProtectedGetPropertyAtIndex(idx);
3390314564Sdim      }
3391254721Semaste    }
3392314564Sdim    return ProtectedGetPropertyAtIndex(idx);
3393314564Sdim  }
3394254721Semaste
3395314564Sdim  lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3396314564Sdim
3397254721Semasteprotected:
3398314564Sdim  void GetHostEnvironmentIfNeeded() const {
3399314564Sdim    if (!m_got_host_env) {
3400314564Sdim      if (m_target) {
3401314564Sdim        m_got_host_env = true;
3402314564Sdim        const uint32_t idx = ePropertyInheritEnv;
3403314564Sdim        if (GetPropertyAtIndexAsBoolean(
3404360784Sdim                nullptr, idx, g_target_properties[idx].default_uint_value != 0)) {
3405314564Sdim          PlatformSP platform_sp(m_target->GetPlatform());
3406314564Sdim          if (platform_sp) {
3407341825Sdim            Environment env = platform_sp->GetEnvironment();
3408341825Sdim            OptionValueDictionary *env_dict =
3409341825Sdim                GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3410341825Sdim                                                          ePropertyEnvVars);
3411341825Sdim            if (env_dict) {
3412341825Sdim              const bool can_replace = false;
3413341825Sdim              for (const auto &KV : env) {
3414341825Sdim                // Don't allow existing keys to be replaced with ones we get
3415341825Sdim                // from the platform environment
3416341825Sdim                env_dict->SetValueForKey(
3417341825Sdim                    ConstString(KV.first()),
3418341825Sdim                    OptionValueSP(new OptionValueString(KV.second.c_str())),
3419341825Sdim                    can_replace);
3420314564Sdim              }
3421254721Semaste            }
3422314564Sdim          }
3423254721Semaste        }
3424314564Sdim      }
3425254721Semaste    }
3426314564Sdim  }
3427314564Sdim  Target *m_target;
3428314564Sdim  mutable bool m_got_host_env;
3429254721Semaste};
3430254721Semaste
3431258884Semaste// TargetProperties
3432360784Sdim#define LLDB_PROPERTIES_experimental
3433360784Sdim#include "TargetProperties.inc"
3434309124Sdim
3435360784Sdimenum {
3436360784Sdim#define LLDB_PROPERTIES_experimental
3437360784Sdim#include "TargetPropertiesEnum.inc"
3438360784Sdim};
3439309124Sdim
3440314564Sdimclass TargetExperimentalOptionValueProperties : public OptionValueProperties {
3441309124Sdimpublic:
3442314564Sdim  TargetExperimentalOptionValueProperties()
3443314564Sdim      : OptionValueProperties(
3444314564Sdim            ConstString(Properties::GetExperimentalSettingsName())) {}
3445309124Sdim};
3446309124Sdim
3447314564SdimTargetExperimentalProperties::TargetExperimentalProperties()
3448314564Sdim    : Properties(OptionValuePropertiesSP(
3449314564Sdim          new TargetExperimentalOptionValueProperties())) {
3450314564Sdim  m_collection_sp->Initialize(g_experimental_properties);
3451309124Sdim}
3452309124Sdim
3453309124Sdim// TargetProperties
3454314564SdimTargetProperties::TargetProperties(Target *target)
3455314564Sdim    : Properties(), m_launch_info() {
3456314564Sdim  if (target) {
3457353358Sdim    m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3458353358Sdim        target, Target::GetGlobalProperties());
3459288943Sdim
3460341825Sdim    // Set callbacks to update launch_info whenever "settins set" updated any
3461341825Sdim    // of these properties
3462314564Sdim    m_collection_sp->SetValueChangedCallback(
3463360784Sdim        ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3464314564Sdim    m_collection_sp->SetValueChangedCallback(
3465360784Sdim        ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3466314564Sdim    m_collection_sp->SetValueChangedCallback(
3467360784Sdim        ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3468314564Sdim    m_collection_sp->SetValueChangedCallback(
3469360784Sdim        ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3470314564Sdim    m_collection_sp->SetValueChangedCallback(
3471360784Sdim        ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3472314564Sdim    m_collection_sp->SetValueChangedCallback(
3473360784Sdim        ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3474360784Sdim    m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3475360784Sdim      DetachOnErrorValueChangedCallback();
3476360784Sdim    });
3477314564Sdim    m_collection_sp->SetValueChangedCallback(
3478360784Sdim        ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3479314564Sdim    m_collection_sp->SetValueChangedCallback(
3480360784Sdim        ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3481309124Sdim
3482314564Sdim    m_experimental_properties_up.reset(new TargetExperimentalProperties());
3483314564Sdim    m_collection_sp->AppendProperty(
3484314564Sdim        ConstString(Properties::GetExperimentalSettingsName()),
3485314564Sdim        ConstString("Experimental settings - setting these won't produce "
3486314564Sdim                    "errors if the setting is not present."),
3487314564Sdim        true, m_experimental_properties_up->GetValueProperties());
3488309124Sdim
3489314564Sdim    // Update m_launch_info once it was created
3490360784Sdim    Arg0ValueChangedCallback();
3491360784Sdim    RunArgsValueChangedCallback();
3492360784Sdim    // EnvVarsValueChangedCallback(); // FIXME: cause segfault in
3493314564Sdim    // Target::GetPlatform()
3494360784Sdim    InputPathValueChangedCallback();
3495360784Sdim    OutputPathValueChangedCallback();
3496360784Sdim    ErrorPathValueChangedCallback();
3497360784Sdim    DetachOnErrorValueChangedCallback();
3498360784Sdim    DisableASLRValueChangedCallback();
3499360784Sdim    DisableSTDIOValueChangedCallback();
3500314564Sdim  } else {
3501353358Sdim    m_collection_sp =
3502353358Sdim        std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3503360784Sdim    m_collection_sp->Initialize(g_target_properties);
3504314564Sdim    m_experimental_properties_up.reset(new TargetExperimentalProperties());
3505314564Sdim    m_collection_sp->AppendProperty(
3506314564Sdim        ConstString(Properties::GetExperimentalSettingsName()),
3507314564Sdim        ConstString("Experimental settings - setting these won't produce "
3508314564Sdim                    "errors if the setting is not present."),
3509314564Sdim        true, m_experimental_properties_up->GetValueProperties());
3510314564Sdim    m_collection_sp->AppendProperty(
3511314564Sdim        ConstString("process"), ConstString("Settings specific to processes."),
3512314564Sdim        true, Process::GetGlobalProperties()->GetValueProperties());
3513314564Sdim  }
3514254721Semaste}
3515254721Semaste
3516296417SdimTargetProperties::~TargetProperties() = default;
3517296417Sdim
3518314564Sdimbool TargetProperties::GetInjectLocalVariables(
3519314564Sdim    ExecutionContext *exe_ctx) const {
3520314564Sdim  const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3521314564Sdim      exe_ctx, false, ePropertyExperimental);
3522314564Sdim  OptionValueProperties *exp_values =
3523314564Sdim      exp_property->GetValue()->GetAsProperties();
3524314564Sdim  if (exp_values)
3525314564Sdim    return exp_values->GetPropertyAtIndexAsBoolean(
3526314564Sdim        exe_ctx, ePropertyInjectLocalVars, true);
3527314564Sdim  else
3528314564Sdim    return true;
3529309124Sdim}
3530309124Sdim
3531314564Sdimvoid TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3532314564Sdim                                               bool b) {
3533314564Sdim  const Property *exp_property =
3534314564Sdim      m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3535314564Sdim  OptionValueProperties *exp_values =
3536314564Sdim      exp_property->GetValue()->GetAsProperties();
3537314564Sdim  if (exp_values)
3538314564Sdim    exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3539314564Sdim                                            true);
3540309124Sdim}
3541309124Sdim
3542314564SdimArchSpec TargetProperties::GetDefaultArchitecture() const {
3543314564Sdim  OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3544314564Sdim      nullptr, ePropertyDefaultArch);
3545314564Sdim  if (value)
3546314564Sdim    return value->GetCurrentValue();
3547314564Sdim  return ArchSpec();
3548254721Semaste}
3549254721Semaste
3550314564Sdimvoid TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3551314564Sdim  OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3552314564Sdim      nullptr, ePropertyDefaultArch);
3553314564Sdim  if (value)
3554314564Sdim    return value->SetCurrentValue(arch, true);
3555254721Semaste}
3556254721Semaste
3557314564Sdimbool TargetProperties::GetMoveToNearestCode() const {
3558314564Sdim  const uint32_t idx = ePropertyMoveToNearestCode;
3559314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3560360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3561288943Sdim}
3562288943Sdim
3563314564Sdimlldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3564314564Sdim  const uint32_t idx = ePropertyPreferDynamic;
3565314564Sdim  return (lldb::DynamicValueType)
3566314564Sdim      m_collection_sp->GetPropertyAtIndexAsEnumeration(
3567360784Sdim          nullptr, idx, g_target_properties[idx].default_uint_value);
3568254721Semaste}
3569254721Semaste
3570314564Sdimbool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3571314564Sdim  const uint32_t idx = ePropertyPreferDynamic;
3572314564Sdim  return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3573288943Sdim}
3574288943Sdim
3575321369Sdimbool TargetProperties::GetPreloadSymbols() const {
3576321369Sdim  const uint32_t idx = ePropertyPreloadSymbols;
3577321369Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3578360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3579321369Sdim}
3580321369Sdim
3581321369Sdimvoid TargetProperties::SetPreloadSymbols(bool b) {
3582321369Sdim  const uint32_t idx = ePropertyPreloadSymbols;
3583321369Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3584321369Sdim}
3585321369Sdim
3586314564Sdimbool TargetProperties::GetDisableASLR() const {
3587314564Sdim  const uint32_t idx = ePropertyDisableASLR;
3588314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3589360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3590254721Semaste}
3591254721Semaste
3592314564Sdimvoid TargetProperties::SetDisableASLR(bool b) {
3593314564Sdim  const uint32_t idx = ePropertyDisableASLR;
3594314564Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3595254721Semaste}
3596254721Semaste
3597314564Sdimbool TargetProperties::GetDetachOnError() const {
3598314564Sdim  const uint32_t idx = ePropertyDetachOnError;
3599314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3600360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3601276479Sdim}
3602276479Sdim
3603314564Sdimvoid TargetProperties::SetDetachOnError(bool b) {
3604314564Sdim  const uint32_t idx = ePropertyDetachOnError;
3605314564Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3606276479Sdim}
3607276479Sdim
3608314564Sdimbool TargetProperties::GetDisableSTDIO() const {
3609314564Sdim  const uint32_t idx = ePropertyDisableSTDIO;
3610314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3611360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3612254721Semaste}
3613254721Semaste
3614314564Sdimvoid TargetProperties::SetDisableSTDIO(bool b) {
3615314564Sdim  const uint32_t idx = ePropertyDisableSTDIO;
3616314564Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3617254721Semaste}
3618254721Semaste
3619314564Sdimconst char *TargetProperties::GetDisassemblyFlavor() const {
3620314564Sdim  const uint32_t idx = ePropertyDisassemblyFlavor;
3621314564Sdim  const char *return_value;
3622314564Sdim
3623314564Sdim  x86DisassemblyFlavor flavor_value =
3624314564Sdim      (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3625360784Sdim          nullptr, idx, g_target_properties[idx].default_uint_value);
3626314564Sdim  return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3627314564Sdim  return return_value;
3628254721Semaste}
3629254721Semaste
3630314564SdimInlineStrategy TargetProperties::GetInlineStrategy() const {
3631314564Sdim  const uint32_t idx = ePropertyInlineStrategy;
3632314564Sdim  return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3633360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3634254721Semaste}
3635254721Semaste
3636314564Sdimllvm::StringRef TargetProperties::GetArg0() const {
3637314564Sdim  const uint32_t idx = ePropertyArg0;
3638360784Sdim  return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3639360784Sdim                                                     llvm::StringRef());
3640254721Semaste}
3641254721Semaste
3642314564Sdimvoid TargetProperties::SetArg0(llvm::StringRef arg) {
3643314564Sdim  const uint32_t idx = ePropertyArg0;
3644360784Sdim  m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3645314564Sdim  m_launch_info.SetArg0(arg);
3646254721Semaste}
3647254721Semaste
3648314564Sdimbool TargetProperties::GetRunArguments(Args &args) const {
3649314564Sdim  const uint32_t idx = ePropertyRunArgs;
3650314564Sdim  return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3651254721Semaste}
3652254721Semaste
3653314564Sdimvoid TargetProperties::SetRunArguments(const Args &args) {
3654314564Sdim  const uint32_t idx = ePropertyRunArgs;
3655314564Sdim  m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3656314564Sdim  m_launch_info.GetArguments() = args;
3657254721Semaste}
3658254721Semaste
3659341825SdimEnvironment TargetProperties::GetEnvironment() const {
3660341825Sdim  // TODO: Get rid of the Args intermediate step
3661341825Sdim  Args env;
3662314564Sdim  const uint32_t idx = ePropertyEnvVars;
3663341825Sdim  m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3664341825Sdim  return Environment(env);
3665254721Semaste}
3666254721Semaste
3667341825Sdimvoid TargetProperties::SetEnvironment(Environment env) {
3668341825Sdim  // TODO: Get rid of the Args intermediate step
3669314564Sdim  const uint32_t idx = ePropertyEnvVars;
3670341825Sdim  m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3671341825Sdim  m_launch_info.GetEnvironment() = std::move(env);
3672288943Sdim}
3673288943Sdim
3674314564Sdimbool TargetProperties::GetSkipPrologue() const {
3675314564Sdim  const uint32_t idx = ePropertySkipPrologue;
3676314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3677360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3678254721Semaste}
3679254721Semaste
3680314564SdimPathMappingList &TargetProperties::GetSourcePathMap() const {
3681314564Sdim  const uint32_t idx = ePropertySourceMap;
3682314564Sdim  OptionValuePathMappings *option_value =
3683314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3684314564Sdim                                                                   false, idx);
3685314564Sdim  assert(option_value);
3686314564Sdim  return option_value->GetCurrentValue();
3687254721Semaste}
3688254721Semaste
3689360784Sdimvoid TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3690314564Sdim  const uint32_t idx = ePropertyExecutableSearchPaths;
3691314564Sdim  OptionValueFileSpecList *option_value =
3692314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3693314564Sdim                                                                   false, idx);
3694314564Sdim  assert(option_value);
3695353358Sdim  option_value->AppendCurrentValue(dir);
3696353358Sdim}
3697353358Sdim
3698353358SdimFileSpecList TargetProperties::GetExecutableSearchPaths() {
3699353358Sdim  const uint32_t idx = ePropertyExecutableSearchPaths;
3700353358Sdim  const OptionValueFileSpecList *option_value =
3701353358Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3702353358Sdim                                                                   false, idx);
3703353358Sdim  assert(option_value);
3704314564Sdim  return option_value->GetCurrentValue();
3705254721Semaste}
3706254721Semaste
3707353358SdimFileSpecList TargetProperties::GetDebugFileSearchPaths() {
3708314564Sdim  const uint32_t idx = ePropertyDebugFileSearchPaths;
3709353358Sdim  const OptionValueFileSpecList *option_value =
3710314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3711314564Sdim                                                                   false, idx);
3712314564Sdim  assert(option_value);
3713314564Sdim  return option_value->GetCurrentValue();
3714254721Semaste}
3715254721Semaste
3716353358SdimFileSpecList TargetProperties::GetClangModuleSearchPaths() {
3717314564Sdim  const uint32_t idx = ePropertyClangModuleSearchPaths;
3718353358Sdim  const OptionValueFileSpecList *option_value =
3719314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3720314564Sdim                                                                   false, idx);
3721314564Sdim  assert(option_value);
3722314564Sdim  return option_value->GetCurrentValue();
3723288943Sdim}
3724288943Sdim
3725314564Sdimbool TargetProperties::GetEnableAutoImportClangModules() const {
3726314564Sdim  const uint32_t idx = ePropertyAutoImportClangModules;
3727314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3728360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3729288943Sdim}
3730288943Sdim
3731353358Sdimbool TargetProperties::GetEnableImportStdModule() const {
3732353358Sdim  const uint32_t idx = ePropertyImportStdModule;
3733353358Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3734360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3735353358Sdim}
3736353358Sdim
3737314564Sdimbool TargetProperties::GetEnableAutoApplyFixIts() const {
3738314564Sdim  const uint32_t idx = ePropertyAutoApplyFixIts;
3739314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3740360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3741309124Sdim}
3742309124Sdim
3743314564Sdimbool TargetProperties::GetEnableNotifyAboutFixIts() const {
3744314564Sdim  const uint32_t idx = ePropertyNotifyAboutFixIts;
3745314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3746360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3747309124Sdim}
3748309124Sdim
3749314564Sdimbool TargetProperties::GetEnableSaveObjects() const {
3750314564Sdim  const uint32_t idx = ePropertySaveObjects;
3751314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3752360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3753254721Semaste}
3754254721Semaste
3755314564Sdimbool TargetProperties::GetEnableSyntheticValue() const {
3756314564Sdim  const uint32_t idx = ePropertyEnableSynthetic;
3757314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3758360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3759254721Semaste}
3760254721Semaste
3761360784Sdimuint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
3762360784Sdim  const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
3763360784Sdim  return m_collection_sp->GetPropertyAtIndexAsUInt64(
3764360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3765360784Sdim}
3766360784Sdim
3767314564Sdimuint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3768314564Sdim  const uint32_t idx = ePropertyMaxChildrenCount;
3769314564Sdim  return m_collection_sp->GetPropertyAtIndexAsSInt64(
3770360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3771254721Semaste}
3772254721Semaste
3773314564Sdimuint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3774314564Sdim  const uint32_t idx = ePropertyMaxSummaryLength;
3775314564Sdim  return m_collection_sp->GetPropertyAtIndexAsSInt64(
3776360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3777254721Semaste}
3778254721Semaste
3779314564Sdimuint32_t TargetProperties::GetMaximumMemReadSize() const {
3780314564Sdim  const uint32_t idx = ePropertyMaxMemReadSize;
3781314564Sdim  return m_collection_sp->GetPropertyAtIndexAsSInt64(
3782360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3783254721Semaste}
3784254721Semaste
3785314564SdimFileSpec TargetProperties::GetStandardInputPath() const {
3786314564Sdim  const uint32_t idx = ePropertyInputPath;
3787314564Sdim  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3788254721Semaste}
3789254721Semaste
3790314564Sdimvoid TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3791314564Sdim  const uint32_t idx = ePropertyInputPath;
3792314564Sdim  m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3793254721Semaste}
3794254721Semaste
3795314564SdimFileSpec TargetProperties::GetStandardOutputPath() const {
3796314564Sdim  const uint32_t idx = ePropertyOutputPath;
3797314564Sdim  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3798254721Semaste}
3799254721Semaste
3800314564Sdimvoid TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3801314564Sdim  const uint32_t idx = ePropertyOutputPath;
3802314564Sdim  m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3803254721Semaste}
3804254721Semaste
3805314564SdimFileSpec TargetProperties::GetStandardErrorPath() const {
3806314564Sdim  const uint32_t idx = ePropertyErrorPath;
3807314564Sdim  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3808296417Sdim}
3809296417Sdim
3810314564Sdimvoid TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3811314564Sdim  const uint32_t idx = ePropertyErrorPath;
3812314564Sdim  m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3813254721Semaste}
3814254721Semaste
3815314564SdimLanguageType TargetProperties::GetLanguage() const {
3816314564Sdim  OptionValueLanguage *value =
3817314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3818314564Sdim          nullptr, ePropertyLanguage);
3819314564Sdim  if (value)
3820314564Sdim    return value->GetCurrentValue();
3821314564Sdim  return LanguageType();
3822254721Semaste}
3823254721Semaste
3824327952Sdimllvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3825314564Sdim  const uint32_t idx = ePropertyExprPrefix;
3826314564Sdim  OptionValueFileSpec *file =
3827314564Sdim      m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3828314564Sdim                                                               idx);
3829314564Sdim  if (file) {
3830327952Sdim    DataBufferSP data_sp(file->GetFileContents());
3831314564Sdim    if (data_sp)
3832327952Sdim      return llvm::StringRef(
3833327952Sdim          reinterpret_cast<const char *>(data_sp->GetBytes()),
3834327952Sdim          data_sp->GetByteSize());
3835314564Sdim  }
3836327952Sdim  return "";
3837254721Semaste}
3838254721Semaste
3839314564Sdimbool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3840314564Sdim  const uint32_t idx = ePropertyBreakpointUseAvoidList;
3841314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3842360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3843254721Semaste}
3844254721Semaste
3845314564Sdimbool TargetProperties::GetUseHexImmediates() const {
3846314564Sdim  const uint32_t idx = ePropertyUseHexImmediates;
3847314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3848360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3849254721Semaste}
3850254721Semaste
3851314564Sdimbool TargetProperties::GetUseFastStepping() const {
3852314564Sdim  const uint32_t idx = ePropertyUseFastStepping;
3853314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3854360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3855262528Semaste}
3856262528Semaste
3857314564Sdimbool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3858314564Sdim  const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3859314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3860360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3861254721Semaste}
3862254721Semaste
3863314564SdimLoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3864314564Sdim  const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3865314564Sdim  return (LoadScriptFromSymFile)
3866314564Sdim      m_collection_sp->GetPropertyAtIndexAsEnumeration(
3867360784Sdim          nullptr, idx, g_target_properties[idx].default_uint_value);
3868309124Sdim}
3869309124Sdim
3870314564SdimLoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3871314564Sdim  const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3872314564Sdim  return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3873360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value);
3874254721Semaste}
3875254721Semaste
3876314564SdimDisassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3877314564Sdim  const uint32_t idx = ePropertyHexImmediateStyle;
3878314564Sdim  return (Disassembler::HexImmediateStyle)
3879314564Sdim      m_collection_sp->GetPropertyAtIndexAsEnumeration(
3880360784Sdim          nullptr, idx, g_target_properties[idx].default_uint_value);
3881254721Semaste}
3882254721Semaste
3883314564SdimMemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3884314564Sdim  const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3885314564Sdim  return (MemoryModuleLoadLevel)
3886314564Sdim      m_collection_sp->GetPropertyAtIndexAsEnumeration(
3887360784Sdim          nullptr, idx, g_target_properties[idx].default_uint_value);
3888262528Semaste}
3889254721Semaste
3890314564Sdimbool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3891314564Sdim  const uint32_t idx = ePropertyTrapHandlerNames;
3892314564Sdim  return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3893262528Semaste}
3894254721Semaste
3895314564Sdimvoid TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3896314564Sdim  const uint32_t idx = ePropertyTrapHandlerNames;
3897314564Sdim  m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3898254721Semaste}
3899254721Semaste
3900314564Sdimbool TargetProperties::GetDisplayRuntimeSupportValues() const {
3901314564Sdim  const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3902314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3903254721Semaste}
3904254721Semaste
3905314564Sdimvoid TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3906314564Sdim  const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3907314564Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3908254721Semaste}
3909254721Semaste
3910344779Sdimbool TargetProperties::GetDisplayRecognizedArguments() const {
3911344779Sdim  const uint32_t idx = ePropertyDisplayRecognizedArguments;
3912344779Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3913344779Sdim}
3914344779Sdim
3915344779Sdimvoid TargetProperties::SetDisplayRecognizedArguments(bool b) {
3916344779Sdim  const uint32_t idx = ePropertyDisplayRecognizedArguments;
3917344779Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3918344779Sdim}
3919344779Sdim
3920314564Sdimbool TargetProperties::GetNonStopModeEnabled() const {
3921314564Sdim  const uint32_t idx = ePropertyNonStopModeEnabled;
3922314564Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3923288943Sdim}
3924254721Semaste
3925314564Sdimvoid TargetProperties::SetNonStopModeEnabled(bool b) {
3926314564Sdim  const uint32_t idx = ePropertyNonStopModeEnabled;
3927314564Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3928254721Semaste}
3929254721Semaste
3930314564Sdimconst ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3931314564Sdim  m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3932314564Sdim  return m_launch_info;
3933288943Sdim}
3934254721Semaste
3935314564Sdimvoid TargetProperties::SetProcessLaunchInfo(
3936314564Sdim    const ProcessLaunchInfo &launch_info) {
3937314564Sdim  m_launch_info = launch_info;
3938314564Sdim  SetArg0(launch_info.GetArg0());
3939314564Sdim  SetRunArguments(launch_info.GetArguments());
3940341825Sdim  SetEnvironment(launch_info.GetEnvironment());
3941314564Sdim  const FileAction *input_file_action =
3942314564Sdim      launch_info.GetFileActionForFD(STDIN_FILENO);
3943314564Sdim  if (input_file_action) {
3944314564Sdim    SetStandardInputPath(input_file_action->GetPath());
3945314564Sdim  }
3946314564Sdim  const FileAction *output_file_action =
3947314564Sdim      launch_info.GetFileActionForFD(STDOUT_FILENO);
3948314564Sdim  if (output_file_action) {
3949314564Sdim    SetStandardOutputPath(output_file_action->GetPath());
3950314564Sdim  }
3951314564Sdim  const FileAction *error_file_action =
3952314564Sdim      launch_info.GetFileActionForFD(STDERR_FILENO);
3953314564Sdim  if (error_file_action) {
3954314564Sdim    SetStandardErrorPath(error_file_action->GetPath());
3955314564Sdim  }
3956314564Sdim  SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3957314564Sdim  SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3958314564Sdim  SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3959254721Semaste}
3960254721Semaste
3961344779Sdimbool TargetProperties::GetRequireHardwareBreakpoints() const {
3962344779Sdim  const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3963344779Sdim  return m_collection_sp->GetPropertyAtIndexAsBoolean(
3964360784Sdim      nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3965344779Sdim}
3966344779Sdim
3967344779Sdimvoid TargetProperties::SetRequireHardwareBreakpoints(bool b) {
3968344779Sdim  const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3969344779Sdim  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3970344779Sdim}
3971344779Sdim
3972360784Sdimvoid TargetProperties::Arg0ValueChangedCallback() {
3973360784Sdim  m_launch_info.SetArg0(GetArg0());
3974288943Sdim}
3975254721Semaste
3976360784Sdimvoid TargetProperties::RunArgsValueChangedCallback() {
3977314564Sdim  Args args;
3978360784Sdim  if (GetRunArguments(args))
3979360784Sdim    m_launch_info.GetArguments() = args;
3980288943Sdim}
3981254721Semaste
3982360784Sdimvoid TargetProperties::EnvVarsValueChangedCallback() {
3983360784Sdim  m_launch_info.GetEnvironment() = GetEnvironment();
3984254721Semaste}
3985254721Semaste
3986360784Sdimvoid TargetProperties::InputPathValueChangedCallback() {
3987360784Sdim  m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
3988360784Sdim                                     false);
3989288943Sdim}
3990288943Sdim
3991360784Sdimvoid TargetProperties::OutputPathValueChangedCallback() {
3992360784Sdim  m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
3993360784Sdim                                     false, true);
3994288943Sdim}
3995288943Sdim
3996360784Sdimvoid TargetProperties::ErrorPathValueChangedCallback() {
3997360784Sdim  m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
3998360784Sdim                                     false, true);
3999288943Sdim}
4000288943Sdim
4001360784Sdimvoid TargetProperties::DetachOnErrorValueChangedCallback() {
4002360784Sdim  if (GetDetachOnError())
4003360784Sdim    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4004314564Sdim  else
4005360784Sdim    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4006288943Sdim}
4007288943Sdim
4008360784Sdimvoid TargetProperties::DisableASLRValueChangedCallback() {
4009360784Sdim  if (GetDisableASLR())
4010360784Sdim    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4011314564Sdim  else
4012360784Sdim    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4013288943Sdim}
4014288943Sdim
4015360784Sdimvoid TargetProperties::DisableSTDIOValueChangedCallback() {
4016360784Sdim  if (GetDisableSTDIO())
4017360784Sdim    m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4018314564Sdim  else
4019360784Sdim    m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4020314564Sdim}
4021314564Sdim
4022288943Sdim// Target::TargetEventData
4023288943Sdim
4024314564SdimTarget::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4025314564Sdim    : EventData(), m_target_sp(target_sp), m_module_list() {}
4026288943Sdim
4027314564SdimTarget::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4028314564Sdim                                         const ModuleList &module_list)
4029314564Sdim    : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4030288943Sdim
4031296417SdimTarget::TargetEventData::~TargetEventData() = default;
4032288943Sdim
4033353358SdimConstString Target::TargetEventData::GetFlavorString() {
4034314564Sdim  static ConstString g_flavor("Target::TargetEventData");
4035314564Sdim  return g_flavor;
4036288943Sdim}
4037288943Sdim
4038314564Sdimvoid Target::TargetEventData::Dump(Stream *s) const {
4039314564Sdim  for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4040314564Sdim    if (i != 0)
4041314564Sdim      *s << ", ";
4042314564Sdim    m_module_list.GetModuleAtIndex(i)->GetDescription(
4043360784Sdim        s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4044314564Sdim  }
4045288943Sdim}
4046288943Sdim
4047254721Semasteconst Target::TargetEventData *
4048314564SdimTarget::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4049314564Sdim  if (event_ptr) {
4050314564Sdim    const EventData *event_data = event_ptr->GetData();
4051314564Sdim    if (event_data &&
4052314564Sdim        event_data->GetFlavor() == TargetEventData::GetFlavorString())
4053314564Sdim      return static_cast<const TargetEventData *>(event_ptr->GetData());
4054314564Sdim  }
4055314564Sdim  return nullptr;
4056254721Semaste}
4057254721Semaste
4058314564SdimTargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4059314564Sdim  TargetSP target_sp;
4060314564Sdim  const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4061314564Sdim  if (event_data)
4062314564Sdim    target_sp = event_data->m_target_sp;
4063314564Sdim  return target_sp;
4064288943Sdim}
4065288943Sdim
4066288943SdimModuleList
4067314564SdimTarget::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4068314564Sdim  ModuleList module_list;
4069314564Sdim  const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4070314564Sdim  if (event_data)
4071314564Sdim    module_list = event_data->m_module_list;
4072314564Sdim  return module_list;
4073288943Sdim}
4074360784Sdim
4075360784Sdimstd::recursive_mutex &Target::GetAPIMutex() {
4076360784Sdim  if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4077360784Sdim    return m_private_mutex;
4078360784Sdim  else
4079360784Sdim    return m_mutex;
4080360784Sdim}
4081