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