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