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