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