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