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