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