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