1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Target/Target.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Breakpoint/BreakpointResolver.h"
17 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
18 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
19 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
20 #include "lldb/Breakpoint/BreakpointResolverName.h"
21 #include "lldb/Breakpoint/Watchpoint.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Event.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/StreamString.h"
26 #include "lldb/Core/Timer.h"
27 #include "lldb/Core/ValueObject.h"
28 #include "lldb/Expression/ClangASTSource.h"
29 #include "lldb/Expression/ClangUserExpression.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
34 #include "lldb/Interpreter/OptionValues.h"
35 #include "lldb/Interpreter/Property.h"
36 #include "lldb/lldb-private-log.h"
37 #include "lldb/Symbol/ObjectFile.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadSpec.h"
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 ConstString &
47 Target::GetStaticBroadcasterClass ()
48 {
49     static ConstString class_name ("lldb.target");
50     return class_name;
51 }
52 
53 //----------------------------------------------------------------------
54 // Target constructor
55 //----------------------------------------------------------------------
56 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
57     TargetProperties (this),
58     Broadcaster (&debugger, "lldb.target"),
59     ExecutionContextScope (),
60     m_debugger (debugger),
61     m_platform_sp (platform_sp),
62     m_mutex (Mutex::eMutexTypeRecursive),
63     m_arch (target_arch),
64     m_images (),
65     m_section_load_list (),
66     m_breakpoint_list (false),
67     m_internal_breakpoint_list (true),
68     m_watchpoint_list (),
69     m_process_sp (),
70     m_valid (true),
71     m_search_filter_sp (),
72     m_image_search_paths (ImageSearchPathsChanged, this),
73     m_scratch_ast_context_ap (NULL),
74     m_scratch_ast_source_ap (NULL),
75     m_ast_importer_ap (NULL),
76     m_persistent_variables (),
77     m_source_manager(*this),
78     m_stop_hooks (),
79     m_stop_hook_next_id (0),
80     m_suppress_stop_hooks (false),
81     m_suppress_synthetic_value(false)
82 {
83     SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
84     SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
85     SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
86 
87     CheckInWithManager();
88 
89     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
90     if (log)
91         log->Printf ("%p Target::Target()", this);
92 }
93 
94 //----------------------------------------------------------------------
95 // Destructor
96 //----------------------------------------------------------------------
97 Target::~Target()
98 {
99     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
100     if (log)
101         log->Printf ("%p Target::~Target()", this);
102     DeleteCurrentProcess ();
103 }
104 
105 void
106 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
107 {
108 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
109     if (description_level != lldb::eDescriptionLevelBrief)
110     {
111         s->Indent();
112         s->PutCString("Target\n");
113         s->IndentMore();
114             m_images.Dump(s);
115             m_breakpoint_list.Dump(s);
116             m_internal_breakpoint_list.Dump(s);
117         s->IndentLess();
118     }
119     else
120     {
121         Module *exe_module = GetExecutableModulePointer();
122         if (exe_module)
123             s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
124         else
125             s->PutCString ("No executable module.");
126     }
127 }
128 
129 void
130 Target::DeleteCurrentProcess ()
131 {
132     if (m_process_sp.get())
133     {
134         m_section_load_list.Clear();
135         if (m_process_sp->IsAlive())
136             m_process_sp->Destroy();
137 
138         m_process_sp->Finalize();
139 
140         // Do any cleanup of the target we need to do between process instances.
141         // NB It is better to do this before destroying the process in case the
142         // clean up needs some help from the process.
143         m_breakpoint_list.ClearAllBreakpointSites();
144         m_internal_breakpoint_list.ClearAllBreakpointSites();
145         // Disable watchpoints just on the debugger side.
146         Mutex::Locker locker;
147         this->GetWatchpointList().GetListMutex(locker);
148         DisableAllWatchpoints(false);
149         ClearAllWatchpointHitCounts();
150         m_process_sp.reset();
151     }
152 }
153 
154 const lldb::ProcessSP &
155 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
156 {
157     DeleteCurrentProcess ();
158     m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
159     return m_process_sp;
160 }
161 
162 const lldb::ProcessSP &
163 Target::GetProcessSP () const
164 {
165     return m_process_sp;
166 }
167 
168 void
169 Target::Destroy()
170 {
171     Mutex::Locker locker (m_mutex);
172     m_valid = false;
173     DeleteCurrentProcess ();
174     m_platform_sp.reset();
175     m_arch.Clear();
176     m_images.Clear();
177     m_section_load_list.Clear();
178     const bool notify = false;
179     m_breakpoint_list.RemoveAll(notify);
180     m_internal_breakpoint_list.RemoveAll(notify);
181     m_last_created_breakpoint.reset();
182     m_last_created_watchpoint.reset();
183     m_search_filter_sp.reset();
184     m_image_search_paths.Clear(notify);
185     m_scratch_ast_context_ap.reset();
186     m_scratch_ast_source_ap.reset();
187     m_ast_importer_ap.reset();
188     m_persistent_variables.Clear();
189     m_stop_hooks.clear();
190     m_stop_hook_next_id = 0;
191     m_suppress_stop_hooks = false;
192     m_suppress_synthetic_value = false;
193 }
194 
195 
196 BreakpointList &
197 Target::GetBreakpointList(bool internal)
198 {
199     if (internal)
200         return m_internal_breakpoint_list;
201     else
202         return m_breakpoint_list;
203 }
204 
205 const BreakpointList &
206 Target::GetBreakpointList(bool internal) const
207 {
208     if (internal)
209         return m_internal_breakpoint_list;
210     else
211         return m_breakpoint_list;
212 }
213 
214 BreakpointSP
215 Target::GetBreakpointByID (break_id_t break_id)
216 {
217     BreakpointSP bp_sp;
218 
219     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
220         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
221     else
222         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
223 
224     return bp_sp;
225 }
226 
227 BreakpointSP
228 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
229                   const FileSpecList *source_file_spec_list,
230                   RegularExpression &source_regex,
231                   bool internal)
232 {
233     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
234     BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
235     return CreateBreakpoint (filter_sp, resolver_sp, internal);
236 }
237 
238 
239 BreakpointSP
240 Target::CreateBreakpoint (const FileSpecList *containingModules,
241                           const FileSpec &file,
242                           uint32_t line_no,
243                           bool check_inlines,
244                           LazyBool skip_prologue,
245                           bool internal)
246 {
247     SearchFilterSP filter_sp(GetSearchFilterForModuleList (containingModules));
248 
249     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines,
250                                                                      skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
251     return CreateBreakpoint (filter_sp, resolver_sp, internal);
252 }
253 
254 
255 BreakpointSP
256 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
257 {
258     Address so_addr;
259     // Attempt to resolve our load address if possible, though it is ok if
260     // it doesn't resolve to section/offset.
261 
262     // Try and resolve as a load address if possible
263     m_section_load_list.ResolveLoadAddress(addr, so_addr);
264     if (!so_addr.IsValid())
265     {
266         // The address didn't resolve, so just set this as an absolute address
267         so_addr.SetOffset (addr);
268     }
269     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
270     return bp_sp;
271 }
272 
273 BreakpointSP
274 Target::CreateBreakpoint (Address &addr, bool internal)
275 {
276     SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
277     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
278     return CreateBreakpoint (filter_sp, resolver_sp, internal);
279 }
280 
281 BreakpointSP
282 Target::CreateBreakpoint (const FileSpecList *containingModules,
283                           const FileSpecList *containingSourceFiles,
284                           const char *func_name,
285                           uint32_t func_name_type_mask,
286                           LazyBool skip_prologue,
287                           bool internal)
288 {
289     BreakpointSP bp_sp;
290     if (func_name)
291     {
292         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
293 
294         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
295                                                                       func_name,
296                                                                       func_name_type_mask,
297                                                                       Breakpoint::Exact,
298                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
299         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
300     }
301     return bp_sp;
302 }
303 
304 lldb::BreakpointSP
305 Target::CreateBreakpoint (const FileSpecList *containingModules,
306                           const FileSpecList *containingSourceFiles,
307                           const std::vector<std::string> &func_names,
308                           uint32_t func_name_type_mask,
309                           LazyBool skip_prologue,
310                           bool internal)
311 {
312     BreakpointSP bp_sp;
313     size_t num_names = func_names.size();
314     if (num_names > 0)
315     {
316         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
317 
318         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
319                                                                       func_names,
320                                                                       func_name_type_mask,
321                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
322         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
323     }
324     return bp_sp;
325 }
326 
327 BreakpointSP
328 Target::CreateBreakpoint (const FileSpecList *containingModules,
329                           const FileSpecList *containingSourceFiles,
330                           const char *func_names[],
331                           size_t num_names,
332                           uint32_t func_name_type_mask,
333                           LazyBool skip_prologue,
334                           bool internal)
335 {
336     BreakpointSP bp_sp;
337     if (num_names > 0)
338     {
339         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
340 
341         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
342                                                                       func_names,
343                                                                       num_names,
344                                                                       func_name_type_mask,
345                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
346         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
347     }
348     return bp_sp;
349 }
350 
351 SearchFilterSP
352 Target::GetSearchFilterForModule (const FileSpec *containingModule)
353 {
354     SearchFilterSP filter_sp;
355     if (containingModule != NULL)
356     {
357         // TODO: We should look into sharing module based search filters
358         // across many breakpoints like we do for the simple target based one
359         filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
360     }
361     else
362     {
363         if (m_search_filter_sp.get() == NULL)
364             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
365         filter_sp = m_search_filter_sp;
366     }
367     return filter_sp;
368 }
369 
370 SearchFilterSP
371 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
372 {
373     SearchFilterSP filter_sp;
374     if (containingModules && containingModules->GetSize() != 0)
375     {
376         // TODO: We should look into sharing module based search filters
377         // across many breakpoints like we do for the simple target based one
378         filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
379     }
380     else
381     {
382         if (m_search_filter_sp.get() == NULL)
383             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
384         filter_sp = m_search_filter_sp;
385     }
386     return filter_sp;
387 }
388 
389 SearchFilterSP
390 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
391                                            const FileSpecList *containingSourceFiles)
392 {
393     if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
394         return GetSearchFilterForModuleList(containingModules);
395 
396     SearchFilterSP filter_sp;
397     if (containingModules == NULL)
398     {
399         // We could make a special "CU List only SearchFilter".  Better yet was if these could be composable,
400         // but that will take a little reworking.
401 
402         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
403     }
404     else
405     {
406         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
407     }
408     return filter_sp;
409 }
410 
411 BreakpointSP
412 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
413                                    const FileSpecList *containingSourceFiles,
414                                    RegularExpression &func_regex,
415                                    LazyBool skip_prologue,
416                                    bool internal)
417 {
418     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
419     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
420                                                                  func_regex,
421                                                                  skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
422 
423     return CreateBreakpoint (filter_sp, resolver_sp, internal);
424 }
425 
426 lldb::BreakpointSP
427 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
428 {
429     return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
430 }
431 
432 BreakpointSP
433 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
434 {
435     BreakpointSP bp_sp;
436     if (filter_sp && resolver_sp)
437     {
438         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
439         resolver_sp->SetBreakpoint (bp_sp.get());
440 
441         if (internal)
442             m_internal_breakpoint_list.Add (bp_sp, false);
443         else
444             m_breakpoint_list.Add (bp_sp, true);
445 
446         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
447         if (log)
448         {
449             StreamString s;
450             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
451             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
452         }
453 
454         bp_sp->ResolveBreakpoint();
455     }
456 
457     if (!internal && bp_sp)
458     {
459         m_last_created_breakpoint = bp_sp;
460     }
461 
462     return bp_sp;
463 }
464 
465 bool
466 Target::ProcessIsValid()
467 {
468     return (m_process_sp && m_process_sp->IsAlive());
469 }
470 
471 static bool
472 CheckIfWatchpointsExhausted(Target *target, Error &error)
473 {
474     uint32_t num_supported_hardware_watchpoints;
475     Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
476     if (rc.Success())
477     {
478         uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
479         if (num_current_watchpoints >= num_supported_hardware_watchpoints)
480             error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
481                                            num_supported_hardware_watchpoints);
482     }
483     return false;
484 }
485 
486 // See also Watchpoint::SetWatchpointType(uint32_t type) and
487 // the OptionGroupWatchpoint::WatchType enum type.
488 WatchpointSP
489 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, uint32_t type, Error &error)
490 {
491     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
492     if (log)
493         log->Printf("Target::%s (addr = 0x%8.8llx size = %zu type = %u)\n",
494                     __FUNCTION__, addr, size, type);
495 
496     WatchpointSP wp_sp;
497     if (!ProcessIsValid())
498     {
499         error.SetErrorString("process is not alive");
500         return wp_sp;
501     }
502     if (addr == LLDB_INVALID_ADDRESS || size == 0)
503     {
504         if (size == 0)
505             error.SetErrorString("cannot set a watchpoint with watch_size of 0");
506         else
507             error.SetErrorStringWithFormat("invalid watch address: %llu", addr);
508         return wp_sp;
509     }
510 
511     // Currently we only support one watchpoint per address, with total number
512     // of watchpoints limited by the hardware which the inferior is running on.
513 
514     // Grab the list mutex while doing operations.
515     Mutex::Locker locker;
516     this->GetWatchpointList().GetListMutex(locker);
517     WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
518     if (matched_sp)
519     {
520         size_t old_size = matched_sp->GetByteSize();
521         uint32_t old_type =
522             (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
523             (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
524         // Return the existing watchpoint if both size and type match.
525         if (size == old_size && type == old_type) {
526             wp_sp = matched_sp;
527             wp_sp->SetEnabled(false);
528         } else {
529             // Nil the matched watchpoint; we will be creating a new one.
530             m_process_sp->DisableWatchpoint(matched_sp.get());
531             m_watchpoint_list.Remove(matched_sp->GetID());
532         }
533     }
534 
535     if (!wp_sp) {
536         Watchpoint *new_wp = new Watchpoint(addr, size);
537         if (!new_wp) {
538             printf("Watchpoint ctor failed, out of memory?\n");
539             return wp_sp;
540         }
541         new_wp->SetWatchpointType(type);
542         new_wp->SetTarget(this);
543         wp_sp.reset(new_wp);
544         m_watchpoint_list.Add(wp_sp);
545     }
546 
547     error = m_process_sp->EnableWatchpoint(wp_sp.get());
548     if (log)
549             log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
550                         __FUNCTION__,
551                         error.Success() ? "succeeded" : "failed",
552                         wp_sp->GetID());
553 
554     if (error.Fail()) {
555         // Enabling the watchpoint on the device side failed.
556         // Remove the said watchpoint from the list maintained by the target instance.
557         m_watchpoint_list.Remove(wp_sp->GetID());
558         // See if we could provide more helpful error message.
559         if (!CheckIfWatchpointsExhausted(this, error))
560         {
561             if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
562                 error.SetErrorStringWithFormat("watch size of %lu is not supported", size);
563         }
564         wp_sp.reset();
565     }
566     else
567         m_last_created_watchpoint = wp_sp;
568     return wp_sp;
569 }
570 
571 void
572 Target::RemoveAllBreakpoints (bool internal_also)
573 {
574     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
575     if (log)
576         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
577 
578     m_breakpoint_list.RemoveAll (true);
579     if (internal_also)
580         m_internal_breakpoint_list.RemoveAll (false);
581 
582     m_last_created_breakpoint.reset();
583 }
584 
585 void
586 Target::DisableAllBreakpoints (bool internal_also)
587 {
588     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
589     if (log)
590         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
591 
592     m_breakpoint_list.SetEnabledAll (false);
593     if (internal_also)
594         m_internal_breakpoint_list.SetEnabledAll (false);
595 }
596 
597 void
598 Target::EnableAllBreakpoints (bool internal_also)
599 {
600     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
601     if (log)
602         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
603 
604     m_breakpoint_list.SetEnabledAll (true);
605     if (internal_also)
606         m_internal_breakpoint_list.SetEnabledAll (true);
607 }
608 
609 bool
610 Target::RemoveBreakpointByID (break_id_t break_id)
611 {
612     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
613     if (log)
614         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
615 
616     if (DisableBreakpointByID (break_id))
617     {
618         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
619             m_internal_breakpoint_list.Remove(break_id, false);
620         else
621         {
622             if (m_last_created_breakpoint)
623             {
624                 if (m_last_created_breakpoint->GetID() == break_id)
625                     m_last_created_breakpoint.reset();
626             }
627             m_breakpoint_list.Remove(break_id, true);
628         }
629         return true;
630     }
631     return false;
632 }
633 
634 bool
635 Target::DisableBreakpointByID (break_id_t break_id)
636 {
637     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
638     if (log)
639         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
640 
641     BreakpointSP bp_sp;
642 
643     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
644         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
645     else
646         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
647     if (bp_sp)
648     {
649         bp_sp->SetEnabled (false);
650         return true;
651     }
652     return false;
653 }
654 
655 bool
656 Target::EnableBreakpointByID (break_id_t break_id)
657 {
658     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
659     if (log)
660         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
661                      __FUNCTION__,
662                      break_id,
663                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
664 
665     BreakpointSP bp_sp;
666 
667     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
668         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
669     else
670         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
671 
672     if (bp_sp)
673     {
674         bp_sp->SetEnabled (true);
675         return true;
676     }
677     return false;
678 }
679 
680 // The flag 'end_to_end', default to true, signifies that the operation is
681 // performed end to end, for both the debugger and the debuggee.
682 
683 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
684 // to end operations.
685 bool
686 Target::RemoveAllWatchpoints (bool end_to_end)
687 {
688     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
689     if (log)
690         log->Printf ("Target::%s\n", __FUNCTION__);
691 
692     if (!end_to_end) {
693         m_watchpoint_list.RemoveAll();
694         return true;
695     }
696 
697     // Otherwise, it's an end to end operation.
698 
699     if (!ProcessIsValid())
700         return false;
701 
702     size_t num_watchpoints = m_watchpoint_list.GetSize();
703     for (size_t i = 0; i < num_watchpoints; ++i)
704     {
705         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
706         if (!wp_sp)
707             return false;
708 
709         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
710         if (rc.Fail())
711             return false;
712     }
713     m_watchpoint_list.RemoveAll ();
714     return true; // Success!
715 }
716 
717 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
718 // end operations.
719 bool
720 Target::DisableAllWatchpoints (bool end_to_end)
721 {
722     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
723     if (log)
724         log->Printf ("Target::%s\n", __FUNCTION__);
725 
726     if (!end_to_end) {
727         m_watchpoint_list.SetEnabledAll(false);
728         return true;
729     }
730 
731     // Otherwise, it's an end to end operation.
732 
733     if (!ProcessIsValid())
734         return false;
735 
736     size_t num_watchpoints = m_watchpoint_list.GetSize();
737     for (size_t i = 0; i < num_watchpoints; ++i)
738     {
739         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
740         if (!wp_sp)
741             return false;
742 
743         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
744         if (rc.Fail())
745             return false;
746     }
747     return true; // Success!
748 }
749 
750 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
751 // end operations.
752 bool
753 Target::EnableAllWatchpoints (bool end_to_end)
754 {
755     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
756     if (log)
757         log->Printf ("Target::%s\n", __FUNCTION__);
758 
759     if (!end_to_end) {
760         m_watchpoint_list.SetEnabledAll(true);
761         return true;
762     }
763 
764     // Otherwise, it's an end to end operation.
765 
766     if (!ProcessIsValid())
767         return false;
768 
769     size_t num_watchpoints = m_watchpoint_list.GetSize();
770     for (size_t i = 0; i < num_watchpoints; ++i)
771     {
772         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
773         if (!wp_sp)
774             return false;
775 
776         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
777         if (rc.Fail())
778             return false;
779     }
780     return true; // Success!
781 }
782 
783 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
784 bool
785 Target::ClearAllWatchpointHitCounts ()
786 {
787     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
788     if (log)
789         log->Printf ("Target::%s\n", __FUNCTION__);
790 
791     size_t num_watchpoints = m_watchpoint_list.GetSize();
792     for (size_t i = 0; i < num_watchpoints; ++i)
793     {
794         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
795         if (!wp_sp)
796             return false;
797 
798         wp_sp->ResetHitCount();
799     }
800     return true; // Success!
801 }
802 
803 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
804 // during these operations.
805 bool
806 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
807 {
808     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
809     if (log)
810         log->Printf ("Target::%s\n", __FUNCTION__);
811 
812     if (!ProcessIsValid())
813         return false;
814 
815     size_t num_watchpoints = m_watchpoint_list.GetSize();
816     for (size_t i = 0; i < num_watchpoints; ++i)
817     {
818         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
819         if (!wp_sp)
820             return false;
821 
822         wp_sp->SetIgnoreCount(ignore_count);
823     }
824     return true; // Success!
825 }
826 
827 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
828 bool
829 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
830 {
831     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
832     if (log)
833         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
834 
835     if (!ProcessIsValid())
836         return false;
837 
838     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
839     if (wp_sp)
840     {
841         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
842         if (rc.Success())
843             return true;
844 
845         // Else, fallthrough.
846     }
847     return false;
848 }
849 
850 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
851 bool
852 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
853 {
854     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
855     if (log)
856         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
857 
858     if (!ProcessIsValid())
859         return false;
860 
861     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
862     if (wp_sp)
863     {
864         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
865         if (rc.Success())
866             return true;
867 
868         // Else, fallthrough.
869     }
870     return false;
871 }
872 
873 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
874 bool
875 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
876 {
877     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
878     if (log)
879         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
880 
881     if (DisableWatchpointByID (watch_id))
882     {
883         m_watchpoint_list.Remove(watch_id);
884         return true;
885     }
886     return false;
887 }
888 
889 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
890 bool
891 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
892 {
893     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
894     if (log)
895         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
896 
897     if (!ProcessIsValid())
898         return false;
899 
900     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
901     if (wp_sp)
902     {
903         wp_sp->SetIgnoreCount(ignore_count);
904         return true;
905     }
906     return false;
907 }
908 
909 ModuleSP
910 Target::GetExecutableModule ()
911 {
912     return m_images.GetModuleAtIndex(0);
913 }
914 
915 Module*
916 Target::GetExecutableModulePointer ()
917 {
918     return m_images.GetModulePointerAtIndex(0);
919 }
920 
921 void
922 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
923 {
924     m_images.Clear();
925     m_scratch_ast_context_ap.reset();
926     m_scratch_ast_source_ap.reset();
927     m_ast_importer_ap.reset();
928 
929     if (executable_sp.get())
930     {
931         Timer scoped_timer (__PRETTY_FUNCTION__,
932                             "Target::SetExecutableModule (executable = '%s/%s')",
933                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
934                             executable_sp->GetFileSpec().GetFilename().AsCString());
935 
936         m_images.Append(executable_sp); // The first image is our exectuable file
937 
938         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
939         if (!m_arch.IsValid())
940             m_arch = executable_sp->GetArchitecture();
941 
942         FileSpecList dependent_files;
943         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
944 
945         if (executable_objfile && get_dependent_files)
946         {
947             executable_objfile->GetDependentModules(dependent_files);
948             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
949             {
950                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
951                 FileSpec platform_dependent_file_spec;
952                 if (m_platform_sp)
953                     m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
954                 else
955                     platform_dependent_file_spec = dependent_file_spec;
956 
957                 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
958                 ModuleSP image_module_sp(GetSharedModule (module_spec));
959                 if (image_module_sp.get())
960                 {
961                     ObjectFile *objfile = image_module_sp->GetObjectFile();
962                     if (objfile)
963                         objfile->GetDependentModules(dependent_files);
964                 }
965             }
966         }
967     }
968 }
969 
970 
971 bool
972 Target::SetArchitecture (const ArchSpec &arch_spec)
973 {
974     if (m_arch == arch_spec || !m_arch.IsValid())
975     {
976         // If we haven't got a valid arch spec, or the architectures are
977         // compatible, so just update the architecture. Architectures can be
978         // equal, yet the triple OS and vendor might change, so we need to do
979         // the assignment here just in case.
980         m_arch = arch_spec;
981         return true;
982     }
983     else
984     {
985         // If we have an executable file, try to reset the executable to the desired architecture
986         m_arch = arch_spec;
987         ModuleSP executable_sp = GetExecutableModule ();
988         m_images.Clear();
989         m_scratch_ast_context_ap.reset();
990         m_scratch_ast_source_ap.reset();
991         m_ast_importer_ap.reset();
992         // Need to do something about unsetting breakpoints.
993 
994         if (executable_sp)
995         {
996             ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
997             Error error = ModuleList::GetSharedModule (module_spec,
998                                                        executable_sp,
999                                                        &GetExecutableSearchPaths(),
1000                                                        NULL,
1001                                                        NULL);
1002 
1003             if (!error.Fail() && executable_sp)
1004             {
1005                 SetExecutableModule (executable_sp, true);
1006                 return true;
1007             }
1008         }
1009     }
1010     return false;
1011 }
1012 
1013 void
1014 Target::ModuleAdded (ModuleSP &module_sp)
1015 {
1016     // A module is being added to this target for the first time
1017     ModuleList module_list;
1018     module_list.Append(module_sp);
1019     ModulesDidLoad (module_list);
1020 }
1021 
1022 void
1023 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
1024 {
1025     // A module is replacing an already added module
1026     m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1027 }
1028 
1029 void
1030 Target::ModulesDidLoad (ModuleList &module_list)
1031 {
1032     m_breakpoint_list.UpdateBreakpoints (module_list, true);
1033     // TODO: make event data that packages up the module_list
1034     BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1035 }
1036 
1037 void
1038 Target::ModulesDidUnload (ModuleList &module_list)
1039 {
1040     m_breakpoint_list.UpdateBreakpoints (module_list, false);
1041 
1042     // Remove the images from the target image list
1043     m_images.Remove(module_list);
1044 
1045     // TODO: make event data that packages up the module_list
1046     BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1047 }
1048 
1049 
1050 bool
1051 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1052 {
1053 
1054     if (GetBreakpointsConsultPlatformAvoidList())
1055     {
1056         ModuleList matchingModules;
1057         ModuleSpec module_spec (module_file_spec);
1058         size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1059 
1060         // If there is more than one module for this file spec, only return true if ALL the modules are on the
1061         // black list.
1062         if (num_modules > 0)
1063         {
1064             for (int i  = 0; i < num_modules; i++)
1065             {
1066                 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1067                     return false;
1068             }
1069             return true;
1070         }
1071     }
1072     return false;
1073 }
1074 
1075 bool
1076 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1077 {
1078     if (GetBreakpointsConsultPlatformAvoidList())
1079     {
1080         if (m_platform_sp)
1081             return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1082     }
1083     return false;
1084 }
1085 
1086 size_t
1087 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1088 {
1089     SectionSP section_sp (addr.GetSection());
1090     if (section_sp)
1091     {
1092         // If the contents of this section are encrypted, the on-disk file is unusuable.  Read only from live memory.
1093         if (section_sp->IsEncrypted())
1094         {
1095             error.SetErrorString("section is encrypted");
1096             return 0;
1097         }
1098         ModuleSP module_sp (section_sp->GetModule());
1099         if (module_sp)
1100         {
1101             ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1102             if (objfile)
1103             {
1104                 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1105                                                               addr.GetOffset(),
1106                                                               dst,
1107                                                               dst_len);
1108                 if (bytes_read > 0)
1109                     return bytes_read;
1110                 else
1111                     error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1112             }
1113             else
1114                 error.SetErrorString("address isn't from a object file");
1115         }
1116         else
1117             error.SetErrorString("address isn't in a module");
1118     }
1119     else
1120         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1121 
1122     return 0;
1123 }
1124 
1125 size_t
1126 Target::ReadMemory (const Address& addr,
1127                     bool prefer_file_cache,
1128                     void *dst,
1129                     size_t dst_len,
1130                     Error &error,
1131                     lldb::addr_t *load_addr_ptr)
1132 {
1133     error.Clear();
1134 
1135     // if we end up reading this from process memory, we will fill this
1136     // with the actual load address
1137     if (load_addr_ptr)
1138         *load_addr_ptr = LLDB_INVALID_ADDRESS;
1139 
1140     size_t bytes_read = 0;
1141 
1142     addr_t load_addr = LLDB_INVALID_ADDRESS;
1143     addr_t file_addr = LLDB_INVALID_ADDRESS;
1144     Address resolved_addr;
1145     if (!addr.IsSectionOffset())
1146     {
1147         if (m_section_load_list.IsEmpty())
1148         {
1149             // No sections are loaded, so we must assume we are not running
1150             // yet and anything we are given is a file address.
1151             file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1152             m_images.ResolveFileAddress (file_addr, resolved_addr);
1153         }
1154         else
1155         {
1156             // We have at least one section loaded. This can be becuase
1157             // we have manually loaded some sections with "target modules load ..."
1158             // or because we have have a live process that has sections loaded
1159             // through the dynamic loader
1160             load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1161             m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1162         }
1163     }
1164     if (!resolved_addr.IsValid())
1165         resolved_addr = addr;
1166 
1167 
1168     if (prefer_file_cache)
1169     {
1170         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1171         if (bytes_read > 0)
1172             return bytes_read;
1173     }
1174 
1175     if (ProcessIsValid())
1176     {
1177         if (load_addr == LLDB_INVALID_ADDRESS)
1178             load_addr = resolved_addr.GetLoadAddress (this);
1179 
1180         if (load_addr == LLDB_INVALID_ADDRESS)
1181         {
1182             ModuleSP addr_module_sp (resolved_addr.GetModule());
1183             if (addr_module_sp && addr_module_sp->GetFileSpec())
1184                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded",
1185                                                addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1186                                                resolved_addr.GetFileAddress(),
1187                                                addr_module_sp->GetFileSpec().GetFilename().AsCString());
1188             else
1189                 error.SetErrorStringWithFormat("0x%llx can't be resolved", resolved_addr.GetFileAddress());
1190         }
1191         else
1192         {
1193             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1194             if (bytes_read != dst_len)
1195             {
1196                 if (error.Success())
1197                 {
1198                     if (bytes_read == 0)
1199                         error.SetErrorStringWithFormat("read memory from 0x%llx failed", load_addr);
1200                     else
1201                         error.SetErrorStringWithFormat("only %zu of %zu bytes were read from memory at 0x%llx", bytes_read, dst_len, load_addr);
1202                 }
1203             }
1204             if (bytes_read)
1205             {
1206                 if (load_addr_ptr)
1207                     *load_addr_ptr = load_addr;
1208                 return bytes_read;
1209             }
1210             // If the address is not section offset we have an address that
1211             // doesn't resolve to any address in any currently loaded shared
1212             // libaries and we failed to read memory so there isn't anything
1213             // more we can do. If it is section offset, we might be able to
1214             // read cached memory from the object file.
1215             if (!resolved_addr.IsSectionOffset())
1216                 return 0;
1217         }
1218     }
1219 
1220     if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1221     {
1222         // If we didn't already try and read from the object file cache, then
1223         // try it after failing to read from the process.
1224         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1225     }
1226     return 0;
1227 }
1228 
1229 size_t
1230 Target::ReadScalarIntegerFromMemory (const Address& addr,
1231                                      bool prefer_file_cache,
1232                                      uint32_t byte_size,
1233                                      bool is_signed,
1234                                      Scalar &scalar,
1235                                      Error &error)
1236 {
1237     uint64_t uval;
1238 
1239     if (byte_size <= sizeof(uval))
1240     {
1241         size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1242         if (bytes_read == byte_size)
1243         {
1244             DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1245             uint32_t offset = 0;
1246             if (byte_size <= 4)
1247                 scalar = data.GetMaxU32 (&offset, byte_size);
1248             else
1249                 scalar = data.GetMaxU64 (&offset, byte_size);
1250 
1251             if (is_signed)
1252                 scalar.SignExtend(byte_size * 8);
1253             return bytes_read;
1254         }
1255     }
1256     else
1257     {
1258         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1259     }
1260     return 0;
1261 }
1262 
1263 uint64_t
1264 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1265                                        bool prefer_file_cache,
1266                                        size_t integer_byte_size,
1267                                        uint64_t fail_value,
1268                                        Error &error)
1269 {
1270     Scalar scalar;
1271     if (ReadScalarIntegerFromMemory (addr,
1272                                      prefer_file_cache,
1273                                      integer_byte_size,
1274                                      false,
1275                                      scalar,
1276                                      error))
1277         return scalar.ULongLong(fail_value);
1278     return fail_value;
1279 }
1280 
1281 bool
1282 Target::ReadPointerFromMemory (const Address& addr,
1283                                bool prefer_file_cache,
1284                                Error &error,
1285                                Address &pointer_addr)
1286 {
1287     Scalar scalar;
1288     if (ReadScalarIntegerFromMemory (addr,
1289                                      prefer_file_cache,
1290                                      m_arch.GetAddressByteSize(),
1291                                      false,
1292                                      scalar,
1293                                      error))
1294     {
1295         addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1296         if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1297         {
1298             if (m_section_load_list.IsEmpty())
1299             {
1300                 // No sections are loaded, so we must assume we are not running
1301                 // yet and anything we are given is a file address.
1302                 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1303             }
1304             else
1305             {
1306                 // We have at least one section loaded. This can be becuase
1307                 // we have manually loaded some sections with "target modules load ..."
1308                 // or because we have have a live process that has sections loaded
1309                 // through the dynamic loader
1310                 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1311             }
1312             // We weren't able to resolve the pointer value, so just return
1313             // an address with no section
1314             if (!pointer_addr.IsValid())
1315                 pointer_addr.SetOffset (pointer_vm_addr);
1316             return true;
1317 
1318         }
1319     }
1320     return false;
1321 }
1322 
1323 ModuleSP
1324 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1325 {
1326     ModuleSP module_sp;
1327 
1328     Error error;
1329 
1330     // First see if we already have this module in our module list.  If we do, then we're done, we don't need
1331     // to consult the shared modules list.  But only do this if we are passed a UUID.
1332 
1333     if (module_spec.GetUUID().IsValid())
1334         module_sp = m_images.FindFirstModule(module_spec);
1335 
1336     if (!module_sp)
1337     {
1338         ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1339         bool did_create_module = false;
1340 
1341         // If there are image search path entries, try to use them first to acquire a suitable image.
1342         if (m_image_search_paths.GetSize())
1343         {
1344             ModuleSpec transformed_spec (module_spec);
1345             if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1346             {
1347                 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1348                 error = ModuleList::GetSharedModule (transformed_spec,
1349                                                      module_sp,
1350                                                      &GetExecutableSearchPaths(),
1351                                                      &old_module_sp,
1352                                                      &did_create_module);
1353             }
1354         }
1355 
1356         if (!module_sp)
1357         {
1358             // If we have a UUID, we can check our global shared module list in case
1359             // we already have it. If we don't have a valid UUID, then we can't since
1360             // the path in "module_spec" will be a platform path, and we will need to
1361             // let the platform find that file. For example, we could be asking for
1362             // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1363             // the local copy of "/usr/lib/dyld" since our platform could be a remote
1364             // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1365             // cache.
1366             if (module_spec.GetUUID().IsValid())
1367             {
1368                 // We have a UUID, it is OK to check the global module list...
1369                 error = ModuleList::GetSharedModule (module_spec,
1370                                                      module_sp,
1371                                                      &GetExecutableSearchPaths(),
1372                                                      &old_module_sp,
1373                                                      &did_create_module);
1374             }
1375 
1376             if (!module_sp)
1377             {
1378                 // The platform is responsible for finding and caching an appropriate
1379                 // module in the shared module cache.
1380                 if (m_platform_sp)
1381                 {
1382                     FileSpec platform_file_spec;
1383                     error = m_platform_sp->GetSharedModule (module_spec,
1384                                                             module_sp,
1385                                                             &GetExecutableSearchPaths(),
1386                                                             &old_module_sp,
1387                                                             &did_create_module);
1388                 }
1389                 else
1390                 {
1391                     error.SetErrorString("no platform is currently set");
1392                 }
1393             }
1394         }
1395 
1396         // We found a module that wasn't in our target list.  Let's make sure that there wasn't an equivalent
1397         // module in the list already, and if there was, let's remove it.
1398         if (module_sp)
1399         {
1400             // GetSharedModule is not guaranteed to find the old shared module, for instance
1401             // in the common case where you pass in the UUID, it is only going to find the one
1402             // module matching the UUID.  In fact, it has no good way to know what the "old module"
1403             // relevant to this target is, since there might be many copies of a module with this file spec
1404             // in various running debug sessions, but only one of them will belong to this target.
1405             // So let's remove the UUID from the module list, and look in the target's module list.
1406             // Only do this if there is SOMETHING else in the module spec...
1407             if (!old_module_sp)
1408             {
1409                 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1410                 {
1411                     ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1412                     module_spec_copy.GetUUID().Clear();
1413 
1414                     ModuleList found_modules;
1415                     size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1416                     if (num_found == 1)
1417                     {
1418                         old_module_sp = found_modules.GetModuleAtIndex(0);
1419                     }
1420                 }
1421             }
1422 
1423             m_images.Append (module_sp);
1424             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1425             {
1426                 ModuleUpdated(old_module_sp, module_sp);
1427                 m_images.Remove (old_module_sp);
1428                 Module *old_module_ptr = old_module_sp.get();
1429                 old_module_sp.reset();
1430                 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1431             }
1432             else
1433                 ModuleAdded(module_sp);
1434         }
1435     }
1436     if (error_ptr)
1437         *error_ptr = error;
1438     return module_sp;
1439 }
1440 
1441 
1442 TargetSP
1443 Target::CalculateTarget ()
1444 {
1445     return shared_from_this();
1446 }
1447 
1448 ProcessSP
1449 Target::CalculateProcess ()
1450 {
1451     return ProcessSP();
1452 }
1453 
1454 ThreadSP
1455 Target::CalculateThread ()
1456 {
1457     return ThreadSP();
1458 }
1459 
1460 StackFrameSP
1461 Target::CalculateStackFrame ()
1462 {
1463     return StackFrameSP();
1464 }
1465 
1466 void
1467 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1468 {
1469     exe_ctx.Clear();
1470     exe_ctx.SetTargetPtr(this);
1471 }
1472 
1473 PathMappingList &
1474 Target::GetImageSearchPathList ()
1475 {
1476     return m_image_search_paths;
1477 }
1478 
1479 void
1480 Target::ImageSearchPathsChanged
1481 (
1482     const PathMappingList &path_list,
1483     void *baton
1484 )
1485 {
1486     Target *target = (Target *)baton;
1487     ModuleSP exe_module_sp (target->GetExecutableModule());
1488     if (exe_module_sp)
1489     {
1490         target->m_images.Clear();
1491         target->SetExecutableModule (exe_module_sp, true);
1492     }
1493 }
1494 
1495 ClangASTContext *
1496 Target::GetScratchClangASTContext(bool create_on_demand)
1497 {
1498     // Now see if we know the target triple, and if so, create our scratch AST context:
1499     if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1500     {
1501         m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1502         m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1503         m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1504         llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1505         m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1506     }
1507     return m_scratch_ast_context_ap.get();
1508 }
1509 
1510 ClangASTImporter *
1511 Target::GetClangASTImporter()
1512 {
1513     ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1514 
1515     if (!ast_importer)
1516     {
1517         ast_importer = new ClangASTImporter();
1518         m_ast_importer_ap.reset(ast_importer);
1519     }
1520 
1521     return ast_importer;
1522 }
1523 
1524 void
1525 Target::SettingsInitialize ()
1526 {
1527     Process::SettingsInitialize ();
1528 }
1529 
1530 void
1531 Target::SettingsTerminate ()
1532 {
1533     Process::SettingsTerminate ();
1534 }
1535 
1536 FileSpecList
1537 Target::GetDefaultExecutableSearchPaths ()
1538 {
1539     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1540     if (properties_sp)
1541         return properties_sp->GetExecutableSearchPaths();
1542     return FileSpecList();
1543 }
1544 
1545 ArchSpec
1546 Target::GetDefaultArchitecture ()
1547 {
1548     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1549     if (properties_sp)
1550         return properties_sp->GetDefaultArchitecture();
1551     return ArchSpec();
1552 }
1553 
1554 void
1555 Target::SetDefaultArchitecture (const ArchSpec &arch)
1556 {
1557     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1558     if (properties_sp)
1559         return properties_sp->SetDefaultArchitecture(arch);
1560 }
1561 
1562 Target *
1563 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1564 {
1565     // The target can either exist in the "process" of ExecutionContext, or in
1566     // the "target_sp" member of SymbolContext. This accessor helper function
1567     // will get the target from one of these locations.
1568 
1569     Target *target = NULL;
1570     if (sc_ptr != NULL)
1571         target = sc_ptr->target_sp.get();
1572     if (target == NULL && exe_ctx_ptr)
1573         target = exe_ctx_ptr->GetTargetPtr();
1574     return target;
1575 }
1576 
1577 ExecutionResults
1578 Target::EvaluateExpression
1579 (
1580     const char *expr_cstr,
1581     StackFrame *frame,
1582     lldb_private::ExecutionPolicy execution_policy,
1583     bool coerce_to_id,
1584     bool unwind_on_error,
1585     bool keep_in_memory,
1586     lldb::DynamicValueType use_dynamic,
1587     lldb::ValueObjectSP &result_valobj_sp,
1588     uint32_t single_thread_timeout_usec
1589 )
1590 {
1591     ExecutionResults execution_results = eExecutionSetupError;
1592 
1593     result_valobj_sp.reset();
1594 
1595     if (expr_cstr == NULL || expr_cstr[0] == '\0')
1596         return execution_results;
1597 
1598     // We shouldn't run stop hooks in expressions.
1599     // Be sure to reset this if you return anywhere within this function.
1600     bool old_suppress_value = m_suppress_stop_hooks;
1601     m_suppress_stop_hooks = true;
1602 
1603     ExecutionContext exe_ctx;
1604 
1605     const size_t expr_cstr_len = ::strlen (expr_cstr);
1606 
1607     if (frame)
1608     {
1609         frame->CalculateExecutionContext(exe_ctx);
1610         Error error;
1611         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1612                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1613                                            StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1614         lldb::VariableSP var_sp;
1615 
1616         // Make sure we don't have any things that we know a variable expression
1617         // won't be able to deal with before calling into it
1618         if (::strcspn (expr_cstr, "()+*&|!~<=/^%,?") == expr_cstr_len)
1619         {
1620             result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1621                                                                          use_dynamic,
1622                                                                          expr_path_options,
1623                                                                          var_sp,
1624                                                                          error);
1625             // if this expression results in a bitfield, we give up and let the IR handle it
1626             if (result_valobj_sp && result_valobj_sp->IsBitfield())
1627                 result_valobj_sp.reset();
1628         }
1629     }
1630     else if (m_process_sp)
1631     {
1632         m_process_sp->CalculateExecutionContext(exe_ctx);
1633     }
1634     else
1635     {
1636         CalculateExecutionContext(exe_ctx);
1637     }
1638 
1639     if (result_valobj_sp)
1640     {
1641         execution_results = eExecutionCompleted;
1642         // We got a result from the frame variable expression path above...
1643         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1644 
1645         lldb::ValueObjectSP const_valobj_sp;
1646 
1647         // Check in case our value is already a constant value
1648         if (result_valobj_sp->GetIsConstant())
1649         {
1650             const_valobj_sp = result_valobj_sp;
1651             const_valobj_sp->SetName (persistent_variable_name);
1652         }
1653         else
1654         {
1655             if (use_dynamic != lldb::eNoDynamicValues)
1656             {
1657                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
1658                 if (dynamic_sp)
1659                     result_valobj_sp = dynamic_sp;
1660             }
1661 
1662             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1663         }
1664 
1665         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1666 
1667         result_valobj_sp = const_valobj_sp;
1668 
1669         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1670         assert (clang_expr_variable_sp.get());
1671 
1672         // Set flags and live data as appropriate
1673 
1674         const Value &result_value = live_valobj_sp->GetValue();
1675 
1676         switch (result_value.GetValueType())
1677         {
1678         case Value::eValueTypeHostAddress:
1679         case Value::eValueTypeFileAddress:
1680             // we don't do anything with these for now
1681             break;
1682         case Value::eValueTypeScalar:
1683             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1684             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1685             break;
1686         case Value::eValueTypeLoadAddress:
1687             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1688             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1689             break;
1690         }
1691     }
1692     else
1693     {
1694         // Make sure we aren't just trying to see the value of a persistent
1695         // variable (something like "$0")
1696         lldb::ClangExpressionVariableSP persistent_var_sp;
1697         // Only check for persistent variables the expression starts with a '$'
1698         if (expr_cstr[0] == '$')
1699             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1700 
1701         if (persistent_var_sp)
1702         {
1703             result_valobj_sp = persistent_var_sp->GetValueObject ();
1704             execution_results = eExecutionCompleted;
1705         }
1706         else
1707         {
1708             const char *prefix = GetExpressionPrefixContentsAsCString();
1709 
1710             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1711                                                                execution_policy,
1712                                                                lldb::eLanguageTypeUnknown,
1713                                                                coerce_to_id ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1714                                                                unwind_on_error,
1715                                                                expr_cstr,
1716                                                                prefix,
1717                                                                result_valobj_sp,
1718                                                                single_thread_timeout_usec);
1719         }
1720     }
1721 
1722     m_suppress_stop_hooks = old_suppress_value;
1723 
1724     return execution_results;
1725 }
1726 
1727 lldb::addr_t
1728 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1729 {
1730     addr_t code_addr = load_addr;
1731     switch (m_arch.GetMachine())
1732     {
1733     case llvm::Triple::arm:
1734     case llvm::Triple::thumb:
1735         switch (addr_class)
1736         {
1737         case eAddressClassData:
1738         case eAddressClassDebug:
1739             return LLDB_INVALID_ADDRESS;
1740 
1741         case eAddressClassUnknown:
1742         case eAddressClassInvalid:
1743         case eAddressClassCode:
1744         case eAddressClassCodeAlternateISA:
1745         case eAddressClassRuntime:
1746             // Check if bit zero it no set?
1747             if ((code_addr & 1ull) == 0)
1748             {
1749                 // Bit zero isn't set, check if the address is a multiple of 2?
1750                 if (code_addr & 2ull)
1751                 {
1752                     // The address is a multiple of 2 so it must be thumb, set bit zero
1753                     code_addr |= 1ull;
1754                 }
1755                 else if (addr_class == eAddressClassCodeAlternateISA)
1756                 {
1757                     // We checked the address and the address claims to be the alternate ISA
1758                     // which means thumb, so set bit zero.
1759                     code_addr |= 1ull;
1760                 }
1761             }
1762             break;
1763         }
1764         break;
1765 
1766     default:
1767         break;
1768     }
1769     return code_addr;
1770 }
1771 
1772 lldb::addr_t
1773 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1774 {
1775     addr_t opcode_addr = load_addr;
1776     switch (m_arch.GetMachine())
1777     {
1778     case llvm::Triple::arm:
1779     case llvm::Triple::thumb:
1780         switch (addr_class)
1781         {
1782         case eAddressClassData:
1783         case eAddressClassDebug:
1784             return LLDB_INVALID_ADDRESS;
1785 
1786         case eAddressClassInvalid:
1787         case eAddressClassUnknown:
1788         case eAddressClassCode:
1789         case eAddressClassCodeAlternateISA:
1790         case eAddressClassRuntime:
1791             opcode_addr &= ~(1ull);
1792             break;
1793         }
1794         break;
1795 
1796     default:
1797         break;
1798     }
1799     return opcode_addr;
1800 }
1801 
1802 lldb::user_id_t
1803 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1804 {
1805     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1806     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1807     m_stop_hooks[new_uid] = new_hook_sp;
1808     return new_uid;
1809 }
1810 
1811 bool
1812 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1813 {
1814     size_t num_removed;
1815     num_removed = m_stop_hooks.erase (user_id);
1816     if (num_removed == 0)
1817         return false;
1818     else
1819         return true;
1820 }
1821 
1822 void
1823 Target::RemoveAllStopHooks ()
1824 {
1825     m_stop_hooks.clear();
1826 }
1827 
1828 Target::StopHookSP
1829 Target::GetStopHookByID (lldb::user_id_t user_id)
1830 {
1831     StopHookSP found_hook;
1832 
1833     StopHookCollection::iterator specified_hook_iter;
1834     specified_hook_iter = m_stop_hooks.find (user_id);
1835     if (specified_hook_iter != m_stop_hooks.end())
1836         found_hook = (*specified_hook_iter).second;
1837     return found_hook;
1838 }
1839 
1840 bool
1841 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1842 {
1843     StopHookCollection::iterator specified_hook_iter;
1844     specified_hook_iter = m_stop_hooks.find (user_id);
1845     if (specified_hook_iter == m_stop_hooks.end())
1846         return false;
1847 
1848     (*specified_hook_iter).second->SetIsActive (active_state);
1849     return true;
1850 }
1851 
1852 void
1853 Target::SetAllStopHooksActiveState (bool active_state)
1854 {
1855     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1856     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1857     {
1858         (*pos).second->SetIsActive (active_state);
1859     }
1860 }
1861 
1862 void
1863 Target::RunStopHooks ()
1864 {
1865     if (m_suppress_stop_hooks)
1866         return;
1867 
1868     if (!m_process_sp)
1869         return;
1870 
1871     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
1872     // since in that case we do not want to run the stop-hooks
1873     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
1874         return;
1875 
1876     if (m_stop_hooks.empty())
1877         return;
1878 
1879     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1880 
1881     // If there aren't any active stop hooks, don't bother either:
1882     bool any_active_hooks = false;
1883     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1884     {
1885         if ((*pos).second->IsActive())
1886         {
1887             any_active_hooks = true;
1888             break;
1889         }
1890     }
1891     if (!any_active_hooks)
1892         return;
1893 
1894     CommandReturnObject result;
1895 
1896     std::vector<ExecutionContext> exc_ctx_with_reasons;
1897     std::vector<SymbolContext> sym_ctx_with_reasons;
1898 
1899     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1900     size_t num_threads = cur_threadlist.GetSize();
1901     for (size_t i = 0; i < num_threads; i++)
1902     {
1903         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1904         if (cur_thread_sp->ThreadStoppedForAReason())
1905         {
1906             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1907             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1908             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1909         }
1910     }
1911 
1912     // If no threads stopped for a reason, don't run the stop-hooks.
1913     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1914     if (num_exe_ctx == 0)
1915         return;
1916 
1917     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1918     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1919 
1920     bool keep_going = true;
1921     bool hooks_ran = false;
1922     bool print_hook_header;
1923     bool print_thread_header;
1924 
1925     if (num_exe_ctx == 1)
1926         print_thread_header = false;
1927     else
1928         print_thread_header = true;
1929 
1930     if (m_stop_hooks.size() == 1)
1931         print_hook_header = false;
1932     else
1933         print_hook_header = true;
1934 
1935     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1936     {
1937         // result.Clear();
1938         StopHookSP cur_hook_sp = (*pos).second;
1939         if (!cur_hook_sp->IsActive())
1940             continue;
1941 
1942         bool any_thread_matched = false;
1943         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1944         {
1945             if ((cur_hook_sp->GetSpecifier () == NULL
1946                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1947                 && (cur_hook_sp->GetThreadSpecifier() == NULL
1948                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
1949             {
1950                 if (!hooks_ran)
1951                 {
1952                     hooks_ran = true;
1953                 }
1954                 if (print_hook_header && !any_thread_matched)
1955                 {
1956                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
1957                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
1958                                        NULL);
1959                     if (cmd)
1960                         result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd);
1961                     else
1962                         result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID());
1963                     any_thread_matched = true;
1964                 }
1965 
1966                 if (print_thread_header)
1967                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
1968 
1969                 bool stop_on_continue = true;
1970                 bool stop_on_error = true;
1971                 bool echo_commands = false;
1972                 bool print_results = true;
1973                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
1974                                                                       &exc_ctx_with_reasons[i],
1975                                                                       stop_on_continue,
1976                                                                       stop_on_error,
1977                                                                       echo_commands,
1978                                                                       print_results,
1979                                                                       eLazyBoolNo,
1980                                                                       result);
1981 
1982                 // If the command started the target going again, we should bag out of
1983                 // running the stop hooks.
1984                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
1985                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
1986                 {
1987                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID());
1988                     keep_going = false;
1989                 }
1990             }
1991         }
1992     }
1993 
1994     result.GetImmediateOutputStream()->Flush();
1995     result.GetImmediateErrorStream()->Flush();
1996 }
1997 
1998 
1999 //--------------------------------------------------------------
2000 // class Target::StopHook
2001 //--------------------------------------------------------------
2002 
2003 
2004 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2005         UserID (uid),
2006         m_target_sp (target_sp),
2007         m_commands (),
2008         m_specifier_sp (),
2009         m_thread_spec_ap(NULL),
2010         m_active (true)
2011 {
2012 }
2013 
2014 Target::StopHook::StopHook (const StopHook &rhs) :
2015         UserID (rhs.GetID()),
2016         m_target_sp (rhs.m_target_sp),
2017         m_commands (rhs.m_commands),
2018         m_specifier_sp (rhs.m_specifier_sp),
2019         m_thread_spec_ap (NULL),
2020         m_active (rhs.m_active)
2021 {
2022     if (rhs.m_thread_spec_ap.get() != NULL)
2023         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2024 }
2025 
2026 
2027 Target::StopHook::~StopHook ()
2028 {
2029 }
2030 
2031 void
2032 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2033 {
2034     m_thread_spec_ap.reset (specifier);
2035 }
2036 
2037 
2038 void
2039 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2040 {
2041     int indent_level = s->GetIndentLevel();
2042 
2043     s->SetIndentLevel(indent_level + 2);
2044 
2045     s->Printf ("Hook: %llu\n", GetID());
2046     if (m_active)
2047         s->Indent ("State: enabled\n");
2048     else
2049         s->Indent ("State: disabled\n");
2050 
2051     if (m_specifier_sp)
2052     {
2053         s->Indent();
2054         s->PutCString ("Specifier:\n");
2055         s->SetIndentLevel (indent_level + 4);
2056         m_specifier_sp->GetDescription (s, level);
2057         s->SetIndentLevel (indent_level + 2);
2058     }
2059 
2060     if (m_thread_spec_ap.get() != NULL)
2061     {
2062         StreamString tmp;
2063         s->Indent("Thread:\n");
2064         m_thread_spec_ap->GetDescription (&tmp, level);
2065         s->SetIndentLevel (indent_level + 4);
2066         s->Indent (tmp.GetData());
2067         s->PutCString ("\n");
2068         s->SetIndentLevel (indent_level + 2);
2069     }
2070 
2071     s->Indent ("Commands: \n");
2072     s->SetIndentLevel (indent_level + 4);
2073     uint32_t num_commands = m_commands.GetSize();
2074     for (uint32_t i = 0; i < num_commands; i++)
2075     {
2076         s->Indent(m_commands.GetStringAtIndex(i));
2077         s->PutCString ("\n");
2078     }
2079     s->SetIndentLevel (indent_level);
2080 }
2081 
2082 //--------------------------------------------------------------
2083 // class TargetProperties
2084 //--------------------------------------------------------------
2085 
2086 OptionEnumValueElement
2087 lldb_private::g_dynamic_value_types[] =
2088 {
2089     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2090     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2091     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2092     { 0, NULL, NULL }
2093 };
2094 
2095 static PropertyDefinition
2096 g_properties[] =
2097 {
2098     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2099     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2100     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2101     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2102     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2103     { "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 "
2104       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2105       "some part (starting at the root) of the path to the file when it was built, "
2106       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2107       "Each element of the array is checked in order and the first one that results in a match wins." },
2108     { "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." },
2109     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2110     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2111     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2112     { "run-args"                           , OptionValue::eTypeArgs      , false, 0                         , NULL, NULL, "A list containing all the arguments to be passed to the executable when it is run." },
2113     { "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." },
2114     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2115     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2116     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2117     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2118     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2119     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2120     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2121 };
2122 enum
2123 {
2124     ePropertyDefaultArch,
2125     ePropertyExprPrefix,
2126     ePropertyPreferDynamic,
2127     ePropertyEnableSynthetic,
2128     ePropertySkipPrologue,
2129     ePropertySourceMap,
2130     ePropertyExecutableSearchPaths,
2131     ePropertyMaxChildrenCount,
2132     ePropertyMaxSummaryLength,
2133     ePropertyBreakpointUseAvoidList,
2134     ePropertyRunArgs,
2135     ePropertyEnvVars,
2136     ePropertyInheritEnv,
2137     ePropertyInputPath,
2138     ePropertyOutputPath,
2139     ePropertyErrorPath,
2140     ePropertyDisableASLR,
2141     ePropertyDisableSTDIO
2142 };
2143 
2144 
2145 class TargetOptionValueProperties : public OptionValueProperties
2146 {
2147 public:
2148     TargetOptionValueProperties (const ConstString &name) :
2149         OptionValueProperties (name),
2150         m_target (NULL),
2151         m_got_host_env (false)
2152     {
2153     }
2154 
2155     // This constructor is used when creating TargetOptionValueProperties when it
2156     // is part of a new lldb_private::Target instance. It will copy all current
2157     // global property values as needed
2158     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2159         OptionValueProperties(*target_properties_sp->GetValueProperties()),
2160         m_target (target),
2161         m_got_host_env (false)
2162     {
2163     }
2164 
2165     virtual const Property *
2166     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2167     {
2168         // When gettings the value for a key from the target options, we will always
2169         // try and grab the setting from the current target if there is one. Else we just
2170         // use the one from this instance.
2171         if (idx == ePropertyEnvVars)
2172             GetHostEnvironmentIfNeeded ();
2173 
2174         if (exe_ctx)
2175         {
2176             Target *target = exe_ctx->GetTargetPtr();
2177             if (target)
2178             {
2179                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2180                 if (this != target_properties)
2181                     return target_properties->ProtectedGetPropertyAtIndex (idx);
2182             }
2183         }
2184         return ProtectedGetPropertyAtIndex (idx);
2185     }
2186 protected:
2187 
2188     void
2189     GetHostEnvironmentIfNeeded () const
2190     {
2191         if (!m_got_host_env)
2192         {
2193             if (m_target)
2194             {
2195                 m_got_host_env = true;
2196                 const uint32_t idx = ePropertyInheritEnv;
2197                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2198                 {
2199                     PlatformSP platform_sp (m_target->GetPlatform());
2200                     if (platform_sp)
2201                     {
2202                         StringList env;
2203                         if (platform_sp->GetEnvironment(env))
2204                         {
2205                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2206                             if (env_dict)
2207                             {
2208                                 const bool can_replace = false;
2209                                 const size_t envc = env.GetSize();
2210                                 for (size_t idx=0; idx<envc; idx++)
2211                                 {
2212                                     const char *env_entry = env.GetStringAtIndex (idx);
2213                                     if (env_entry)
2214                                     {
2215                                         const char *equal_pos = ::strchr(env_entry, '=');
2216                                         ConstString key;
2217                                         // It is ok to have environment variables with no values
2218                                         const char *value = NULL;
2219                                         if (equal_pos)
2220                                         {
2221                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2222                                             if (equal_pos[1])
2223                                                 value = equal_pos + 1;
2224                                         }
2225                                         else
2226                                         {
2227                                             key.SetCString(env_entry);
2228                                         }
2229                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
2230                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2231                                     }
2232                                 }
2233                             }
2234                         }
2235                     }
2236                 }
2237             }
2238         }
2239     }
2240     Target *m_target;
2241     mutable bool m_got_host_env;
2242 };
2243 
2244 TargetProperties::TargetProperties (Target *target) :
2245     Properties ()
2246 {
2247     if (target)
2248     {
2249         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2250     }
2251     else
2252     {
2253         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2254         m_collection_sp->Initialize(g_properties);
2255         m_collection_sp->AppendProperty(ConstString("process"),
2256                                         ConstString("Settings specify to processes."),
2257                                         true,
2258                                         Process::GetGlobalProperties()->GetValueProperties());
2259     }
2260 }
2261 
2262 TargetProperties::~TargetProperties ()
2263 {
2264 }
2265 ArchSpec
2266 TargetProperties::GetDefaultArchitecture () const
2267 {
2268     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2269     if (value)
2270         return value->GetCurrentValue();
2271     return ArchSpec();
2272 }
2273 
2274 void
2275 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2276 {
2277     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2278     if (value)
2279         return value->SetCurrentValue(arch, true);
2280 }
2281 
2282 lldb::DynamicValueType
2283 TargetProperties::GetPreferDynamicValue() const
2284 {
2285     const uint32_t idx = ePropertyPreferDynamic;
2286     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2287 }
2288 
2289 bool
2290 TargetProperties::GetDisableASLR () const
2291 {
2292     const uint32_t idx = ePropertyDisableASLR;
2293     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2294 }
2295 
2296 void
2297 TargetProperties::SetDisableASLR (bool b)
2298 {
2299     const uint32_t idx = ePropertyDisableASLR;
2300     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2301 }
2302 
2303 bool
2304 TargetProperties::GetDisableSTDIO () const
2305 {
2306     const uint32_t idx = ePropertyDisableSTDIO;
2307     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2308 }
2309 
2310 void
2311 TargetProperties::SetDisableSTDIO (bool b)
2312 {
2313     const uint32_t idx = ePropertyDisableSTDIO;
2314     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2315 }
2316 
2317 bool
2318 TargetProperties::GetRunArguments (Args &args) const
2319 {
2320     const uint32_t idx = ePropertyRunArgs;
2321     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2322 }
2323 
2324 void
2325 TargetProperties::SetRunArguments (const Args &args)
2326 {
2327     const uint32_t idx = ePropertyRunArgs;
2328     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2329 }
2330 
2331 size_t
2332 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2333 {
2334     const uint32_t idx = ePropertyEnvVars;
2335     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2336 }
2337 
2338 bool
2339 TargetProperties::GetSkipPrologue() const
2340 {
2341     const uint32_t idx = ePropertySkipPrologue;
2342     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2343 }
2344 
2345 PathMappingList &
2346 TargetProperties::GetSourcePathMap () const
2347 {
2348     const uint32_t idx = ePropertySourceMap;
2349     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2350     assert(option_value);
2351     return option_value->GetCurrentValue();
2352 }
2353 
2354 FileSpecList &
2355 TargetProperties::GetExecutableSearchPaths ()
2356 {
2357     const uint32_t idx = ePropertyExecutableSearchPaths;
2358     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2359     assert(option_value);
2360     return option_value->GetCurrentValue();
2361 }
2362 
2363 bool
2364 TargetProperties::GetEnableSyntheticValue () const
2365 {
2366     const uint32_t idx = ePropertyEnableSynthetic;
2367     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2368 }
2369 
2370 uint32_t
2371 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2372 {
2373     const uint32_t idx = ePropertyMaxChildrenCount;
2374     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2375 }
2376 
2377 uint32_t
2378 TargetProperties::GetMaximumSizeOfStringSummary() const
2379 {
2380     const uint32_t idx = ePropertyMaxSummaryLength;
2381     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2382 }
2383 
2384 FileSpec
2385 TargetProperties::GetStandardInputPath () const
2386 {
2387     const uint32_t idx = ePropertyInputPath;
2388     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2389 }
2390 
2391 void
2392 TargetProperties::SetStandardInputPath (const char *p)
2393 {
2394     const uint32_t idx = ePropertyInputPath;
2395     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2396 }
2397 
2398 FileSpec
2399 TargetProperties::GetStandardOutputPath () const
2400 {
2401     const uint32_t idx = ePropertyOutputPath;
2402     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2403 }
2404 
2405 void
2406 TargetProperties::SetStandardOutputPath (const char *p)
2407 {
2408     const uint32_t idx = ePropertyOutputPath;
2409     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2410 }
2411 
2412 FileSpec
2413 TargetProperties::GetStandardErrorPath () const
2414 {
2415     const uint32_t idx = ePropertyErrorPath;
2416     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2417 }
2418 
2419 const char *
2420 TargetProperties::GetExpressionPrefixContentsAsCString ()
2421 {
2422     const uint32_t idx = ePropertyExprPrefix;
2423     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
2424     if (file)
2425         return (const char *)file->GetFileContents()->GetBytes();
2426     return NULL;
2427 }
2428 
2429 void
2430 TargetProperties::SetStandardErrorPath (const char *p)
2431 {
2432     const uint32_t idx = ePropertyErrorPath;
2433     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2434 }
2435 
2436 bool
2437 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
2438 {
2439     const uint32_t idx = ePropertyBreakpointUseAvoidList;
2440     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2441 }
2442 
2443 const TargetPropertiesSP &
2444 Target::GetGlobalProperties()
2445 {
2446     static TargetPropertiesSP g_settings_sp;
2447     if (!g_settings_sp)
2448     {
2449         g_settings_sp.reset (new TargetProperties (NULL));
2450     }
2451     return g_settings_sp;
2452 }
2453 
2454 const ConstString &
2455 Target::TargetEventData::GetFlavorString ()
2456 {
2457     static ConstString g_flavor ("Target::TargetEventData");
2458     return g_flavor;
2459 }
2460 
2461 const ConstString &
2462 Target::TargetEventData::GetFlavor () const
2463 {
2464     return TargetEventData::GetFlavorString ();
2465 }
2466 
2467 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2468     EventData(),
2469     m_target_sp (new_target_sp)
2470 {
2471 }
2472 
2473 Target::TargetEventData::~TargetEventData()
2474 {
2475 
2476 }
2477 
2478 void
2479 Target::TargetEventData::Dump (Stream *s) const
2480 {
2481 
2482 }
2483 
2484 const TargetSP
2485 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2486 {
2487     TargetSP target_sp;
2488 
2489     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2490     if (data)
2491         target_sp = data->m_target_sp;
2492 
2493     return target_sp;
2494 }
2495 
2496 const Target::TargetEventData *
2497 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2498 {
2499     if (event_ptr)
2500     {
2501         const EventData *event_data = event_ptr->GetData();
2502         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2503             return static_cast <const TargetEventData *> (event_ptr->GetData());
2504     }
2505     return NULL;
2506 }
2507 
2508