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