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