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