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