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